diff --git a/.changeset/angry-apricots-invite.md b/.changeset/angry-apricots-invite.md new file mode 100644 index 000000000000..18db7ab25249 --- /dev/null +++ b/.changeset/angry-apricots-invite.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fixes HMR of CSS that is imported from astro, when using the static build flag diff --git a/.changeset/loud-seals-camp.md b/.changeset/loud-seals-camp.md new file mode 100644 index 000000000000..67dd8dff2d89 --- /dev/null +++ b/.changeset/loud-seals-camp.md @@ -0,0 +1,5 @@ +--- +'astro': minor +--- + +Upgrade `vite` to `2.8.x`, unvendoring `vite` and bringing Astro up-to-date with the ecosystem diff --git a/.changeset/many-berries-bake.md b/.changeset/many-berries-bake.md new file mode 100644 index 000000000000..5c77ff973b1d --- /dev/null +++ b/.changeset/many-berries-bake.md @@ -0,0 +1,7 @@ +--- +'@astrojs/renderer-svelte': minor +'@astrojs/renderer-vue': minor +'@astrojs/renderer-solid': minor +--- + +Upgrade to vite@2.8.x diff --git a/examples/with-nanostores/src/components/AdminsPreact.jsx b/examples/with-nanostores/src/components/AdminsPreact.jsx deleted file mode 100644 index 2f93ed437e27..000000000000 --- a/examples/with-nanostores/src/components/AdminsPreact.jsx +++ /dev/null @@ -1,30 +0,0 @@ -import { h, Fragment } from 'preact'; -import { useStore } from '@nanostores/preact'; - -import { admins } from '../store/admins.js'; -import { counter, increaseCounter, decreaseCounter } from '../store/counter.js'; - -const AdminsPreact = () => { - const list = useStore(admins); - const count = useStore(counter); - - return ( - <> -

Preact

- -
-

Counter

-

{count.value}

- - -
-
- - ); -}; - -export default AdminsPreact; diff --git a/examples/with-nanostores/src/pages/index.astro b/examples/with-nanostores/src/pages/index.astro index 424384933108..5aba10e8ad60 100644 --- a/examples/with-nanostores/src/pages/index.astro +++ b/examples/with-nanostores/src/pages/index.astro @@ -3,7 +3,6 @@ import AdminsReact from '../components/AdminsReact.jsx'; import AdminsSvelte from '../components/AdminsSvelte.svelte'; import AdminsVue from '../components/AdminsVue.vue'; -import AdminsPreact from '../components/AdminsPreact.jsx'; import AdminsSolid from '../components/AdminsSolid.jsx'; // Full Astro Component Syntax: @@ -46,7 +45,6 @@ import AdminsSolid from '../components/AdminsSolid.jsx'; - diff --git a/packages/astro/package.json b/packages/astro/package.json index 13907ed3560f..37af252838d2 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -66,18 +66,16 @@ "@astropub/webapi": "^0.10.1", "@babel/core": "^7.15.8", "@babel/traverse": "^7.15.4", - "@proload/core": "^0.2.1", + "@proload/core": "^0.2.2", "@proload/plugin-tsm": "^0.1.0", "@types/babel__core": "^7.1.15", "@types/debug": "^4.1.7", "@web/parse5-utils": "^1.3.0", - "astring": "^1.7.5", "ci-info": "^3.2.0", "common-ancestor-path": "^1.0.1", "eol": "^0.9.1", "es-module-lexer": "^0.9.3", "esbuild": "0.13.7", - "estree-util-value-to-estree": "^1.2.0", "estree-walker": "^3.0.0", "fast-glob": "^3.2.7", "fast-xml-parser": "^4.0.0-beta.3", @@ -93,10 +91,11 @@ "prismjs": "^1.25.0", "rehype-slug": "^5.0.0", "resolve": "^1.20.0", - "rollup": "^2.57.0", - "sass": "^1.43.4", + "rollup": "^2.64.0", + "sass": "^1.49.0", "semver": "^7.3.5", "send": "^0.17.1", + "serialize-javascript": "^6.0.0", "shiki": "^0.10.0", "shorthash": "^0.0.2", "slash": "^4.0.0", @@ -106,7 +105,7 @@ "strip-ansi": "^7.0.1", "supports-esm": "^1.0.0", "tsconfig-resolver": "^3.0.1", - "vite": "~2.6.10", + "vite": "^2.8.0-beta.7", "yargs-parser": "^21.0.0", "zod": "^3.8.1" }, @@ -125,9 +124,8 @@ "@types/yargs-parser": "^20.2.1", "chai": "^4.3.4", "cheerio": "^1.0.0-rc.10", - "hast-util-select": "^5.0.1", - "mocha": "^9.1.3", - "vite": "~2.6.10" + "execa": "^6.0.0", + "mocha": "^9.1.3" }, "engines": { "node": "^14.15.0 || >=16.0.0", diff --git a/packages/astro/src/@types/serialize-javascript.d.ts b/packages/astro/src/@types/serialize-javascript.d.ts new file mode 100644 index 000000000000..35ee081b2f5b --- /dev/null +++ b/packages/astro/src/@types/serialize-javascript.d.ts @@ -0,0 +1,3 @@ +declare module 'serialize-javascript' { + export default function serialize(value: any): string; +} diff --git a/packages/astro/src/core/create-vite.ts b/packages/astro/src/core/create-vite.ts index b458bea2851c..76f1c11b5bc0 100644 --- a/packages/astro/src/core/create-vite.ts +++ b/packages/astro/src/core/create-vite.ts @@ -16,8 +16,8 @@ import { resolveDependency } from './util.js'; const ALWAYS_EXTERNAL = new Set([ ...builtinModules.map((name) => `node:${name}`), '@sveltejs/vite-plugin-svelte', - 'estree-util-value-to-estree', 'micromark-util-events-to-acorn', + 'serialize-javascript', 'node-fetch', 'prismjs', 'shiki', @@ -25,9 +25,6 @@ const ALWAYS_EXTERNAL = new Set([ 'unified', 'whatwg-url', ]); -const ALWAYS_NOEXTERNAL = new Set([ - 'astro', // This is only because Vite's native ESM doesn't resolve "exports" correctly. -]); // note: ssr is still an experimental API hence the type omission export type ViteConfigWithSSR = vite.InlineConfig & { ssr?: { external?: string[]; noExternal?: string[] } }; @@ -72,7 +69,7 @@ export async function createVite(inlineConfig: ViteConfigWithSSR, { astroConfig, // Note: SSR API is in beta (https://vitejs.dev/guide/ssr.html) ssr: { external: [...ALWAYS_EXTERNAL], - noExternal: [...ALWAYS_NOEXTERNAL], + noExternal: [], }, }; diff --git a/packages/astro/src/core/vite.ts b/packages/astro/src/core/vite.ts index 7ceb4d8a0cdb..dee46a36800d 100644 --- a/packages/astro/src/core/vite.ts +++ b/packages/astro/src/core/vite.ts @@ -1,2 +1,2 @@ -export * from '../../vendor/vite/dist/node/index.js'; -export { default } from '../../vendor/vite/dist/node/index.js'; +export * from 'vite'; +export { default } from 'vite'; diff --git a/packages/astro/src/runtime/server/hydration.ts b/packages/astro/src/runtime/server/hydration.ts index cd786999dd04..b339b934f090 100644 --- a/packages/astro/src/runtime/server/hydration.ts +++ b/packages/astro/src/runtime/server/hydration.ts @@ -1,34 +1,12 @@ import type { AstroComponentMetadata } from '../../@types/astro'; import type { SSRElement, SSRResult } from '../../@types/astro'; -import { valueToEstree } from 'estree-util-value-to-estree'; -import * as astring from 'astring'; import { hydrationSpecifier, serializeListValue } from './util.js'; - -const { generate, GENERATOR } = astring; - -// INVESTIGATE: What features are we getting from this that we need? -// JSON.stringify has a "replacer" argument. -// A more robust version alternative to `JSON.stringify` that can handle most values -// see https://github.com/remcohaszing/estree-util-value-to-estree#readme -const customGenerator: astring.Generator = { - ...GENERATOR, - Literal(node, state) { - if (node.raw != null) { - // escape closing script tags in strings so browsers wouldn't interpret them as - // closing the actual end tag in HTML - state.write(node.raw.replace('', '<\\/script>')); - } else { - GENERATOR.Literal(node, state); - } - }, -}; +import serializeJavaScript from 'serialize-javascript'; // Serializes props passed into a component so that they can be reused during hydration. // The value is any export function serializeProps(value: any) { - return generate(valueToEstree(value), { - generator: customGenerator, - }); + return serializeJavaScript(value); } const HydrationDirectives = ['load', 'idle', 'media', 'visible', 'only']; diff --git a/packages/astro/src/vite-plugin-astro/compile.ts b/packages/astro/src/vite-plugin-astro/compile.ts index d52a8be17785..7eb0eddc4304 100644 --- a/packages/astro/src/vite-plugin-astro/compile.ts +++ b/packages/astro/src/vite-plugin-astro/compile.ts @@ -12,23 +12,9 @@ type CompilationCache = Map; const configCache = new WeakMap(); -// https://github.com/vitejs/vite/discussions/5109#discussioncomment-1450726 -function isSSR(options: undefined | boolean | { ssr: boolean }): boolean { - if (options === undefined) { - return false; - } - if (typeof options === 'boolean') { - return options; - } - if (typeof options == 'object') { - return !!options.ssr; - } - return false; -} - type CompileResult = TransformResult & { rawCSSDeps: Set }; -async function compile(config: AstroConfig, filename: string, source: string, viteTransform: TransformHook, opts: boolean | undefined): Promise { +async function compile(config: AstroConfig, filename: string, source: string, viteTransform: TransformHook, opts: { ssr: boolean }): Promise { // pages and layouts should be transformed as full documents (implicit etc) // everything else is treated as a fragment const filenameURL = new URL(`file://${filename}`); @@ -69,7 +55,7 @@ async function compile(config: AstroConfig, filename: string, source: string, vi lang, id: normalizedID, transformHook: viteTransform, - ssr: isSSR(opts), + ssr: opts.ssr, }); let map: SourceMapInput | undefined; @@ -119,7 +105,7 @@ export async function cachedCompilation( filename: string, source: string | null, viteTransform: TransformHook, - opts: boolean | undefined + opts: { ssr: boolean } ): Promise { let cache: CompilationCache; if (!configCache.has(config)) { diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index 1986803881db..5f6138b04840 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -64,15 +64,20 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu let { filename, query } = parseAstroRequest(id); if (query.astro) { if (query.type === 'style') { + if (filename.startsWith('/@fs')) { + filename = filename.slice('/@fs'.length); + } else if (filename.startsWith('/') && !ancestor(filename, config.projectRoot.pathname)) { + filename = new URL('.' + filename, config.projectRoot).pathname; + } + if (typeof query.index === 'undefined') { throw new Error(`Requests for Astro CSS must include an index.`); } - const transformResult = await cachedCompilation(config, normalizeFilename(filename), null, viteTransform, opts); + const transformResult = await cachedCompilation(config, normalizeFilename(filename), null, viteTransform, { ssr: Boolean(opts?.ssr) }); // Track any CSS dependencies so that HMR is triggered when they change. await trackCSSDependencies.call(this, { viteDevServer, id, filename, deps: transformResult.rawCSSDeps }); - const csses = transformResult.css; const code = csses[query.index]; @@ -84,7 +89,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu throw new Error(`Requests for hoisted scripts must include an index`); } - const transformResult = await cachedCompilation(config, normalizeFilename(filename), null, viteTransform, opts); + const transformResult = await cachedCompilation(config, normalizeFilename(filename), null, viteTransform, { ssr: Boolean(opts?.ssr) }); const scripts = transformResult.scripts; const hoistedScript = scripts[query.index]; @@ -106,7 +111,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu } try { - const transformResult = await cachedCompilation(config, id, source, viteTransform, opts); + const transformResult = await cachedCompilation(config, id, source, viteTransform, { ssr: Boolean(opts?.ssr) }); // Compile all TypeScript to JavaScript. // Also, catches invalid JS/TS in the compiled output before returning. diff --git a/packages/astro/src/vite-plugin-jsx/index.ts b/packages/astro/src/vite-plugin-jsx/index.ts index 642aa865d2f5..46d92fef97a3 100644 --- a/packages/astro/src/vite-plugin-jsx/index.ts +++ b/packages/astro/src/vite-plugin-jsx/index.ts @@ -24,21 +24,6 @@ const IMPORT_STATEMENTS: Record = { // be careful about esbuild not treating h, React, Fragment, etc. as unused. const PREVENT_UNUSED_IMPORTS = ';;(React,Fragment,h);'; -// This check on a flexible "options" object is needed because Vite uses this flexible argument for ssr. -// More context: https://github.com/vitejs/vite/discussions/5109#discussioncomment-1450726 -function isSSR(options: undefined | boolean | { ssr: boolean }): boolean { - if (options === undefined) { - return false; - } - if (typeof options === 'boolean') { - return options; - } - if (typeof options == 'object') { - return !!options.ssr; - } - return false; -} - function getEsbuildLoader(fileExt: string): string { return fileExt.substr(1); } @@ -103,8 +88,8 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin configResolved(resolvedConfig) { viteConfig = resolvedConfig; }, - async transform(code, id, ssrOrOptions) { - const ssr = isSSR(ssrOrOptions); + async transform(code, id, opts) { + const ssr = Boolean(opts?.ssr); if (!JSX_EXTENSIONS.has(path.extname(id))) { return null; } diff --git a/packages/astro/test/0-css.test.js b/packages/astro/test/0-css.test.js index 6c55a360da91..1ca8acf2e164 100644 --- a/packages/astro/test/0-css.test.js +++ b/packages/astro/test/0-css.test.js @@ -277,8 +277,13 @@ describe('CSS', function () { expect((await fixture.fetch(href)).status).to.equal(200); }); - it('resolved imported CSS with ?url', async () => { + // Skipped until upstream fix lands + // Our fix: https://github.com/withastro/astro/pull/2106 + // OG Vite PR: https://github.com/vitejs/vite/pull/5940 + // Next Vite PR: https://github.com/vitejs/vite/pull/5796 + it.skip('resolved imported CSS with ?url', async () => { const href = $('link[href$="imported-url.css"]').attr('href'); + expect(href).to.be.ok; expect((await fixture.fetch(href)).status).to.equal(200); }); diff --git a/packages/astro/test/fixtures/custom-elements/my-component-lib/index.js b/packages/astro/test/fixtures/custom-elements/my-component-lib/index.js index 7054d021969f..79ebae558895 100644 --- a/packages/astro/test/fixtures/custom-elements/my-component-lib/index.js +++ b/packages/astro/test/fixtures/custom-elements/my-component-lib/index.js @@ -10,7 +10,8 @@ export default { viteConfig() { return { optimizeDeps: { - include: ['@astrojs/test-custom-element-renderer/polyfill.js', '@astrojs/test-custom-element-renderer/hydration-polyfill.js'] + include: ['@astrojs/test-custom-element-renderer/polyfill.js', '@astrojs/test-custom-element-renderer/hydration-polyfill.js'], + exclude: ['@astrojs/test-custom-element-renderer/server.js'] } } } diff --git a/packages/astro/test/fixtures/static build/pkg/package.json b/packages/astro/test/fixtures/static build/pkg/package.json index 8d84a91a1709..5d202516fd48 100644 --- a/packages/astro/test/fixtures/static build/pkg/package.json +++ b/packages/astro/test/fixtures/static build/pkg/package.json @@ -1,11 +1,11 @@ { "name": "@astrojs/test-static-build-pkg", - "main": "./oops.js", - "version": "0.0.2", + "main": "./oops.cjs", + "version": "0.0.3", "exports": { ".": { - "import": "./pkg.js", - "require": "./oops.js" + "import": "./pkg.mjs", + "require": "./oops.cjs" } } } diff --git a/packages/astro/test/fixtures/static build/pkg/pkg.js b/packages/astro/test/fixtures/static build/pkg/pkg.mjs similarity index 100% rename from packages/astro/test/fixtures/static build/pkg/pkg.js rename to packages/astro/test/fixtures/static build/pkg/pkg.mjs diff --git a/packages/astro/vendor/vite/LICENSE.md b/packages/astro/vendor/vite/LICENSE.md deleted file mode 100644 index 73e3dcd0a162..000000000000 --- a/packages/astro/vendor/vite/LICENSE.md +++ /dev/null @@ -1,2150 +0,0 @@ -# Vite core license -Vite is released under the MIT license: - -MIT License - -Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -# Licenses of bundled dependencies -The published Vite artifact additionally contains code with the following licenses: -Apache-2.0, BSD-2-Clause, BSD-3-Clause, CC0-1.0, ISC, MIT, (BSD-3-Clause OR GPL-2.0) - -# Bundled dependencies: -## @ampproject/remapping -License: Apache-2.0 -By: Justin Ridgewell -Repository: git+https://github.com/ampproject/remapping.git - -> Apache License -> Version 2.0, January 2004 -> http://www.apache.org/licenses/ -> -> TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION -> -> 1. Definitions. -> -> "License" shall mean the terms and conditions for use, reproduction, -> and distribution as defined by Sections 1 through 9 of this document. -> -> "Licensor" shall mean the copyright owner or entity authorized by -> the copyright owner that is granting the License. -> -> "Legal Entity" shall mean the union of the acting entity and all -> other entities that control, are controlled by, or are under common -> control with that entity. For the purposes of this definition, -> "control" means (i) the power, direct or indirect, to cause the -> direction or management of such entity, whether by contract or -> otherwise, or (ii) ownership of fifty percent (50%) or more of the -> outstanding shares, or (iii) beneficial ownership of such entity. -> -> "You" (or "Your") shall mean an individual or Legal Entity -> exercising permissions granted by this License. -> -> "Source" form shall mean the preferred form for making modifications, -> including but not limited to software source code, documentation -> source, and configuration files. -> -> "Object" form shall mean any form resulting from mechanical -> transformation or translation of a Source form, including but -> not limited to compiled object code, generated documentation, -> and conversions to other media types. -> -> "Work" shall mean the work of authorship, whether in Source or -> Object form, made available under the License, as indicated by a -> copyright notice that is included in or attached to the work -> (an example is provided in the Appendix below). -> -> "Derivative Works" shall mean any work, whether in Source or Object -> form, that is based on (or derived from) the Work and for which the -> editorial revisions, annotations, elaborations, or other modifications -> represent, as a whole, an original work of authorship. For the purposes -> of this License, Derivative Works shall not include works that remain -> separable from, or merely link (or bind by name) to the interfaces of, -> the Work and Derivative Works thereof. -> -> "Contribution" shall mean any work of authorship, including -> the original version of the Work and any modifications or additions -> to that Work or Derivative Works thereof, that is intentionally -> submitted to Licensor for inclusion in the Work by the copyright owner -> or by an individual or Legal Entity authorized to submit on behalf of -> the copyright owner. For the purposes of this definition, "submitted" -> means any form of electronic, verbal, or written communication sent -> to the Licensor or its representatives, including but not limited to -> communication on electronic mailing lists, source code control systems, -> and issue tracking systems that are managed by, or on behalf of, the -> Licensor for the purpose of discussing and improving the Work, but -> excluding communication that is conspicuously marked or otherwise -> designated in writing by the copyright owner as "Not a Contribution." -> -> "Contributor" shall mean Licensor and any individual or Legal Entity -> on behalf of whom a Contribution has been received by Licensor and -> subsequently incorporated within the Work. -> -> 2. Grant of Copyright License. Subject to the terms and conditions of -> this License, each Contributor hereby grants to You a perpetual, -> worldwide, non-exclusive, no-charge, royalty-free, irrevocable -> copyright license to reproduce, prepare Derivative Works of, -> publicly display, publicly perform, sublicense, and distribute the -> Work and such Derivative Works in Source or Object form. -> -> 3. Grant of Patent License. Subject to the terms and conditions of -> this License, each Contributor hereby grants to You a perpetual, -> worldwide, non-exclusive, no-charge, royalty-free, irrevocable -> (except as stated in this section) patent license to make, have made, -> use, offer to sell, sell, import, and otherwise transfer the Work, -> where such license applies only to those patent claims licensable -> by such Contributor that are necessarily infringed by their -> Contribution(s) alone or by combination of their Contribution(s) -> with the Work to which such Contribution(s) was submitted. If You -> institute patent litigation against any entity (including a -> cross-claim or counterclaim in a lawsuit) alleging that the Work -> or a Contribution incorporated within the Work constitutes direct -> or contributory patent infringement, then any patent licenses -> granted to You under this License for that Work shall terminate -> as of the date such litigation is filed. -> -> 4. Redistribution. You may reproduce and distribute copies of the -> Work or Derivative Works thereof in any medium, with or without -> modifications, and in Source or Object form, provided that You -> meet the following conditions: -> -> (a) You must give any other recipients of the Work or -> Derivative Works a copy of this License; and -> -> (b) You must cause any modified files to carry prominent notices -> stating that You changed the files; and -> -> (c) You must retain, in the Source form of any Derivative Works -> that You distribute, all copyright, patent, trademark, and -> attribution notices from the Source form of the Work, -> excluding those notices that do not pertain to any part of -> the Derivative Works; and -> -> (d) If the Work includes a "NOTICE" text file as part of its -> distribution, then any Derivative Works that You distribute must -> include a readable copy of the attribution notices contained -> within such NOTICE file, excluding those notices that do not -> pertain to any part of the Derivative Works, in at least one -> of the following places: within a NOTICE text file distributed -> as part of the Derivative Works; within the Source form or -> documentation, if provided along with the Derivative Works; or, -> within a display generated by the Derivative Works, if and -> wherever such third-party notices normally appear. The contents -> of the NOTICE file are for informational purposes only and -> do not modify the License. You may add Your own attribution -> notices within Derivative Works that You distribute, alongside -> or as an addendum to the NOTICE text from the Work, provided -> that such additional attribution notices cannot be construed -> as modifying the License. -> -> You may add Your own copyright statement to Your modifications and -> may provide additional or different license terms and conditions -> for use, reproduction, or distribution of Your modifications, or -> for any such Derivative Works as a whole, provided Your use, -> reproduction, and distribution of the Work otherwise complies with -> the conditions stated in this License. -> -> 5. Submission of Contributions. Unless You explicitly state otherwise, -> any Contribution intentionally submitted for inclusion in the Work -> by You to the Licensor shall be under the terms and conditions of -> this License, without any additional terms or conditions. -> Notwithstanding the above, nothing herein shall supersede or modify -> the terms of any separate license agreement you may have executed -> with Licensor regarding such Contributions. -> -> 6. Trademarks. This License does not grant permission to use the trade -> names, trademarks, service marks, or product names of the Licensor, -> except as required for reasonable and customary use in describing the -> origin of the Work and reproducing the content of the NOTICE file. -> -> 7. Disclaimer of Warranty. Unless required by applicable law or -> agreed to in writing, Licensor provides the Work (and each -> Contributor provides its Contributions) on an "AS IS" BASIS, -> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -> implied, including, without limitation, any warranties or conditions -> of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A -> PARTICULAR PURPOSE. You are solely responsible for determining the -> appropriateness of using or redistributing the Work and assume any -> risks associated with Your exercise of permissions under this License. -> -> 8. Limitation of Liability. In no event and under no legal theory, -> whether in tort (including negligence), contract, or otherwise, -> unless required by applicable law (such as deliberate and grossly -> negligent acts) or agreed to in writing, shall any Contributor be -> liable to You for damages, including any direct, indirect, special, -> incidental, or consequential damages of any character arising as a -> result of this License or out of the use or inability to use the -> Work (including but not limited to damages for loss of goodwill, -> work stoppage, computer failure or malfunction, or any and all -> other commercial damages or losses), even if such Contributor -> has been advised of the possibility of such damages. -> -> 9. Accepting Warranty or Additional Liability. While redistributing -> the Work or Derivative Works thereof, You may choose to offer, -> and charge a fee for, acceptance of support, warranty, indemnity, -> or other liability obligations and/or rights consistent with this -> License. However, in accepting such obligations, You may act only -> on Your own behalf and on Your sole responsibility, not on behalf -> of any other Contributor, and only if You agree to indemnify, -> defend, and hold each Contributor harmless for any liability -> incurred by, or claims asserted against, such Contributor by reason -> of your accepting any such warranty or additional liability. -> -> END OF TERMS AND CONDITIONS -> -> APPENDIX: How to apply the Apache License to your work. -> -> To apply the Apache License to your work, attach the following -> boilerplate notice, with the fields enclosed by brackets "[]" -> replaced with your own identifying information. (Don't include -> the brackets!) The text should be enclosed in the appropriate -> comment syntax for the file format. We also recommend that a -> file or class name and description of purpose be included on the -> same "printed page" as the copyright notice for easier -> identification within third-party archives. -> -> Copyright 2019 Google LLC -> -> Licensed under the Apache License, Version 2.0 (the "License"); -> you may not use this file except in compliance with the License. -> You may obtain a copy of the License at -> -> http://www.apache.org/licenses/LICENSE-2.0 -> -> Unless required by applicable law or agreed to in writing, software -> distributed under the License is distributed on an "AS IS" BASIS, -> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -> See the License for the specific language governing permissions and -> limitations under the License. - ---------------------------------------- - -## @nodelib/fs.scandir -License: MIT -Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.scandir - ---------------------------------------- - -## @nodelib/fs.stat -License: MIT -Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat - ---------------------------------------- - -## @nodelib/fs.walk -License: MIT -Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk - ---------------------------------------- - -## @polka/url -License: MIT -By: Luke Edwards -Repository: lukeed/polka - ---------------------------------------- - -## @rollup/plugin-alias -License: MIT -By: Johannes Stein -Repository: rollup/plugins - ---------------------------------------- - -## @rollup/plugin-commonjs -License: MIT -By: Rich Harris -Repository: rollup/plugins - -> The MIT License (MIT) -> -> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## @rollup/plugin-dynamic-import-vars -License: MIT -By: LarsDenBakker -Repository: rollup/plugins - ---------------------------------------- - -## @rollup/pluginutils -License: MIT -By: Rich Harris -Repository: rollup/plugins - ---------------------------------------- - -## @vue/compiler-core -License: MIT -By: Evan You -Repository: git+https://github.com/vuejs/vue-next.git - ---------------------------------------- - -## @vue/compiler-dom -License: MIT -By: Evan You -Repository: git+https://github.com/vuejs/vue-next.git - -> The MIT License (MIT) -> -> Copyright (c) 2018-present, Yuxi (Evan) You -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## @vue/shared -License: MIT -By: Evan You -Repository: git+https://github.com/vuejs/vue-next.git - ---------------------------------------- - -## accepts -License: MIT -By: Douglas Christopher Wilson, Jonathan Ong -Repository: jshttp/accepts - ---------------------------------------- - -## acorn -License: MIT -By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine -Repository: https://github.com/acornjs/acorn.git - -> MIT License -> -> Copyright (C) 2012-2020 by various contributors (see AUTHORS) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## acorn-class-fields -License: MIT -By: Adrian Heine -Repository: https://github.com/acornjs/acorn-class-fields - -> Copyright (C) 2017-2018 by Adrian Heine -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## acorn-private-class-elements -License: MIT -By: Adrian Heine -Repository: https://github.com/acornjs/acorn-private-class-elements - ---------------------------------------- - -## acorn-static-class-features -License: MIT -By: Adrian Heine -Repository: https://github.com/acornjs/acorn-static-class-features - -> Copyright (C) 2017-2018 by Adrian Heine -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## ansi-regex -License: MIT -By: Sindre Sorhus -Repository: chalk/ansi-regex - ---------------------------------------- - -## ansi-styles -License: MIT -By: Sindre Sorhus -Repository: chalk/ansi-styles - ---------------------------------------- - -## anymatch -License: ISC -By: Elan Shanker -Repository: https://github.com/micromatch/anymatch - ---------------------------------------- - -## array-union -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/array-union - ---------------------------------------- - -## balanced-match -License: MIT -By: Julian Gruber -Repository: git://github.com/juliangruber/balanced-match.git - ---------------------------------------- - -## big.js -License: MIT -By: Michael Mclaughlin -Repository: https://github.com/MikeMcl/big.js.git - ---------------------------------------- - -## binary-extensions -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/binary-extensions - ---------------------------------------- - -## brace-expansion -License: MIT -By: Julian Gruber -Repository: git://github.com/juliangruber/brace-expansion.git - ---------------------------------------- - -## braces -License: MIT -By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm -Repository: micromatch/braces - ---------------------------------------- - -## builtin-modules -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/builtin-modules - -> MIT License -> -> Copyright (c) Sindre Sorhus (https://sindresorhus.com) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. - ---------------------------------------- - -## bytes -License: MIT -By: TJ Holowaychuk, Jed Watson, Théo FIDRY -Repository: visionmedia/bytes.js - ---------------------------------------- - -## cac -License: MIT -By: egoist -Repository: egoist/cac - -> The MIT License (MIT) -> -> Copyright (c) EGOIST <0x142857@gmail.com> (https://github.com/egoist) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## chalk -License: MIT -Repository: chalk/chalk - -> MIT License -> -> Copyright (c) Sindre Sorhus (sindresorhus.com) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. - ---------------------------------------- - -## chokidar -License: MIT -By: Paul Miller, Elan Shanker -Repository: git+https://github.com/paulmillr/chokidar.git - -> The MIT License (MIT) -> -> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the “Software”), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## color-convert -License: MIT -By: Heather Arthur -Repository: Qix-/color-convert - ---------------------------------------- - -## color-name -License: MIT -By: DY -Repository: git@github.com:colorjs/color-name.git - ---------------------------------------- - -## commondir -License: MIT -By: James Halliday -Repository: http://github.com/substack/node-commondir.git - ---------------------------------------- - -## compressible -License: MIT -By: Douglas Christopher Wilson, Jonathan Ong, Jeremiah Senkpiel -Repository: jshttp/compressible - ---------------------------------------- - -## compression -License: MIT -By: Douglas Christopher Wilson, Jonathan Ong -Repository: expressjs/compression - -> (The MIT License) -> -> Copyright (c) 2014 Jonathan Ong -> Copyright (c) 2014-2015 Douglas Christopher Wilson -> -> Permission is hereby granted, free of charge, to any person obtaining -> a copy of this software and associated documentation files (the -> 'Software'), to deal in the Software without restriction, including -> without limitation the rights to use, copy, modify, merge, publish, -> distribute, sublicense, and/or sell copies of the Software, and to -> permit persons to whom the Software is furnished to do so, subject to -> the following conditions: -> -> The above copyright notice and this permission notice shall be -> included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## concat-map -License: MIT -By: James Halliday -Repository: git://github.com/substack/node-concat-map.git - ---------------------------------------- - -## connect -License: MIT -By: TJ Holowaychuk, Douglas Christopher Wilson, Jonathan Ong, Tim Caswell -Repository: senchalabs/connect - -> (The MIT License) -> -> Copyright (c) 2010 Sencha Inc. -> Copyright (c) 2011 LearnBoost -> Copyright (c) 2011-2014 TJ Holowaychuk -> Copyright (c) 2015 Douglas Christopher Wilson -> -> Permission is hereby granted, free of charge, to any person obtaining -> a copy of this software and associated documentation files (the -> 'Software'), to deal in the Software without restriction, including -> without limitation the rights to use, copy, modify, merge, publish, -> distribute, sublicense, and/or sell copies of the Software, and to -> permit persons to whom the Software is furnished to do so, subject to -> the following conditions: -> -> The above copyright notice and this permission notice shall be -> included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## connect-history-api-fallback -License: MIT -By: Ben Ripkens, Craig Myles -Repository: http://github.com/bripkens/connect-history-api-fallback.git - -> The MIT License -> -> Copyright (c) 2012 Ben Ripkens http://bripkens.de -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## convert-source-map -License: MIT -By: Thorsten Lorenz -Repository: git://github.com/thlorenz/convert-source-map.git - -> Copyright 2013 Thorsten Lorenz. -> All rights reserved. -> -> Permission is hereby granted, free of charge, to any person -> obtaining a copy of this software and associated documentation -> files (the "Software"), to deal in the Software without -> restriction, including without limitation the rights to use, -> copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the -> Software is furnished to do so, subject to the following -> conditions: -> -> The above copyright notice and this permission notice shall be -> included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -> HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -> OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## cors -License: MIT -By: Troy Goode -Repository: expressjs/cors - -> (The MIT License) -> -> Copyright (c) 2013 Troy Goode -> -> Permission is hereby granted, free of charge, to any person obtaining -> a copy of this software and associated documentation files (the -> 'Software'), to deal in the Software without restriction, including -> without limitation the rights to use, copy, modify, merge, publish, -> distribute, sublicense, and/or sell copies of the Software, and to -> permit persons to whom the Software is furnished to do so, subject to -> the following conditions: -> -> The above copyright notice and this permission notice shall be -> included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## cross-spawn -License: MIT -By: André Cruz -Repository: git@github.com:moxystudio/node-cross-spawn.git - ---------------------------------------- - -## cssesc -License: MIT -By: Mathias Bynens -Repository: https://github.com/mathiasbynens/cssesc.git - ---------------------------------------- - -## debug -License: MIT -By: TJ Holowaychuk, Nathan Rajlich, Andrew Rhyne, Josh Junon -Repository: git://github.com/visionmedia/debug.git - -> (The MIT License) -> -> Copyright (c) 2014 TJ Holowaychuk -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software -> and associated documentation files (the 'Software'), to deal in the Software without restriction, -> including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, -> and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, -> subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial -> portions of the Software. -> -> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT -> LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## define-lazy-prop -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/define-lazy-prop - ---------------------------------------- - -## dir-glob -License: MIT -By: Kevin Mårtensson -Repository: kevva/dir-glob - ---------------------------------------- - -## dotenv -License: BSD-2-Clause -Repository: git://github.com/motdotla/dotenv.git - -> Copyright (c) 2015, Scott Motte -> All rights reserved. -> -> Redistribution and use in source and binary forms, with or without -> modification, are permitted provided that the following conditions are met: -> -> * Redistributions of source code must retain the above copyright notice, this -> list of conditions and the following disclaimer. -> -> * Redistributions in binary form must reproduce the above copyright notice, -> this list of conditions and the following disclaimer in the documentation -> and/or other materials provided with the distribution. -> -> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ---------------------------------------- - -## dotenv-expand -License: BSD-2-Clause -By: motdotla - -> Copyright (c) 2016, Scott Motte -> All rights reserved. -> -> Redistribution and use in source and binary forms, with or without -> modification, are permitted provided that the following conditions are met: -> -> * Redistributions of source code must retain the above copyright notice, this -> list of conditions and the following disclaimer. -> -> * Redistributions in binary form must reproduce the above copyright notice, -> this list of conditions and the following disclaimer in the documentation -> and/or other materials provided with the distribution. -> -> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ---------------------------------------- - -## ee-first -License: MIT -By: Jonathan Ong, Douglas Christopher Wilson -Repository: jonathanong/ee-first - ---------------------------------------- - -## emojis-list -License: MIT -By: Kiko Beats -Repository: git+https://github.com/kikobeats/emojis-list.git - ---------------------------------------- - -## encodeurl -License: MIT -By: Douglas Christopher Wilson -Repository: pillarjs/encodeurl - ---------------------------------------- - -## es-module-lexer -License: MIT -By: Guy Bedford -Repository: git+https://github.com/guybedford/es-module-lexer.git - -> MIT License -> ----------- -> -> Copyright (C) 2018-2021 Guy Bedford -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## escape-html -License: MIT -Repository: component/escape-html - ---------------------------------------- - -## escape-string-regexp -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/escape-string-regexp - ---------------------------------------- - -## estree-walker -License: MIT -By: Rich Harris -Repository: https://github.com/Rich-Harris/estree-walker - -> Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/contributors) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## etag -License: MIT -By: Douglas Christopher Wilson, David Björklund -Repository: jshttp/etag - -> (The MIT License) -> -> Copyright (c) 2014-2016 Douglas Christopher Wilson -> -> Permission is hereby granted, free of charge, to any person obtaining -> a copy of this software and associated documentation files (the -> 'Software'), to deal in the Software without restriction, including -> without limitation the rights to use, copy, modify, merge, publish, -> distribute, sublicense, and/or sell copies of the Software, and to -> permit persons to whom the Software is furnished to do so, subject to -> the following conditions: -> -> The above copyright notice and this permission notice shall be -> included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## eventemitter3 -License: MIT -By: Arnout Kazemier -Repository: git://github.com/primus/eventemitter3.git - ---------------------------------------- - -## execa -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/execa - -> MIT License -> -> Copyright (c) Sindre Sorhus (https://sindresorhus.com) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. - ---------------------------------------- - -## fast-glob -License: MIT -By: Denis Malinochkin -Repository: mrmlnc/fast-glob - -> The MIT License (MIT) -> -> Copyright (c) Denis Malinochkin -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all -> copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -> SOFTWARE. - ---------------------------------------- - -## fastq -License: ISC -By: Matteo Collina -Repository: git+https://github.com/mcollina/fastq.git - ---------------------------------------- - -## fill-range -License: MIT -By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling -Repository: jonschlinkert/fill-range - ---------------------------------------- - -## finalhandler -License: MIT -By: Douglas Christopher Wilson -Repository: pillarjs/finalhandler - ---------------------------------------- - -## follow-redirects -License: MIT -By: Ruben Verborgh, Olivier Lalonde, James Talmage -Repository: git@github.com:follow-redirects/follow-redirects.git - ---------------------------------------- - -## fs.realpath -License: ISC -By: Isaac Z. Schlueter -Repository: git+https://github.com/isaacs/fs.realpath.git - ---------------------------------------- - -## generic-names -License: MIT -By: Alexey Litvinov -Repository: git+https://github.com/css-modules/generic-names.git - ---------------------------------------- - -## get-stream -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/get-stream - ---------------------------------------- - -## glob -License: ISC -By: Isaac Z. Schlueter -Repository: git://github.com/isaacs/node-glob.git - ---------------------------------------- - -## glob-parent -License: ISC -By: Gulp Team, Elan Shanker, Blaine Bublitz -Repository: gulpjs/glob-parent - ---------------------------------------- - -## globby -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/globby - ---------------------------------------- - -## has-flag -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/has-flag - ---------------------------------------- - -## http-proxy -License: MIT -By: Charlie Robbins -Repository: https://github.com/http-party/node-http-proxy.git - -> node-http-proxy -> -> Copyright (c) 2010-2016 Charlie Robbins, Jarrett Cruger & the Contributors. -> -> Permission is hereby granted, free of charge, to any person obtaining -> a copy of this software and associated documentation files (the -> "Software"), to deal in the Software without restriction, including -> without limitation the rights to use, copy, modify, merge, publish, -> distribute, sublicense, and/or sell copies of the Software, and to -> permit persons to whom the Software is furnished to do so, subject to -> the following conditions: -> -> The above copyright notice and this permission notice shall be -> included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## human-signals -License: Apache-2.0 -By: ehmicky -Repository: ehmicky/human-signals - ---------------------------------------- - -## icss-replace-symbols -License: ISC -By: Glen Maddern -Repository: git+https://github.com/css-modules/icss-replace-symbols.git - ---------------------------------------- - -## icss-utils -License: ISC -By: Glen Maddern -Repository: git+https://github.com/css-modules/icss-utils.git - ---------------------------------------- - -## ignore -License: MIT -By: kael -Repository: git@github.com:kaelzhang/node-ignore.git - ---------------------------------------- - -## import-cwd -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/import-cwd - ---------------------------------------- - -## import-from -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/import-from - ---------------------------------------- - -## inflight -License: ISC -By: Isaac Z. Schlueter -Repository: https://github.com/npm/inflight.git - ---------------------------------------- - -## inherits -License: ISC -Repository: git://github.com/isaacs/inherits - ---------------------------------------- - -## is-binary-path -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/is-binary-path - ---------------------------------------- - -## is-docker -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/is-docker - ---------------------------------------- - -## is-extglob -License: MIT -By: Jon Schlinkert -Repository: jonschlinkert/is-extglob - ---------------------------------------- - -## is-glob -License: MIT -By: Jon Schlinkert, Brian Woodward, Daniel Perez -Repository: micromatch/is-glob - ---------------------------------------- - -## is-number -License: MIT -By: Jon Schlinkert, Olsten Larck, Rouven Weßling -Repository: jonschlinkert/is-number - ---------------------------------------- - -## is-reference -License: MIT -By: Rich Harris -Repository: git+https://github.com/Rich-Harris/is-reference.git - ---------------------------------------- - -## is-stream -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/is-stream - ---------------------------------------- - -## is-wsl -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/is-wsl - ---------------------------------------- - -## isexe -License: ISC -By: Isaac Z. Schlueter -Repository: git+https://github.com/isaacs/isexe.git - ---------------------------------------- - -## json5 -License: MIT -By: Aseem Kishore, Max Nanasy, Andrew Eisenberg, Jordan Tucker -Repository: git+https://github.com/json5/json5.git - ---------------------------------------- - -## launch-editor -License: MIT -By: Evan You -Repository: git+https://github.com/yyx990803/launch-editor.git - ---------------------------------------- - -## launch-editor-middleware -License: MIT -By: Evan You -Repository: git+https://github.com/yyx990803/launch-editor.git - ---------------------------------------- - -## lilconfig -License: MIT -By: antonk52 -Repository: https://github.com/antonk52/lilconfig - ---------------------------------------- - -## loader-utils -License: MIT -By: Tobias Koppers @sokra -Repository: https://github.com/webpack/loader-utils.git - ---------------------------------------- - -## lodash.camelcase -License: MIT -By: John-David Dalton, Blaine Bublitz, Mathias Bynens -Repository: lodash/lodash - ---------------------------------------- - -## magic-string -License: MIT -By: Rich Harris -Repository: https://github.com/rich-harris/magic-string - -> Copyright 2018 Rich Harris -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## merge-stream -License: MIT -By: Stephen Sugden -Repository: grncdr/merge-stream - ---------------------------------------- - -## merge2 -License: MIT -Repository: git@github.com:teambition/merge2.git - ---------------------------------------- - -## micromatch -License: MIT -By: Jon Schlinkert, Amila Welihinda, Bogdan Chadkin, Brian Woodward, Devon Govett, Elan Shanker, Fabrício Matté, Martin Kolárik, Olsten Larck, Paul Miller, Tom Byrer, Tyler Akins, Peter Bright, Kuba Juszczyk -Repository: micromatch/micromatch - ---------------------------------------- - -## mime -License: MIT -By: Robert Kieffer -Repository: https://github.com/broofa/mime - -> The MIT License (MIT) -> -> Copyright (c) 2010 Benjamin Thomas, Robert Kieffer -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## mime-db -License: MIT -By: Douglas Christopher Wilson, Jonathan Ong, Robert Kieffer -Repository: jshttp/mime-db - ---------------------------------------- - -## mime-types -License: MIT -By: Douglas Christopher Wilson, Jeremiah Senkpiel, Jonathan Ong -Repository: jshttp/mime-types - -> (The MIT License) -> -> Copyright (c) 2014 Jonathan Ong -> Copyright (c) 2015 Douglas Christopher Wilson -> -> Permission is hereby granted, free of charge, to any person obtaining -> a copy of this software and associated documentation files (the -> 'Software'), to deal in the Software without restriction, including -> without limitation the rights to use, copy, modify, merge, publish, -> distribute, sublicense, and/or sell copies of the Software, and to -> permit persons to whom the Software is furnished to do so, subject to -> the following conditions: -> -> The above copyright notice and this permission notice shall be -> included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## mimic-fn -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/mimic-fn - ---------------------------------------- - -## minimatch -License: ISC -By: Isaac Z. Schlueter -Repository: git://github.com/isaacs/minimatch.git - -> The ISC License -> -> Copyright (c) Isaac Z. Schlueter and Contributors -> -> Permission to use, copy, modify, and/or distribute this software for any -> purpose with or without fee is hereby granted, provided that the above -> copyright notice and this permission notice appear in all copies. -> -> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - ---------------------------------------- - -## ms -License: MIT -Repository: zeit/ms - ---------------------------------------- - -## negotiator -License: MIT -By: Douglas Christopher Wilson, Federico Romero, Isaac Z. Schlueter -Repository: jshttp/negotiator - ---------------------------------------- - -## node-forge -License: (BSD-3-Clause OR GPL-2.0) -By: Digital Bazaar, Inc., Dave Longley, David I. Lehn, Stefan Siegl, Christoph Dorn -Repository: https://github.com/digitalbazaar/forge - ---------------------------------------- - -## normalize-path -License: MIT -By: Jon Schlinkert, Blaine Bublitz -Repository: jonschlinkert/normalize-path - ---------------------------------------- - -## npm-run-path -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/npm-run-path - ---------------------------------------- - -## object-assign -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/object-assign - ---------------------------------------- - -## okie -License: MIT -By: Evan You -Repository: git+https://github.com/yyx990803/okie.git - -> MIT License -> -> Copyright (c) 2020-present, Yuxi (Evan) You -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all -> copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -> SOFTWARE. - ---------------------------------------- - -## on-finished -License: MIT -By: Douglas Christopher Wilson, Jonathan Ong -Repository: jshttp/on-finished - ---------------------------------------- - -## on-headers -License: MIT -By: Douglas Christopher Wilson -Repository: jshttp/on-headers - ---------------------------------------- - -## once -License: ISC -By: Isaac Z. Schlueter -Repository: git://github.com/isaacs/once - ---------------------------------------- - -## onetime -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/onetime - ---------------------------------------- - -## open -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/open - -> MIT License -> -> Copyright (c) Sindre Sorhus (https://sindresorhus.com) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. - ---------------------------------------- - -## parseurl -License: MIT -By: Douglas Christopher Wilson, Jonathan Ong -Repository: pillarjs/parseurl - ---------------------------------------- - -## path-is-absolute -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/path-is-absolute - ---------------------------------------- - -## path-key -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/path-key - ---------------------------------------- - -## path-type -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/path-type - ---------------------------------------- - -## periscopic -License: MIT -Repository: Rich-Harris/periscopic - -> Copyright (c) 2019 Rich Harris -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## picomatch -License: MIT -By: Jon Schlinkert -Repository: micromatch/picomatch - ---------------------------------------- - -## pify -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/pify - ---------------------------------------- - -## postcss-import -License: MIT -By: Maxime Thirouin -Repository: https://github.com/postcss/postcss-import.git - -> The MIT License (MIT) -> -> Copyright (c) 2014 Maxime Thirouin, Jason Campbell & Kevin Mårtensson -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of -> this software and associated documentation files (the "Software"), to deal in -> the Software without restriction, including without limitation the rights to -> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -> the Software, and to permit persons to whom the Software is furnished to do so, -> subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all -> copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## postcss-load-config -License: MIT -By: Michael Ciniawky, Ryan Dunckel, Mateusz Derks, Dalton Santos, Patrick Gilday -Repository: postcss/postcss-load-config - -> The MIT License (MIT) -> -> Copyright Michael Ciniawsky -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of -> this software and associated documentation files (the "Software"), to deal in -> the Software without restriction, including without limitation the rights to -> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -> the Software, and to permit persons to whom the Software is furnished to do so, -> subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all -> copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## postcss-modules -License: MIT -By: Alexander Madyankin -Repository: https://github.com/css-modules/postcss-modules.git - -> The MIT License (MIT) -> -> Copyright 2015-2016 Alexander Madyankin -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of -> this software and associated documentation files (the "Software"), to deal in -> the Software without restriction, including without limitation the rights to -> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -> the Software, and to permit persons to whom the Software is furnished to do so, -> subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all -> copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------------------------------------- - -## postcss-modules-extract-imports -License: ISC -By: Glen Maddern -Repository: https://github.com/css-modules/postcss-modules-extract-imports.git - ---------------------------------------- - -## postcss-modules-local-by-default -License: MIT -By: Mark Dalgleish -Repository: https://github.com/css-modules/postcss-modules-local-by-default.git - ---------------------------------------- - -## postcss-modules-scope -License: ISC -By: Glen Maddern -Repository: https://github.com/css-modules/postcss-modules-scope.git - ---------------------------------------- - -## postcss-modules-values -License: ISC -By: Glen Maddern -Repository: git+https://github.com/css-modules/postcss-modules-values.git - ---------------------------------------- - -## postcss-selector-parser -License: MIT -By: Ben Briggs, Chris Eppstein -Repository: postcss/postcss-selector-parser - ---------------------------------------- - -## postcss-value-parser -License: MIT -By: Bogdan Chadkin -Repository: https://github.com/TrySound/postcss-value-parser.git - ---------------------------------------- - -## queue-microtask -License: MIT -By: Feross Aboukhadijeh -Repository: git://github.com/feross/queue-microtask.git - ---------------------------------------- - -## read-cache -License: MIT -By: Bogdan Chadkin -Repository: git+https://github.com/TrySound/read-cache.git - ---------------------------------------- - -## readdirp -License: MIT -By: Thorsten Lorenz, Paul Miller -Repository: git://github.com/paulmillr/readdirp.git - ---------------------------------------- - -## requires-port -License: MIT -By: Arnout Kazemier -Repository: https://github.com/unshiftio/requires-port - ---------------------------------------- - -## resolve-from -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/resolve-from - ---------------------------------------- - -## resolve.exports -License: MIT -By: Luke Edwards -Repository: lukeed/resolve.exports - -> The MIT License (MIT) -> -> Copyright (c) Luke Edwards (lukeed.com) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS 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. - ---------------------------------------- - -## reusify -License: MIT -By: Matteo Collina -Repository: git+https://github.com/mcollina/reusify.git - ---------------------------------------- - -## run-parallel -License: MIT -By: Feross Aboukhadijeh -Repository: git://github.com/feross/run-parallel.git - ---------------------------------------- - -## safe-buffer -License: MIT -By: Feross Aboukhadijeh -Repository: git://github.com/feross/safe-buffer.git - ---------------------------------------- - -## selfsigned -License: MIT -By: José F. Romaniello, Paolo Fragomeni, Charles Bushong -Repository: git://github.com/jfromaniello/selfsigned.git - -> MIT License -> -> Copyright (c) 2013 José F. Romaniello -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all -> copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -> SOFTWARE. - ---------------------------------------- - -## shebang-command -License: MIT -By: Kevin Mårtensson -Repository: kevva/shebang-command - ---------------------------------------- - -## shebang-regex -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/shebang-regex - ---------------------------------------- - -## shell-quote -License: MIT -By: James Halliday -Repository: http://github.com/substack/node-shell-quote.git - ---------------------------------------- - -## signal-exit -License: ISC -By: Ben Coe -Repository: https://github.com/tapjs/signal-exit.git - ---------------------------------------- - -## sirv -License: MIT -By: Luke Edwards -Repository: lukeed/sirv - ---------------------------------------- - -## slash -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/slash - ---------------------------------------- - -## source-map -License: BSD-3-Clause -By: Nick Fitzgerald, Tobias Koppers, Duncan Beevers, Stephen Crane, Ryan Seddon, Miles Elam, Mihai Bazon, Michael Ficarra, Todd Wolfson, Alexander Solovyov, Felix Gnass, Conrad Irwin, usrbincc, David Glasser, Chase Douglas, Evan Wallace, Heather Arthur, Hugh Kennedy, Simon Lydell, Jmeas Smith, Michael Z Goddard, azu, John Gozde, Adam Kirkton, Chris Montgomery, J. Ryan Stinnett, Jack Herrington, Chris Truter, Daniel Espeset, Jamie Wong, Eddy Bruël, Hawken Rives, Gilad Peleg, djchie, Gary Ye, Nicolas Lalevée -Repository: http://github.com/mozilla/source-map.git - -> Copyright (c) 2009-2011, Mozilla Foundation and contributors -> All rights reserved. -> -> Redistribution and use in source and binary forms, with or without -> modification, are permitted provided that the following conditions are met: -> -> * Redistributions of source code must retain the above copyright notice, this -> list of conditions and the following disclaimer. -> -> * Redistributions in binary form must reproduce the above copyright notice, -> this list of conditions and the following disclaimer in the documentation -> and/or other materials provided with the distribution. -> -> * Neither the names of the Mozilla Foundation nor the names of project -> contributors may be used to endorse or promote products derived from this -> software without specific prior written permission. -> -> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -> ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -> WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ---------------------------------------- - -## sourcemap-codec -License: MIT -By: Rich Harris -Repository: https://github.com/Rich-Harris/sourcemap-codec - ---------------------------------------- - -## statuses -License: MIT -By: Douglas Christopher Wilson, Jonathan Ong -Repository: jshttp/statuses - ---------------------------------------- - -## string-hash -License: CC0-1.0 -By: The Dark Sky Company -Repository: git://github.com/darkskyapp/string-hash.git - ---------------------------------------- - -## strip-ansi -License: MIT -By: Sindre Sorhus -Repository: chalk/strip-ansi - -> MIT License -> -> Copyright (c) Sindre Sorhus (sindresorhus.com) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. - ---------------------------------------- - -## strip-final-newline -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/strip-final-newline - ---------------------------------------- - -## supports-color -License: MIT -By: Sindre Sorhus -Repository: chalk/supports-color - ---------------------------------------- - -## to-regex-range -License: MIT -By: Jon Schlinkert, Rouven Weßling -Repository: micromatch/to-regex-range - ---------------------------------------- - -## totalist -License: MIT -By: Luke Edwards -Repository: lukeed/totalist - ---------------------------------------- - -## tsconfck -License: MIT -By: dominikg -Repository: git+https://github.com/dominikg/tsconfck.git - -> MIT License -> -> Copyright (c) 2021-present dominikg and [contributors](https://github.com/dominikg/tsconfck/graphs/contributors) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all -> copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -> SOFTWARE. -> -> -- Licenses for 3rd-party code included in tsconfck -- -> -> # strip-bom and strip-json-comments -> MIT License -> -> Copyright (c) Sindre Sorhus (https://sindresorhus.com) -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all -> copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS 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. - ---------------------------------------- - -## unpipe -License: MIT -By: Douglas Christopher Wilson -Repository: stream-utils/unpipe - ---------------------------------------- - -## util-deprecate -License: MIT -By: Nathan Rajlich -Repository: git://github.com/TooTallNate/util-deprecate.git - ---------------------------------------- - -## utils-merge -License: MIT -By: Jared Hanson -Repository: git://github.com/jaredhanson/utils-merge.git - ---------------------------------------- - -## vary -License: MIT -By: Douglas Christopher Wilson -Repository: jshttp/vary - ---------------------------------------- - -## which -License: ISC -By: Isaac Z. Schlueter -Repository: git://github.com/isaacs/node-which.git - ---------------------------------------- - -## wrappy -License: ISC -By: Isaac Z. Schlueter -Repository: https://github.com/npm/wrappy - ---------------------------------------- - -## ws -License: MIT -By: Einar Otto Stangvik -Repository: websockets/ws - -> The MIT License (MIT) -> -> Copyright (c) 2011 Einar Otto Stangvik -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all -> copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -> SOFTWARE. - ---------------------------------------- - -## yaml -License: ISC -By: Eemeli Aro -Repository: github:eemeli/yaml diff --git a/packages/astro/vendor/vite/client.d.ts b/packages/astro/vendor/vite/client.d.ts deleted file mode 100644 index 2586f07816ca..000000000000 --- a/packages/astro/vendor/vite/client.d.ts +++ /dev/null @@ -1,204 +0,0 @@ -/// -/// - -// CSS modules -type CSSModuleClasses = { readonly [key: string]: string } - -declare module '*.module.css' { - const classes: CSSModuleClasses - export default classes -} -declare module '*.module.scss' { - const classes: CSSModuleClasses - export default classes -} -declare module '*.module.sass' { - const classes: CSSModuleClasses - export default classes -} -declare module '*.module.less' { - const classes: CSSModuleClasses - export default classes -} -declare module '*.module.styl' { - const classes: CSSModuleClasses - export default classes -} -declare module '*.module.stylus' { - const classes: CSSModuleClasses - export default classes -} -declare module '*.module.pcss' { - const classes: CSSModuleClasses - export default classes -} - -// CSS -declare module '*.css' { - const css: string - export default css -} -declare module '*.scss' { - const css: string - export default css -} -declare module '*.sass' { - const css: string - export default css -} -declare module '*.less' { - const css: string - export default css -} -declare module '*.styl' { - const css: string - export default css -} -declare module '*.stylus' { - const css: string - export default css -} -declare module '*.pcss' { - const css: string - export default css -} - -// Built-in asset types -// see `src/constants.ts` - -// images -declare module '*.jpg' { - const src: string - export default src -} -declare module '*.jpeg' { - const src: string - export default src -} -declare module '*.png' { - const src: string - export default src -} -declare module '*.gif' { - const src: string - export default src -} -declare module '*.svg' { - const src: string - export default src -} -declare module '*.ico' { - const src: string - export default src -} -declare module '*.webp' { - const src: string - export default src -} -declare module '*.avif' { - const src: string - export default src -} - -// media -declare module '*.mp4' { - const src: string - export default src -} -declare module '*.webm' { - const src: string - export default src -} -declare module '*.ogg' { - const src: string - export default src -} -declare module '*.mp3' { - const src: string - export default src -} -declare module '*.wav' { - const src: string - export default src -} -declare module '*.flac' { - const src: string - export default src -} -declare module '*.aac' { - const src: string - export default src -} - -// fonts -declare module '*.woff' { - const src: string - export default src -} -declare module '*.woff2' { - const src: string - export default src -} -declare module '*.eot' { - const src: string - export default src -} -declare module '*.ttf' { - const src: string - export default src -} -declare module '*.otf' { - const src: string - export default src -} - -// other -declare module '*.wasm' { - const initWasm: (options: WebAssembly.Imports) => Promise - export default initWasm -} -declare module '*.webmanifest' { - const src: string - export default src -} -declare module '*.pdf' { - const src: string - export default src -} - -// web worker -declare module '*?worker' { - const workerConstructor: { - new (): Worker - } - export default workerConstructor -} - -declare module '*?worker&inline' { - const workerConstructor: { - new (): Worker - } - export default workerConstructor -} - -declare module '*?sharedworker' { - const sharedWorkerConstructor: { - new (): SharedWorker - } - export default sharedWorkerConstructor -} - -declare module '*?raw' { - const src: string - export default src -} - -declare module '*?url' { - const src: string - export default src -} - -declare module '*?inline' { - const src: string - export default src -} diff --git a/packages/astro/vendor/vite/dist/client/client.mjs b/packages/astro/vendor/vite/dist/client/client.mjs deleted file mode 100755 index 53609982f9d2..000000000000 --- a/packages/astro/vendor/vite/dist/client/client.mjs +++ /dev/null @@ -1,565 +0,0 @@ -import '@vite/env'; - -const template = /*html*/ ` - -
-
-

-  

-  

-  
- Click outside or fix the code to dismiss.
- You can also disable this overlay by setting - server.hmr.overlay to false in vite.config.js. -
-
-`; -const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g; -const codeframeRE = /^(?:>?\s+\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm; -class ErrorOverlay extends HTMLElement { - constructor(err) { - var _a; - super(); - this.root = this.attachShadow({ mode: 'open' }); - this.root.innerHTML = template; - codeframeRE.lastIndex = 0; - const hasFrame = err.frame && codeframeRE.test(err.frame); - const message = hasFrame - ? err.message.replace(codeframeRE, '') - : err.message; - if (err.plugin) { - this.text('.plugin', `[plugin:${err.plugin}] `); - } - this.text('.message-body', message.trim()); - const [file] = (((_a = err.loc) === null || _a === void 0 ? void 0 : _a.file) || err.id || 'unknown file').split(`?`); - if (err.loc) { - this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true); - } - else if (err.id) { - this.text('.file', file); - } - if (hasFrame) { - this.text('.frame', err.frame.trim()); - } - this.text('.stack', err.stack, true); - this.root.querySelector('.window').addEventListener('click', (e) => { - e.stopPropagation(); - }); - this.addEventListener('click', () => { - this.close(); - }); - } - text(selector, text, linkFiles = false) { - const el = this.root.querySelector(selector); - if (!linkFiles) { - el.textContent = text; - } - else { - let curIndex = 0; - let match; - while ((match = fileRE.exec(text))) { - const { 0: file, index } = match; - if (index != null) { - const frag = text.slice(curIndex, index); - el.appendChild(document.createTextNode(frag)); - const link = document.createElement('a'); - link.textContent = file; - link.className = 'file-link'; - link.onclick = () => { - fetch('/__open-in-editor?file=' + encodeURIComponent(file)); - }; - el.appendChild(link); - curIndex += frag.length + file.length; - } - } - } - } - close() { - var _a; - (_a = this.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this); - } -} -const overlayId = 'vite-error-overlay'; -if (customElements && !customElements.get(overlayId)) { - customElements.define(overlayId, ErrorOverlay); -} - -console.log('[vite] connecting...'); -// use server configuration, then fallback to inference -const socketProtocol = __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws'); -const socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`; -const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr'); -const base = __BASE__ || '/'; -function warnFailedFetch(err, path) { - if (!err.message.match('fetch')) { - console.error(err); - } - console.error(`[hmr] Failed to reload ${path}. ` + - `This could be due to syntax errors or importing non-existent ` + - `modules. (see errors above)`); -} -// Listen for messages -socket.addEventListener('message', async ({ data }) => { - handleMessage(JSON.parse(data)); -}); - -/** - * This cleans up the query params and removes the `direct` param which is internal. - * Other query params are preserved. - */ -function cleanUrl(pathname) { - let url = new URL(pathname, location); - url.searchParams.delete('direct'); - return url.pathname + url.search; -} -let isFirstUpdate = true; -async function handleMessage(payload) { - switch (payload.type) { - case 'connected': - console.log(`[vite] connected.`); - // proxy(nginx, docker) hmr ws maybe caused timeout, - // so send ping package let ws keep alive. - setInterval(() => socket.send('ping'), __HMR_TIMEOUT__); - break; - case 'update': - notifyListeners('vite:beforeUpdate', payload); - // if this is the first update and there's already an error overlay, it - // means the page opened with existing server compile error and the whole - // module script failed to load (since one of the nested imports is 500). - // in this case a normal update won't work and a full reload is needed. - if (isFirstUpdate && hasErrorOverlay()) { - window.location.reload(); - return; - } - else { - clearErrorOverlay(); - isFirstUpdate = false; - } - payload.updates.forEach((update) => { - if (update.type === 'js-update') { - queueUpdate(fetchUpdate(update)); - } - else { - // css-update - // this is only sent when a css file referenced with is updated - let { path, timestamp } = update; - let searchUrl = cleanUrl(path); - // can't use querySelector with `[href*=]` here since the link may be - // using relative paths so we need to use link.href to grab the full - // URL for the include check. - const el = [].slice.call(document.querySelectorAll(`link`)).find((e) => { - return cleanUrl(e.href).includes(searchUrl) - }); - if (el) { - const newPath = `${base}${path.slice(1)}${path.includes('?') ? '&' : '?'}t=${timestamp}`; - el.href = new URL(newPath, el.href).href; - } - console.log(`[vite] css hot updated: ${path}`); - } - }); - break; - case 'custom': { - notifyListeners(payload.event, payload.data); - break; - } - case 'full-reload': - notifyListeners('vite:beforeFullReload', payload); - if (payload.path && payload.path.endsWith('.html')) { - // if html file is edited, only reload the page if the browser is - // currently on that page. - const pagePath = location.pathname; - const payloadPath = base + payload.path.slice(1); - if (pagePath === payloadPath || - (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)) { - location.reload(); - } - return; - } - else { - location.reload(); - } - break; - case 'prune': - notifyListeners('vite:beforePrune', payload); - // After an HMR update, some modules are no longer imported on the page - // but they may have left behind side effects that need to be cleaned up - // (.e.g style injections) - // TODO Trigger their dispose callbacks. - payload.paths.forEach((path) => { - const fn = pruneMap.get(path); - if (fn) { - fn(dataMap.get(path)); - } - }); - break; - case 'error': { - notifyListeners('vite:error', payload); - const err = payload.err; - if (enableOverlay) { - createErrorOverlay(err); - } - else { - console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`); - } - break; - } - default: { - const check = payload; - return check; - } - } -} -function notifyListeners(event, data) { - const cbs = customListenersMap.get(event); - if (cbs) { - cbs.forEach((cb) => cb(data)); - } -} -const enableOverlay = __HMR_ENABLE_OVERLAY__; -function createErrorOverlay(err) { - if (!enableOverlay) - return; - clearErrorOverlay(); - document.body.appendChild(new ErrorOverlay(err)); -} -function clearErrorOverlay() { - document - .querySelectorAll(overlayId) - .forEach((n) => n.close()); -} -function hasErrorOverlay() { - return document.querySelectorAll(overlayId).length; -} -let pending = false; -let queued = []; -/** - * buffer multiple hot updates triggered by the same src change - * so that they are invoked in the same order they were sent. - * (otherwise the order may be inconsistent because of the http request round trip) - */ -async function queueUpdate(p) { - queued.push(p); - if (!pending) { - pending = true; - await Promise.resolve(); - pending = false; - const loading = [...queued]; - queued = []; - (await Promise.all(loading)).forEach((fn) => fn && fn()); - } -} -async function waitForSuccessfulPing(ms = 1000) { - // eslint-disable-next-line no-constant-condition - while (true) { - try { - await fetch(`${base}__vite_ping`); - break; - } - catch (e) { - await new Promise((resolve) => setTimeout(resolve, ms)); - } - } -} -// ping server -socket.addEventListener('close', async ({ wasClean }) => { - if (wasClean) - return; - console.log(`[vite] server connection lost. polling for restart...`); - await waitForSuccessfulPing(); - location.reload(); -}); -const sheetsMap = new Map(); -function updateStyle(id, content) { - let style = sheetsMap.get(id); - { - if (style && !(style instanceof HTMLStyleElement)) { - removeStyle(id); - style = undefined; - } - if (!style) { - style = document.createElement('style'); - style.setAttribute('type', 'text/css'); - style.innerHTML = content; - document.head.appendChild(style); - } - else { - style.innerHTML = content; - } - } - sheetsMap.set(id, style); -} -function removeStyle(id) { - const style = sheetsMap.get(id); - if (style) { - if (style instanceof CSSStyleSheet) { - // @ts-ignore - document.adoptedStyleSheets.indexOf(style); - // @ts-ignore - document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style); - } - else { - document.head.removeChild(style); - } - sheetsMap.delete(id); - } -} -async function fetchUpdate({ path, acceptedPath, timestamp }) { - const mod = hotModulesMap.get(path); - if (!mod) { - // In a code-splitting project, - // it is common that the hot-updating module is not loaded yet. - // https://github.com/vitejs/vite/issues/721 - return; - } - const moduleMap = new Map(); - const isSelfUpdate = path === acceptedPath; - // make sure we only import each dep once - const modulesToUpdate = new Set(); - if (isSelfUpdate) { - // self update - only update self - modulesToUpdate.add(path); - } - else { - // dep update - for (const { deps } of mod.callbacks) { - deps.forEach((dep) => { - if (acceptedPath === dep) { - modulesToUpdate.add(dep); - } - }); - } - } - // determine the qualified callbacks before we re-import the modules - const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => { - return deps.some((dep) => modulesToUpdate.has(dep)); - }); - await Promise.all(Array.from(modulesToUpdate).map(async (dep) => { - const disposer = disposeMap.get(dep); - if (disposer) - await disposer(dataMap.get(dep)); - const [path, query] = dep.split(`?`); - try { - const newMod = await import( - /* @vite-ignore */ - base + - path.slice(1) + - `?import&t=${timestamp}${query ? `&${query}` : ''}`); - moduleMap.set(dep, newMod); - } - catch (e) { - warnFailedFetch(e, dep); - } - })); - return () => { - for (const { deps, fn } of qualifiedCallbacks) { - fn(deps.map((dep) => moduleMap.get(dep))); - } - const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`; - console.log(`[vite] hot updated: ${loggedPath}`); - }; -} -const hotModulesMap = new Map(); -const disposeMap = new Map(); -const pruneMap = new Map(); -const dataMap = new Map(); -const customListenersMap = new Map(); -const ctxToListenersMap = new Map(); -// Just infer the return type for now -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -const createHotContext = (ownerPath) => { - if (!dataMap.has(ownerPath)) { - dataMap.set(ownerPath, {}); - } - // when a file is hot updated, a new context is created - // clear its stale callbacks - const mod = hotModulesMap.get(ownerPath); - if (mod) { - mod.callbacks = []; - } - // clear stale custom event listeners - const staleListeners = ctxToListenersMap.get(ownerPath); - if (staleListeners) { - for (const [event, staleFns] of staleListeners) { - const listeners = customListenersMap.get(event); - if (listeners) { - customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l))); - } - } - } - const newListeners = new Map(); - ctxToListenersMap.set(ownerPath, newListeners); - function acceptDeps(deps, callback = () => { }) { - const mod = hotModulesMap.get(ownerPath) || { - id: ownerPath, - callbacks: [] - }; - mod.callbacks.push({ - deps, - fn: callback - }); - hotModulesMap.set(ownerPath, mod); - } - const hot = { - get data() { - return dataMap.get(ownerPath); - }, - accept(deps, callback) { - if (typeof deps === 'function' || !deps) { - // self-accept: hot.accept(() => {}) - acceptDeps([ownerPath], ([mod]) => deps && deps(mod)); - } - else if (typeof deps === 'string') { - // explicit deps - acceptDeps([deps], ([mod]) => callback && callback(mod)); - } - else if (Array.isArray(deps)) { - acceptDeps(deps, callback); - } - else { - throw new Error(`invalid hot.accept() usage.`); - } - }, - acceptDeps() { - throw new Error(`hot.acceptDeps() is deprecated. ` + - `Use hot.accept() with the same signature instead.`); - }, - dispose(cb) { - disposeMap.set(ownerPath, cb); - }, - prune(cb) { - pruneMap.set(ownerPath, cb); - }, - // TODO - // eslint-disable-next-line @typescript-eslint/no-empty-function - decline() { }, - invalidate() { - // TODO should tell the server to re-perform hmr propagation - // from this module as root - location.reload(); - }, - // custom events - on: (event, cb) => { - const addToMap = (map) => { - const existing = map.get(event) || []; - existing.push(cb); - map.set(event, existing); - }; - addToMap(customListenersMap); - addToMap(newListeners); - } - }; - return hot; -}; -/** - * urls here are dynamic import() urls that couldn't be statically analyzed - */ -function injectQuery(url, queryToInject) { - // skip urls that won't be handled by vite - if (!url.startsWith('.') && !url.startsWith('/')) { - return url; - } - // can't use pathname from URL since it may be relative like ../ - const pathname = url.replace(/#.*$/, '').replace(/\?.*$/, ''); - const { search, hash } = new URL(url, 'http://vitejs.dev'); - return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`; -} - -export { createHotContext, injectQuery, removeStyle, updateStyle }; -//# sourceMappingURL=client.mjs.map diff --git a/packages/astro/vendor/vite/dist/client/client.mjs.map b/packages/astro/vendor/vite/dist/client/client.mjs.map deleted file mode 100755 index 483469f1dd50..000000000000 --- a/packages/astro/vendor/vite/dist/client/client.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"client.mjs","sources":["../../src/client/overlay.ts","../../src/client/client.ts"],"sourcesContent":["import { ErrorPayload } from 'types/hmrPayload'\n\nconst template = /*html*/ `\n\n
\n
\n
\n  
\n  
\n  
\n Click outside or fix the code to dismiss.
\n You can also disable this overlay by setting\n server.hmr.overlay to false in vite.config.js.\n
\n
\n`\n\nconst fileRE = /(?:[a-zA-Z]:\\\\|\\/).*?:\\d+:\\d+/g\nconst codeframeRE = /^(?:>?\\s+\\d+\\s+\\|.*|\\s+\\|\\s*\\^.*)\\r?\\n/gm\n\nexport class ErrorOverlay extends HTMLElement {\n root: ShadowRoot\n\n constructor(err: ErrorPayload['err']) {\n super()\n this.root = this.attachShadow({ mode: 'open' })\n this.root.innerHTML = template\n\n codeframeRE.lastIndex = 0\n const hasFrame = err.frame && codeframeRE.test(err.frame)\n const message = hasFrame\n ? err.message.replace(codeframeRE, '')\n : err.message\n if (err.plugin) {\n this.text('.plugin', `[plugin:${err.plugin}] `)\n }\n this.text('.message-body', message.trim())\n\n const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`)\n if (err.loc) {\n this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true)\n } else if (err.id) {\n this.text('.file', file)\n }\n\n if (hasFrame) {\n this.text('.frame', err.frame!.trim())\n }\n this.text('.stack', err.stack, true)\n\n this.root.querySelector('.window')!.addEventListener('click', (e) => {\n e.stopPropagation()\n })\n this.addEventListener('click', () => {\n this.close()\n })\n }\n\n text(selector: string, text: string, linkFiles = false): void {\n const el = this.root.querySelector(selector)!\n if (!linkFiles) {\n el.textContent = text\n } else {\n let curIndex = 0\n let match: RegExpExecArray | null\n while ((match = fileRE.exec(text))) {\n const { 0: file, index } = match\n if (index != null) {\n const frag = text.slice(curIndex, index)\n el.appendChild(document.createTextNode(frag))\n const link = document.createElement('a')\n link.textContent = file\n link.className = 'file-link'\n link.onclick = () => {\n fetch('/__open-in-editor?file=' + encodeURIComponent(file))\n }\n el.appendChild(link)\n curIndex += frag.length + file.length\n }\n }\n }\n }\n\n close(): void {\n this.parentNode?.removeChild(this)\n }\n}\n\nexport const overlayId = 'vite-error-overlay'\nif (customElements && !customElements.get(overlayId)) {\n customElements.define(overlayId, ErrorOverlay)\n}\n","import {\n ErrorPayload,\n FullReloadPayload,\n HMRPayload,\n PrunePayload,\n Update,\n UpdatePayload\n} from 'types/hmrPayload'\nimport { CustomEventName } from 'types/customEvent'\nimport { ErrorOverlay, overlayId } from './overlay'\n// eslint-disable-next-line node/no-missing-import\nimport '@vite/env'\n\n// injected by the hmr plugin when served\ndeclare const __BASE__: string\ndeclare const __HMR_PROTOCOL__: string\ndeclare const __HMR_HOSTNAME__: string\ndeclare const __HMR_PORT__: string\ndeclare const __HMR_TIMEOUT__: number\ndeclare const __HMR_ENABLE_OVERLAY__: boolean\n\nconsole.log('[vite] connecting...')\n\n// use server configuration, then fallback to inference\nconst socketProtocol =\n __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws')\nconst socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`\nconst socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')\nconst base = __BASE__ || '/'\n\nfunction warnFailedFetch(err: Error, path: string | string[]) {\n if (!err.message.match('fetch')) {\n console.error(err)\n }\n console.error(\n `[hmr] Failed to reload ${path}. ` +\n `This could be due to syntax errors or importing non-existent ` +\n `modules. (see errors above)`\n )\n}\n\n// Listen for messages\nsocket.addEventListener('message', async ({ data }) => {\n handleMessage(JSON.parse(data))\n})\n\nlet isFirstUpdate = true\n\nasync function handleMessage(payload: HMRPayload) {\n switch (payload.type) {\n case 'connected':\n console.log(`[vite] connected.`)\n // proxy(nginx, docker) hmr ws maybe caused timeout,\n // so send ping package let ws keep alive.\n setInterval(() => socket.send('ping'), __HMR_TIMEOUT__)\n break\n case 'update':\n notifyListeners('vite:beforeUpdate', payload)\n // if this is the first update and there's already an error overlay, it\n // means the page opened with existing server compile error and the whole\n // module script failed to load (since one of the nested imports is 500).\n // in this case a normal update won't work and a full reload is needed.\n if (isFirstUpdate && hasErrorOverlay()) {\n window.location.reload()\n return\n } else {\n clearErrorOverlay()\n isFirstUpdate = false\n }\n payload.updates.forEach((update) => {\n if (update.type === 'js-update') {\n queueUpdate(fetchUpdate(update))\n } else {\n // css-update\n // this is only sent when a css file referenced with is updated\n let { path, timestamp } = update\n path = path.replace(/\\?.*/, '')\n // can't use querySelector with `[href*=]` here since the link may be\n // using relative paths so we need to use link.href to grab the full\n // URL for the include check.\n const el = (\n [].slice.call(\n document.querySelectorAll(`link`)\n ) as HTMLLinkElement[]\n ).find((e) => e.href.includes(path))\n if (el) {\n const newPath = `${base}${path.slice(1)}${\n path.includes('?') ? '&' : '?'\n }t=${timestamp}`\n el.href = new URL(newPath, el.href).href\n }\n console.log(`[vite] css hot updated: ${path}`)\n }\n })\n break\n case 'custom': {\n notifyListeners(payload.event as CustomEventName, payload.data)\n break\n }\n case 'full-reload':\n notifyListeners('vite:beforeFullReload', payload)\n if (payload.path && payload.path.endsWith('.html')) {\n // if html file is edited, only reload the page if the browser is\n // currently on that page.\n const pagePath = location.pathname\n const payloadPath = base + payload.path.slice(1)\n if (\n pagePath === payloadPath ||\n (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)\n ) {\n location.reload()\n }\n return\n } else {\n location.reload()\n }\n break\n case 'prune':\n notifyListeners('vite:beforePrune', payload)\n // After an HMR update, some modules are no longer imported on the page\n // but they may have left behind side effects that need to be cleaned up\n // (.e.g style injections)\n // TODO Trigger their dispose callbacks.\n payload.paths.forEach((path) => {\n const fn = pruneMap.get(path)\n if (fn) {\n fn(dataMap.get(path))\n }\n })\n break\n case 'error': {\n notifyListeners('vite:error', payload)\n const err = payload.err\n if (enableOverlay) {\n createErrorOverlay(err)\n } else {\n console.error(\n `[vite] Internal Server Error\\n${err.message}\\n${err.stack}`\n )\n }\n break\n }\n default: {\n const check: never = payload\n return check\n }\n }\n}\n\nfunction notifyListeners(\n event: 'vite:beforeUpdate',\n payload: UpdatePayload\n): void\nfunction notifyListeners(event: 'vite:beforePrune', payload: PrunePayload): void\nfunction notifyListeners(\n event: 'vite:beforeFullReload',\n payload: FullReloadPayload\n): void\nfunction notifyListeners(event: 'vite:error', payload: ErrorPayload): void\nfunction notifyListeners(\n event: CustomEventName,\n data: any\n): void\nfunction notifyListeners(event: string, data: any): void {\n const cbs = customListenersMap.get(event)\n if (cbs) {\n cbs.forEach((cb) => cb(data))\n }\n}\n\nconst enableOverlay = __HMR_ENABLE_OVERLAY__\n\nfunction createErrorOverlay(err: ErrorPayload['err']) {\n if (!enableOverlay) return\n clearErrorOverlay()\n document.body.appendChild(new ErrorOverlay(err))\n}\n\nfunction clearErrorOverlay() {\n document\n .querySelectorAll(overlayId)\n .forEach((n) => (n as ErrorOverlay).close())\n}\n\nfunction hasErrorOverlay() {\n return document.querySelectorAll(overlayId).length\n}\n\nlet pending = false\nlet queued: Promise<(() => void) | undefined>[] = []\n\n/**\n * buffer multiple hot updates triggered by the same src change\n * so that they are invoked in the same order they were sent.\n * (otherwise the order may be inconsistent because of the http request round trip)\n */\nasync function queueUpdate(p: Promise<(() => void) | undefined>) {\n queued.push(p)\n if (!pending) {\n pending = true\n await Promise.resolve()\n pending = false\n const loading = [...queued]\n queued = []\n ;(await Promise.all(loading)).forEach((fn) => fn && fn())\n }\n}\n\nasync function waitForSuccessfulPing(ms = 1000) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n await fetch(`${base}__vite_ping`)\n break\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, ms))\n }\n }\n}\n\n// ping server\nsocket.addEventListener('close', async ({ wasClean }) => {\n if (wasClean) return\n console.log(`[vite] server connection lost. polling for restart...`)\n await waitForSuccessfulPing()\n location.reload()\n})\n\n// https://wicg.github.io/construct-stylesheets\nconst supportsConstructedSheet = (() => {\n try {\n // new CSSStyleSheet()\n // return true\n } catch (e) {}\n return false\n})()\n\nconst sheetsMap = new Map()\n\nexport function updateStyle(id: string, content: string): void {\n let style = sheetsMap.get(id)\n if (supportsConstructedSheet && !content.includes('@import')) {\n if (style && !(style instanceof CSSStyleSheet)) {\n removeStyle(id)\n style = undefined\n }\n\n if (!style) {\n style = new CSSStyleSheet()\n style.replaceSync(content)\n // @ts-ignore\n document.adoptedStyleSheets = [...document.adoptedStyleSheets, style]\n } else {\n style.replaceSync(content)\n }\n } else {\n if (style && !(style instanceof HTMLStyleElement)) {\n removeStyle(id)\n style = undefined\n }\n\n if (!style) {\n style = document.createElement('style')\n style.setAttribute('type', 'text/css')\n style.innerHTML = content\n document.head.appendChild(style)\n } else {\n style.innerHTML = content\n }\n }\n sheetsMap.set(id, style)\n}\n\nexport function removeStyle(id: string): void {\n const style = sheetsMap.get(id)\n if (style) {\n if (style instanceof CSSStyleSheet) {\n // @ts-ignore\n const index = document.adoptedStyleSheets.indexOf(style)\n // @ts-ignore\n document.adoptedStyleSheets = document.adoptedStyleSheets.filter(\n (s: CSSStyleSheet) => s !== style\n )\n } else {\n document.head.removeChild(style)\n }\n sheetsMap.delete(id)\n }\n}\n\nasync function fetchUpdate({ path, acceptedPath, timestamp }: Update) {\n const mod = hotModulesMap.get(path)\n if (!mod) {\n // In a code-splitting project,\n // it is common that the hot-updating module is not loaded yet.\n // https://github.com/vitejs/vite/issues/721\n return\n }\n\n const moduleMap = new Map()\n const isSelfUpdate = path === acceptedPath\n\n // make sure we only import each dep once\n const modulesToUpdate = new Set()\n if (isSelfUpdate) {\n // self update - only update self\n modulesToUpdate.add(path)\n } else {\n // dep update\n for (const { deps } of mod.callbacks) {\n deps.forEach((dep) => {\n if (acceptedPath === dep) {\n modulesToUpdate.add(dep)\n }\n })\n }\n }\n\n // determine the qualified callbacks before we re-import the modules\n const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {\n return deps.some((dep) => modulesToUpdate.has(dep))\n })\n\n await Promise.all(\n Array.from(modulesToUpdate).map(async (dep) => {\n const disposer = disposeMap.get(dep)\n if (disposer) await disposer(dataMap.get(dep))\n const [path, query] = dep.split(`?`)\n try {\n const newMod = await import(\n /* @vite-ignore */\n base +\n path.slice(1) +\n `?import&t=${timestamp}${query ? `&${query}` : ''}`\n )\n moduleMap.set(dep, newMod)\n } catch (e) {\n warnFailedFetch(e, dep)\n }\n })\n )\n\n return () => {\n for (const { deps, fn } of qualifiedCallbacks) {\n fn(deps.map((dep) => moduleMap.get(dep)))\n }\n const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`\n console.log(`[vite] hot updated: ${loggedPath}`)\n }\n}\n\ninterface HotModule {\n id: string\n callbacks: HotCallback[]\n}\n\ninterface HotCallback {\n // the dependencies must be fetchable paths\n deps: string[]\n fn: (modules: object[]) => void\n}\n\nconst hotModulesMap = new Map()\nconst disposeMap = new Map void | Promise>()\nconst pruneMap = new Map void | Promise>()\nconst dataMap = new Map()\nconst customListenersMap = new Map void)[]>()\nconst ctxToListenersMap = new Map<\n string,\n Map void)[]>\n>()\n\n// Just infer the return type for now\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport const createHotContext = (ownerPath: string) => {\n if (!dataMap.has(ownerPath)) {\n dataMap.set(ownerPath, {})\n }\n\n // when a file is hot updated, a new context is created\n // clear its stale callbacks\n const mod = hotModulesMap.get(ownerPath)\n if (mod) {\n mod.callbacks = []\n }\n\n // clear stale custom event listeners\n const staleListeners = ctxToListenersMap.get(ownerPath)\n if (staleListeners) {\n for (const [event, staleFns] of staleListeners) {\n const listeners = customListenersMap.get(event)\n if (listeners) {\n customListenersMap.set(\n event,\n listeners.filter((l) => !staleFns.includes(l))\n )\n }\n }\n }\n\n const newListeners = new Map()\n ctxToListenersMap.set(ownerPath, newListeners)\n\n function acceptDeps(deps: string[], callback: HotCallback['fn'] = () => {}) {\n const mod: HotModule = hotModulesMap.get(ownerPath) || {\n id: ownerPath,\n callbacks: []\n }\n mod.callbacks.push({\n deps,\n fn: callback\n })\n hotModulesMap.set(ownerPath, mod)\n }\n\n const hot = {\n get data() {\n return dataMap.get(ownerPath)\n },\n\n accept(deps: any, callback?: any) {\n if (typeof deps === 'function' || !deps) {\n // self-accept: hot.accept(() => {})\n acceptDeps([ownerPath], ([mod]) => deps && deps(mod))\n } else if (typeof deps === 'string') {\n // explicit deps\n acceptDeps([deps], ([mod]) => callback && callback(mod))\n } else if (Array.isArray(deps)) {\n acceptDeps(deps, callback)\n } else {\n throw new Error(`invalid hot.accept() usage.`)\n }\n },\n\n acceptDeps() {\n throw new Error(\n `hot.acceptDeps() is deprecated. ` +\n `Use hot.accept() with the same signature instead.`\n )\n },\n\n dispose(cb: (data: any) => void) {\n disposeMap.set(ownerPath, cb)\n },\n\n prune(cb: (data: any) => void) {\n pruneMap.set(ownerPath, cb)\n },\n\n // TODO\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n decline() {},\n\n invalidate() {\n // TODO should tell the server to re-perform hmr propagation\n // from this module as root\n location.reload()\n },\n\n // custom events\n on: (event: string, cb: (data: any) => void) => {\n const addToMap = (map: Map) => {\n const existing = map.get(event) || []\n existing.push(cb)\n map.set(event, existing)\n }\n addToMap(customListenersMap)\n addToMap(newListeners)\n }\n }\n\n return hot\n}\n\n/**\n * urls here are dynamic import() urls that couldn't be statically analyzed\n */\nexport function injectQuery(url: string, queryToInject: string): string {\n // skip urls that won't be handled by vite\n if (!url.startsWith('.') && !url.startsWith('/')) {\n return url\n }\n\n // can't use pathname from URL since it may be relative like ../\n const pathname = url.replace(/#.*$/, '').replace(/\\?.*$/, '')\n const { search, hash } = new URL(url, 'http://vitejs.dev')\n\n return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${\n hash || ''\n }`\n}\n"],"names":[],"mappings":";;AAEA,MAAM,QAAQ,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;IAC7D,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,mBAAmB,CAAC,CAAA;IAE1D,OAAO,GAAG,QAAQ,IAAI,aAAa,GAAG,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,GACvE,IAAI,IAAI,EACV,EAAE,CAAA;AACJ;;;;"} \ No newline at end of file diff --git a/packages/astro/vendor/vite/dist/client/env.mjs b/packages/astro/vendor/vite/dist/client/env.mjs deleted file mode 100755 index 1b3a7d26e9ea..000000000000 --- a/packages/astro/vendor/vite/dist/client/env.mjs +++ /dev/null @@ -1,30 +0,0 @@ -const context = (() => { - if (typeof globalThis !== 'undefined') { - return globalThis; - } - else if (typeof self !== 'undefined') { - return self; - } - else if (typeof window !== 'undefined') { - return window; - } - else { - return Function('return this')(); - } -})(); -// assign defines -const defines = __DEFINES__; -Object.keys(defines).forEach((key) => { - const segments = key.split('.'); - let target = context; - for (let i = 0; i < segments.length; i++) { - const segment = segments[i]; - if (i === segments.length - 1) { - target[segment] = defines[key]; - } - else { - target = target[segment] || (target[segment] = {}); - } - } -}); -//# sourceMappingURL=env.mjs.map diff --git a/packages/astro/vendor/vite/dist/client/env.mjs.map b/packages/astro/vendor/vite/dist/client/env.mjs.map deleted file mode 100755 index 592b5231c273..000000000000 --- a/packages/astro/vendor/vite/dist/client/env.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"env.mjs","sources":["../../src/client/env.ts"],"sourcesContent":["declare const __MODE__: string\ndeclare const __DEFINES__: Record\n\nconst context = (() => {\n if (typeof globalThis !== 'undefined') {\n return globalThis\n } else if (typeof self !== 'undefined') {\n return self\n } else if (typeof window !== 'undefined') {\n return window\n } else {\n return Function('return this')()\n }\n})()\n\n// assign defines\nconst defines = __DEFINES__\nObject.keys(defines).forEach((key) => {\n const segments = key.split('.')\n let target = context\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]\n if (i === segments.length - 1) {\n target[segment] = defines[key]\n } else {\n target = target[segment] || (target[segment] = {})\n }\n }\n})\n"],"names":[],"mappings":"AAGA,MAAM,OAAO,GAAG,CAAC;IACf,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE;QACrC,OAAO,UAAU,CAAA;KAClB;SAAM,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QACtC,OAAO,IAAI,CAAA;KACZ;SAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACxC,OAAO,MAAM,CAAA;KACd;SAAM;QACL,OAAO,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAA;KACjC;AACH,CAAC,GAAG,CAAA;AAEJ;AACA,MAAM,OAAO,GAAG,WAAW,CAAA;AAC3B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG;IAC/B,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC/B,IAAI,MAAM,GAAG,OAAO,CAAA;IACpB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;QAC3B,IAAI,CAAC,KAAK,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YAC7B,MAAM,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;SAC/B;aAAM;YACL,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;SACnD;KACF;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/packages/astro/vendor/vite/dist/node/chunks/dep-34d2edc0.js b/packages/astro/vendor/vite/dist/node/chunks/dep-34d2edc0.js deleted file mode 100755 index ffbcca5833f8..000000000000 --- a/packages/astro/vendor/vite/dist/node/chunks/dep-34d2edc0.js +++ /dev/null @@ -1,29182 +0,0 @@ -'use strict'; - -var build = require('./dep-35df7f96.js'); -var require$$1 = require('crypto'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; } - -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - var e = m[i]; - for (var k in e) { - if (k !== 'default' && !(k in n)) { - n[k] = e[k]; - } - } - } - return n; -} - -var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); - -var selfsigned = {}; - -/** - * Node.js module for Forge. - * - * @author Dave Longley - * - * Copyright 2011-2016 Digital Bazaar, Inc. - */ - -var forge$F = { - // default options - options: { - usePureJavaScript: false - } -}; - -/** - * Base-N/Base-X encoding/decoding functions. - * - * Original implementation from base-x: - * https://github.com/cryptocoinjs/base-x - * - * Which is MIT licensed: - * - * The MIT License (MIT) - * - * Copyright base-x contributors (c) 2016 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - */ - -var api = {}; -var baseN$1 = api; - -// baseN alphabet indexes -var _reverseAlphabets = {}; - -/** - * BaseN-encodes a Uint8Array using the given alphabet. - * - * @param input the Uint8Array to encode. - * @param maxline the maximum number of encoded characters per line to use, - * defaults to none. - * - * @return the baseN-encoded output string. - */ -api.encode = function(input, alphabet, maxline) { - if(typeof alphabet !== 'string') { - throw new TypeError('"alphabet" must be a string.'); - } - if(maxline !== undefined && typeof maxline !== 'number') { - throw new TypeError('"maxline" must be a number.'); - } - - var output = ''; - - if(!(input instanceof Uint8Array)) { - // assume forge byte buffer - output = _encodeWithByteBuffer(input, alphabet); - } else { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for(i = 0; i < input.length; ++i) { - for(var j = 0, carry = input[i]; j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = (carry / base) | 0; - } - - while(carry > 0) { - digits.push(carry % base); - carry = (carry / base) | 0; - } - } - - // deal with leading zeros - for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { - output += first; - } - // convert digits to a string - for(i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; - } - } - - if(maxline) { - var regex = new RegExp('.{1,' + maxline + '}', 'g'); - output = output.match(regex).join('\r\n'); - } - - return output; -}; - -/** - * Decodes a baseN-encoded (using the given alphabet) string to a - * Uint8Array. - * - * @param input the baseN-encoded input string. - * - * @return the Uint8Array. - */ -api.decode = function(input, alphabet) { - if(typeof input !== 'string') { - throw new TypeError('"input" must be a string.'); - } - if(typeof alphabet !== 'string') { - throw new TypeError('"alphabet" must be a string.'); - } - - var table = _reverseAlphabets[alphabet]; - if(!table) { - // compute reverse alphabet - table = _reverseAlphabets[alphabet] = []; - for(var i = 0; i < alphabet.length; ++i) { - table[alphabet.charCodeAt(i)] = i; - } - } - - // remove whitespace characters - input = input.replace(/\s/g, ''); - - var base = alphabet.length; - var first = alphabet.charAt(0); - var bytes = [0]; - for(var i = 0; i < input.length; i++) { - var value = table[input.charCodeAt(i)]; - if(value === undefined) { - return; - } - - for(var j = 0, carry = value; j < bytes.length; ++j) { - carry += bytes[j] * base; - bytes[j] = carry & 0xff; - carry >>= 8; - } - - while(carry > 0) { - bytes.push(carry & 0xff); - carry >>= 8; - } - } - - // deal with leading zeros - for(var k = 0; input[k] === first && k < input.length - 1; ++k) { - bytes.push(0); - } - - if(typeof Buffer !== 'undefined') { - return Buffer.from(bytes.reverse()); - } - - return new Uint8Array(bytes.reverse()); -}; - -function _encodeWithByteBuffer(input, alphabet) { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for(i = 0; i < input.length(); ++i) { - for(var j = 0, carry = input.at(i); j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = (carry / base) | 0; - } - - while(carry > 0) { - digits.push(carry % base); - carry = (carry / base) | 0; - } - } - - var output = ''; - - // deal with leading zeros - for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { - output += first; - } - // convert digits to a string - for(i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; - } - - return output; -} - -/** - * Utility functions for web applications. - * - * @author Dave Longley - * - * Copyright (c) 2010-2018 Digital Bazaar, Inc. - */ - -var forge$E = forge$F; -var baseN = baseN$1; - -/* Utilities API */ -var util$1 = forge$E.util = forge$E.util || {}; - -// define setImmediate and nextTick -(function() { - // use native nextTick (unless we're in webpack) - // webpack (or better node-libs-browser polyfill) sets process.browser. - // this way we can detect webpack properly - if(typeof process !== 'undefined' && process.nextTick && !process.browser) { - util$1.nextTick = process.nextTick; - if(typeof setImmediate === 'function') { - util$1.setImmediate = setImmediate; - } else { - // polyfill setImmediate with nextTick, older versions of node - // (those w/o setImmediate) won't totally starve IO - util$1.setImmediate = util$1.nextTick; - } - return; - } - - // polyfill nextTick with native setImmediate - if(typeof setImmediate === 'function') { - util$1.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; - util$1.nextTick = function(callback) { - return setImmediate(callback); - }; - return; - } - - /* Note: A polyfill upgrade pattern is used here to allow combining - polyfills. For example, MutationObserver is fast, but blocks UI updates, - so it needs to allow UI updates periodically, so it falls back on - postMessage or setTimeout. */ - - // polyfill with setTimeout - util$1.setImmediate = function(callback) { - setTimeout(callback, 0); - }; - - // upgrade polyfill to use postMessage - if(typeof window !== 'undefined' && - typeof window.postMessage === 'function') { - var msg = 'forge.setImmediate'; - var callbacks = []; - util$1.setImmediate = function(callback) { - callbacks.push(callback); - // only send message when one hasn't been sent in - // the current turn of the event loop - if(callbacks.length === 1) { - window.postMessage(msg, '*'); - } - }; - function handler(event) { - if(event.source === window && event.data === msg) { - event.stopPropagation(); - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - } - } - window.addEventListener('message', handler, true); - } - - // upgrade polyfill to use MutationObserver - if(typeof MutationObserver !== 'undefined') { - // polyfill with MutationObserver - var now = Date.now(); - var attr = true; - var div = document.createElement('div'); - var callbacks = []; - new MutationObserver(function() { - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - }).observe(div, {attributes: true}); - var oldSetImmediate = util$1.setImmediate; - util$1.setImmediate = function(callback) { - if(Date.now() - now > 15) { - now = Date.now(); - oldSetImmediate(callback); - } else { - callbacks.push(callback); - // only trigger observer when it hasn't been triggered in - // the current turn of the event loop - if(callbacks.length === 1) { - div.setAttribute('a', attr = !attr); - } - } - }; - } - - util$1.nextTick = util$1.setImmediate; -})(); - -// check if running under Node.js -util$1.isNodejs = - typeof process !== 'undefined' && process.versions && process.versions.node; - - -// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while -// it will point to `window` in the main thread. -// To remain compatible with older browsers, we fall back to 'window' if 'self' -// is not available. -util$1.globalScope = (function() { - if(util$1.isNodejs) { - return build.commonjsGlobal; - } - - return typeof self === 'undefined' ? window : self; -})(); - -// define isArray -util$1.isArray = Array.isArray || function(x) { - return Object.prototype.toString.call(x) === '[object Array]'; -}; - -// define isArrayBuffer -util$1.isArrayBuffer = function(x) { - return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; -}; - -// define isArrayBufferView -util$1.isArrayBufferView = function(x) { - return x && util$1.isArrayBuffer(x.buffer) && x.byteLength !== undefined; -}; - -/** - * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for - * algorithms where bit manipulation, JavaScript limitations, and/or algorithm - * design only allow for byte operations of a limited size. - * - * @param n number of bits. - * - * Throw Error if n invalid. - */ -function _checkBitsParam(n) { - if(!(n === 8 || n === 16 || n === 24 || n === 32)) { - throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); - } -} - -// TODO: set ByteBuffer to best available backing -util$1.ByteBuffer = ByteStringBuffer; - -/** Buffer w/BinaryString backing */ - -/** - * Constructor for a binary string backed byte buffer. - * - * @param [b] the bytes to wrap (either encoded as string, one byte per - * character, or as an ArrayBuffer or Typed Array). - */ -function ByteStringBuffer(b) { - // TODO: update to match DataBuffer API - - // the data in this buffer - this.data = ''; - // the pointer for reading from this buffer - this.read = 0; - - if(typeof b === 'string') { - this.data = b; - } else if(util$1.isArrayBuffer(b) || util$1.isArrayBufferView(b)) { - if(typeof Buffer !== 'undefined' && b instanceof Buffer) { - this.data = b.toString('binary'); - } else { - // convert native buffer to forge buffer - // FIXME: support native buffers internally instead - var arr = new Uint8Array(b); - try { - this.data = String.fromCharCode.apply(null, arr); - } catch(e) { - for(var i = 0; i < arr.length; ++i) { - this.putByte(arr[i]); - } - } - } - } else if(b instanceof ByteStringBuffer || - (typeof b === 'object' && typeof b.data === 'string' && - typeof b.read === 'number')) { - // copy existing buffer - this.data = b.data; - this.read = b.read; - } - - // used for v8 optimization - this._constructedStringLength = 0; -} -util$1.ByteStringBuffer = ByteStringBuffer; - -/* Note: This is an optimization for V8-based browsers. When V8 concatenates - a string, the strings are only joined logically using a "cons string" or - "constructed/concatenated string". These containers keep references to one - another and can result in very large memory usage. For example, if a 2MB - string is constructed by concatenating 4 bytes together at a time, the - memory usage will be ~44MB; so ~22x increase. The strings are only joined - together when an operation requiring their joining takes place, such as - substr(). This function is called when adding data to this buffer to ensure - these types of strings are periodically joined to reduce the memory - footprint. */ -var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; -util$1.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { - this._constructedStringLength += x; - if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { - // this substr() should cause the constructed string to join - this.data.substr(0, 1); - this._constructedStringLength = 0; - } -}; - -/** - * Gets the number of bytes in this buffer. - * - * @return the number of bytes in this buffer. - */ -util$1.ByteStringBuffer.prototype.length = function() { - return this.data.length - this.read; -}; - -/** - * Gets whether or not this buffer is empty. - * - * @return true if this buffer is empty, false if not. - */ -util$1.ByteStringBuffer.prototype.isEmpty = function() { - return this.length() <= 0; -}; - -/** - * Puts a byte in this buffer. - * - * @param b the byte to put. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putByte = function(b) { - return this.putBytes(String.fromCharCode(b)); -}; - -/** - * Puts a byte in this buffer N times. - * - * @param b the byte to put. - * @param n the number of bytes of value b to put. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.fillWithByte = function(b, n) { - b = String.fromCharCode(b); - var d = this.data; - while(n > 0) { - if(n & 1) { - d += b; - } - n >>>= 1; - if(n > 0) { - b += b; - } - } - this.data = d; - this._optimizeConstructedString(n); - return this; -}; - -/** - * Puts bytes in this buffer. - * - * @param bytes the bytes (as a binary encoded string) to put. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putBytes = function(bytes) { - this.data += bytes; - this._optimizeConstructedString(bytes.length); - return this; -}; - -/** - * Puts a UTF-16 encoded string into this buffer. - * - * @param str the string to put. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putString = function(str) { - return this.putBytes(util$1.encodeUtf8(str)); -}; - -/** - * Puts a 16-bit integer in this buffer in big-endian order. - * - * @param i the 16-bit integer. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putInt16 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i & 0xFF)); -}; - -/** - * Puts a 24-bit integer in this buffer in big-endian order. - * - * @param i the 24-bit integer. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putInt24 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 16 & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i & 0xFF)); -}; - -/** - * Puts a 32-bit integer in this buffer in big-endian order. - * - * @param i the 32-bit integer. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putInt32 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 24 & 0xFF) + - String.fromCharCode(i >> 16 & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i & 0xFF)); -}; - -/** - * Puts a 16-bit integer in this buffer in little-endian order. - * - * @param i the 16-bit integer. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putInt16Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF)); -}; - -/** - * Puts a 24-bit integer in this buffer in little-endian order. - * - * @param i the 24-bit integer. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putInt24Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i >> 16 & 0xFF)); -}; - -/** - * Puts a 32-bit integer in this buffer in little-endian order. - * - * @param i the 32-bit integer. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putInt32Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i >> 16 & 0xFF) + - String.fromCharCode(i >> 24 & 0xFF)); -}; - -/** - * Puts an n-bit integer in this buffer in big-endian order. - * - * @param i the n-bit integer. - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - var bytes = ''; - do { - n -= 8; - bytes += String.fromCharCode((i >> n) & 0xFF); - } while(n > 0); - return this.putBytes(bytes); -}; - -/** - * Puts a signed n-bit integer in this buffer in big-endian order. Two's - * complement representation is used. - * - * @param i the n-bit integer. - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putSignedInt = function(i, n) { - // putInt checks n - if(i < 0) { - i += 2 << (n - 1); - } - return this.putInt(i, n); -}; - -/** - * Puts the given buffer into this buffer. - * - * @param buffer the buffer to put into this one. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.putBuffer = function(buffer) { - return this.putBytes(buffer.getBytes()); -}; - -/** - * Gets a byte from this buffer and advances the read pointer by 1. - * - * @return the byte. - */ -util$1.ByteStringBuffer.prototype.getByte = function() { - return this.data.charCodeAt(this.read++); -}; - -/** - * Gets a uint16 from this buffer in big-endian order and advances the read - * pointer by 2. - * - * @return the uint16. - */ -util$1.ByteStringBuffer.prototype.getInt16 = function() { - var rval = ( - this.data.charCodeAt(this.read) << 8 ^ - this.data.charCodeAt(this.read + 1)); - this.read += 2; - return rval; -}; - -/** - * Gets a uint24 from this buffer in big-endian order and advances the read - * pointer by 3. - * - * @return the uint24. - */ -util$1.ByteStringBuffer.prototype.getInt24 = function() { - var rval = ( - this.data.charCodeAt(this.read) << 16 ^ - this.data.charCodeAt(this.read + 1) << 8 ^ - this.data.charCodeAt(this.read + 2)); - this.read += 3; - return rval; -}; - -/** - * Gets a uint32 from this buffer in big-endian order and advances the read - * pointer by 4. - * - * @return the word. - */ -util$1.ByteStringBuffer.prototype.getInt32 = function() { - var rval = ( - this.data.charCodeAt(this.read) << 24 ^ - this.data.charCodeAt(this.read + 1) << 16 ^ - this.data.charCodeAt(this.read + 2) << 8 ^ - this.data.charCodeAt(this.read + 3)); - this.read += 4; - return rval; -}; - -/** - * Gets a uint16 from this buffer in little-endian order and advances the read - * pointer by 2. - * - * @return the uint16. - */ -util$1.ByteStringBuffer.prototype.getInt16Le = function() { - var rval = ( - this.data.charCodeAt(this.read) ^ - this.data.charCodeAt(this.read + 1) << 8); - this.read += 2; - return rval; -}; - -/** - * Gets a uint24 from this buffer in little-endian order and advances the read - * pointer by 3. - * - * @return the uint24. - */ -util$1.ByteStringBuffer.prototype.getInt24Le = function() { - var rval = ( - this.data.charCodeAt(this.read) ^ - this.data.charCodeAt(this.read + 1) << 8 ^ - this.data.charCodeAt(this.read + 2) << 16); - this.read += 3; - return rval; -}; - -/** - * Gets a uint32 from this buffer in little-endian order and advances the read - * pointer by 4. - * - * @return the word. - */ -util$1.ByteStringBuffer.prototype.getInt32Le = function() { - var rval = ( - this.data.charCodeAt(this.read) ^ - this.data.charCodeAt(this.read + 1) << 8 ^ - this.data.charCodeAt(this.read + 2) << 16 ^ - this.data.charCodeAt(this.read + 3) << 24); - this.read += 4; - return rval; -}; - -/** - * Gets an n-bit integer from this buffer in big-endian order and advances the - * read pointer by ceil(n/8). - * - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return the integer. - */ -util$1.ByteStringBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. - rval = (rval << 8) + this.data.charCodeAt(this.read++); - n -= 8; - } while(n > 0); - return rval; -}; - -/** - * Gets a signed n-bit integer from this buffer in big-endian order, using - * two's complement, and advances the read pointer by n/8. - * - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return the integer. - */ -util$1.ByteStringBuffer.prototype.getSignedInt = function(n) { - // getInt checks n - var x = this.getInt(n); - var max = 2 << (n - 2); - if(x >= max) { - x -= max << 1; - } - return x; -}; - -/** - * Reads bytes out as a binary encoded string and clears them from the - * buffer. Note that the resulting string is binary encoded (in node.js this - * encoding is referred to as `binary`, it is *not* `utf8`). - * - * @param count the number of bytes to read, undefined or null for all. - * - * @return a binary encoded string of bytes. - */ -util$1.ByteStringBuffer.prototype.getBytes = function(count) { - var rval; - if(count) { - // read count bytes - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if(count === 0) { - rval = ''; - } else { - // read all bytes, optimize to only copy when needed - rval = (this.read === 0) ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; -}; - -/** - * Gets a binary encoded string of the bytes from this buffer without - * modifying the read pointer. - * - * @param count the number of bytes to get, omit to get all. - * - * @return a string full of binary encoded characters. - */ -util$1.ByteStringBuffer.prototype.bytes = function(count) { - return (typeof(count) === 'undefined' ? - this.data.slice(this.read) : - this.data.slice(this.read, this.read + count)); -}; - -/** - * Gets a byte at the given index without modifying the read pointer. - * - * @param i the byte index. - * - * @return the byte. - */ -util$1.ByteStringBuffer.prototype.at = function(i) { - return this.data.charCodeAt(this.read + i); -}; - -/** - * Puts a byte at the given index without modifying the read pointer. - * - * @param i the byte index. - * @param b the byte to put. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.setAt = function(i, b) { - this.data = this.data.substr(0, this.read + i) + - String.fromCharCode(b) + - this.data.substr(this.read + i + 1); - return this; -}; - -/** - * Gets the last byte without modifying the read pointer. - * - * @return the last byte. - */ -util$1.ByteStringBuffer.prototype.last = function() { - return this.data.charCodeAt(this.data.length - 1); -}; - -/** - * Creates a copy of this buffer. - * - * @return the copy. - */ -util$1.ByteStringBuffer.prototype.copy = function() { - var c = util$1.createBuffer(this.data); - c.read = this.read; - return c; -}; - -/** - * Compacts this buffer. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.compact = function() { - if(this.read > 0) { - this.data = this.data.slice(this.read); - this.read = 0; - } - return this; -}; - -/** - * Clears this buffer. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.clear = function() { - this.data = ''; - this.read = 0; - return this; -}; - -/** - * Shortens this buffer by triming bytes off of the end of this buffer. - * - * @param count the number of bytes to trim off. - * - * @return this buffer. - */ -util$1.ByteStringBuffer.prototype.truncate = function(count) { - var len = Math.max(0, this.length() - count); - this.data = this.data.substr(this.read, len); - this.read = 0; - return this; -}; - -/** - * Converts this buffer to a hexadecimal string. - * - * @return a hexadecimal string. - */ -util$1.ByteStringBuffer.prototype.toHex = function() { - var rval = ''; - for(var i = this.read; i < this.data.length; ++i) { - var b = this.data.charCodeAt(i); - if(b < 16) { - rval += '0'; - } - rval += b.toString(16); - } - return rval; -}; - -/** - * Converts this buffer to a UTF-16 string (standard JavaScript string). - * - * @return a UTF-16 string. - */ -util$1.ByteStringBuffer.prototype.toString = function() { - return util$1.decodeUtf8(this.bytes()); -}; - -/** End Buffer w/BinaryString backing */ - -/** Buffer w/UInt8Array backing */ - -/** - * FIXME: Experimental. Do not use yet. - * - * Constructor for an ArrayBuffer-backed byte buffer. - * - * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a - * TypedArray. - * - * If a string is given, its encoding should be provided as an option, - * otherwise it will default to 'binary'. A 'binary' string is encoded such - * that each character is one byte in length and size. - * - * If an ArrayBuffer, DataView, or TypedArray is given, it will be used - * *directly* without any copying. Note that, if a write to the buffer requires - * more space, the buffer will allocate a new backing ArrayBuffer to - * accommodate. The starting read and write offsets for the buffer may be - * given as options. - * - * @param [b] the initial bytes for this buffer. - * @param options the options to use: - * [readOffset] the starting read offset to use (default: 0). - * [writeOffset] the starting write offset to use (default: the - * length of the first parameter). - * [growSize] the minimum amount, in bytes, to grow the buffer by to - * accommodate writes (default: 1024). - * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the - * first parameter, if it is a string (default: 'binary'). - */ -function DataBuffer(b, options) { - // default options - options = options || {}; - - // pointers for read from/write to buffer - this.read = options.readOffset || 0; - this.growSize = options.growSize || 1024; - - var isArrayBuffer = util$1.isArrayBuffer(b); - var isArrayBufferView = util$1.isArrayBufferView(b); - if(isArrayBuffer || isArrayBufferView) { - // use ArrayBuffer directly - if(isArrayBuffer) { - this.data = new DataView(b); - } else { - // TODO: adjust read/write offset based on the type of view - // or specify that this must be done in the options ... that the - // offsets are byte-based - this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); - } - this.write = ('writeOffset' in options ? - options.writeOffset : this.data.byteLength); - return; - } - - // initialize to empty array buffer and add any given bytes using putBytes - this.data = new DataView(new ArrayBuffer(0)); - this.write = 0; - - if(b !== null && b !== undefined) { - this.putBytes(b); - } - - if('writeOffset' in options) { - this.write = options.writeOffset; - } -} -util$1.DataBuffer = DataBuffer; - -/** - * Gets the number of bytes in this buffer. - * - * @return the number of bytes in this buffer. - */ -util$1.DataBuffer.prototype.length = function() { - return this.write - this.read; -}; - -/** - * Gets whether or not this buffer is empty. - * - * @return true if this buffer is empty, false if not. - */ -util$1.DataBuffer.prototype.isEmpty = function() { - return this.length() <= 0; -}; - -/** - * Ensures this buffer has enough empty space to accommodate the given number - * of bytes. An optional parameter may be given that indicates a minimum - * amount to grow the buffer if necessary. If the parameter is not given, - * the buffer will be grown by some previously-specified default amount - * or heuristic. - * - * @param amount the number of bytes to accommodate. - * @param [growSize] the minimum amount, in bytes, to grow the buffer by if - * necessary. - */ -util$1.DataBuffer.prototype.accommodate = function(amount, growSize) { - if(this.length() >= amount) { - return this; - } - growSize = Math.max(growSize || this.growSize, amount); - - // grow buffer - var src = new Uint8Array( - this.data.buffer, this.data.byteOffset, this.data.byteLength); - var dst = new Uint8Array(this.length() + growSize); - dst.set(src); - this.data = new DataView(dst.buffer); - - return this; -}; - -/** - * Puts a byte in this buffer. - * - * @param b the byte to put. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putByte = function(b) { - this.accommodate(1); - this.data.setUint8(this.write++, b); - return this; -}; - -/** - * Puts a byte in this buffer N times. - * - * @param b the byte to put. - * @param n the number of bytes of value b to put. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.fillWithByte = function(b, n) { - this.accommodate(n); - for(var i = 0; i < n; ++i) { - this.data.setUint8(b); - } - return this; -}; - -/** - * Puts bytes in this buffer. The bytes may be given as a string, an - * ArrayBuffer, a DataView, or a TypedArray. - * - * @param bytes the bytes to put. - * @param [encoding] the encoding for the first parameter ('binary', 'utf8', - * 'utf16', 'hex'), if it is a string (default: 'binary'). - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putBytes = function(bytes, encoding) { - if(util$1.isArrayBufferView(bytes)) { - var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); - var len = src.byteLength - src.byteOffset; - this.accommodate(len); - var dst = new Uint8Array(this.data.buffer, this.write); - dst.set(src); - this.write += len; - return this; - } - - if(util$1.isArrayBuffer(bytes)) { - var src = new Uint8Array(bytes); - this.accommodate(src.byteLength); - var dst = new Uint8Array(this.data.buffer); - dst.set(src, this.write); - this.write += src.byteLength; - return this; - } - - // bytes is a util.DataBuffer or equivalent - if(bytes instanceof util$1.DataBuffer || - (typeof bytes === 'object' && - typeof bytes.read === 'number' && typeof bytes.write === 'number' && - util$1.isArrayBufferView(bytes.data))) { - var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); - this.accommodate(src.byteLength); - var dst = new Uint8Array(bytes.data.byteLength, this.write); - dst.set(src); - this.write += src.byteLength; - return this; - } - - if(bytes instanceof util$1.ByteStringBuffer) { - // copy binary string and process as the same as a string parameter below - bytes = bytes.data; - encoding = 'binary'; - } - - // string conversion - encoding = encoding || 'binary'; - if(typeof bytes === 'string') { - var view; - - // decode from string - if(encoding === 'hex') { - this.accommodate(Math.ceil(bytes.length / 2)); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util$1.binary.hex.decode(bytes, view, this.write); - return this; - } - if(encoding === 'base64') { - this.accommodate(Math.ceil(bytes.length / 4) * 3); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util$1.binary.base64.decode(bytes, view, this.write); - return this; - } - - // encode text as UTF-8 bytes - if(encoding === 'utf8') { - // encode as UTF-8 then decode string as raw binary - bytes = util$1.encodeUtf8(bytes); - encoding = 'binary'; - } - - // decode string as raw binary - if(encoding === 'binary' || encoding === 'raw') { - // one byte per character - this.accommodate(bytes.length); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util$1.binary.raw.decode(view); - return this; - } - - // encode text as UTF-16 bytes - if(encoding === 'utf16') { - // two bytes per character - this.accommodate(bytes.length * 2); - view = new Uint16Array(this.data.buffer, this.write); - this.write += util$1.text.utf16.encode(view); - return this; - } - - throw new Error('Invalid encoding: ' + encoding); - } - - throw Error('Invalid parameter: ' + bytes); -}; - -/** - * Puts the given buffer into this buffer. - * - * @param buffer the buffer to put into this one. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putBuffer = function(buffer) { - this.putBytes(buffer); - buffer.clear(); - return this; -}; - -/** - * Puts a string into this buffer. - * - * @param str the string to put. - * @param [encoding] the encoding for the string (default: 'utf16'). - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putString = function(str) { - return this.putBytes(str, 'utf16'); -}; - -/** - * Puts a 16-bit integer in this buffer in big-endian order. - * - * @param i the 16-bit integer. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putInt16 = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i); - this.write += 2; - return this; -}; - -/** - * Puts a 24-bit integer in this buffer in big-endian order. - * - * @param i the 24-bit integer. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putInt24 = function(i) { - this.accommodate(3); - this.data.setInt16(this.write, i >> 8 & 0xFFFF); - this.data.setInt8(this.write, i >> 16 & 0xFF); - this.write += 3; - return this; -}; - -/** - * Puts a 32-bit integer in this buffer in big-endian order. - * - * @param i the 32-bit integer. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putInt32 = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i); - this.write += 4; - return this; -}; - -/** - * Puts a 16-bit integer in this buffer in little-endian order. - * - * @param i the 16-bit integer. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putInt16Le = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i, true); - this.write += 2; - return this; -}; - -/** - * Puts a 24-bit integer in this buffer in little-endian order. - * - * @param i the 24-bit integer. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putInt24Le = function(i) { - this.accommodate(3); - this.data.setInt8(this.write, i >> 16 & 0xFF); - this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); - this.write += 3; - return this; -}; - -/** - * Puts a 32-bit integer in this buffer in little-endian order. - * - * @param i the 32-bit integer. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putInt32Le = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i, true); - this.write += 4; - return this; -}; - -/** - * Puts an n-bit integer in this buffer in big-endian order. - * - * @param i the n-bit integer. - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - do { - n -= 8; - this.data.setInt8(this.write++, (i >> n) & 0xFF); - } while(n > 0); - return this; -}; - -/** - * Puts a signed n-bit integer in this buffer in big-endian order. Two's - * complement representation is used. - * - * @param i the n-bit integer. - * @param n the number of bits in the integer. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.putSignedInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - if(i < 0) { - i += 2 << (n - 1); - } - return this.putInt(i, n); -}; - -/** - * Gets a byte from this buffer and advances the read pointer by 1. - * - * @return the byte. - */ -util$1.DataBuffer.prototype.getByte = function() { - return this.data.getInt8(this.read++); -}; - -/** - * Gets a uint16 from this buffer in big-endian order and advances the read - * pointer by 2. - * - * @return the uint16. - */ -util$1.DataBuffer.prototype.getInt16 = function() { - var rval = this.data.getInt16(this.read); - this.read += 2; - return rval; -}; - -/** - * Gets a uint24 from this buffer in big-endian order and advances the read - * pointer by 3. - * - * @return the uint24. - */ -util$1.DataBuffer.prototype.getInt24 = function() { - var rval = ( - this.data.getInt16(this.read) << 8 ^ - this.data.getInt8(this.read + 2)); - this.read += 3; - return rval; -}; - -/** - * Gets a uint32 from this buffer in big-endian order and advances the read - * pointer by 4. - * - * @return the word. - */ -util$1.DataBuffer.prototype.getInt32 = function() { - var rval = this.data.getInt32(this.read); - this.read += 4; - return rval; -}; - -/** - * Gets a uint16 from this buffer in little-endian order and advances the read - * pointer by 2. - * - * @return the uint16. - */ -util$1.DataBuffer.prototype.getInt16Le = function() { - var rval = this.data.getInt16(this.read, true); - this.read += 2; - return rval; -}; - -/** - * Gets a uint24 from this buffer in little-endian order and advances the read - * pointer by 3. - * - * @return the uint24. - */ -util$1.DataBuffer.prototype.getInt24Le = function() { - var rval = ( - this.data.getInt8(this.read) ^ - this.data.getInt16(this.read + 1, true) << 8); - this.read += 3; - return rval; -}; - -/** - * Gets a uint32 from this buffer in little-endian order and advances the read - * pointer by 4. - * - * @return the word. - */ -util$1.DataBuffer.prototype.getInt32Le = function() { - var rval = this.data.getInt32(this.read, true); - this.read += 4; - return rval; -}; - -/** - * Gets an n-bit integer from this buffer in big-endian order and advances the - * read pointer by n/8. - * - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return the integer. - */ -util$1.DataBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. - rval = (rval << 8) + this.data.getInt8(this.read++); - n -= 8; - } while(n > 0); - return rval; -}; - -/** - * Gets a signed n-bit integer from this buffer in big-endian order, using - * two's complement, and advances the read pointer by n/8. - * - * @param n the number of bits in the integer (8, 16, 24, or 32). - * - * @return the integer. - */ -util$1.DataBuffer.prototype.getSignedInt = function(n) { - // getInt checks n - var x = this.getInt(n); - var max = 2 << (n - 2); - if(x >= max) { - x -= max << 1; - } - return x; -}; - -/** - * Reads bytes out as a binary encoded string and clears them from the - * buffer. - * - * @param count the number of bytes to read, undefined or null for all. - * - * @return a binary encoded string of bytes. - */ -util$1.DataBuffer.prototype.getBytes = function(count) { - // TODO: deprecate this method, it is poorly named and - // this.toString('binary') replaces it - // add a toTypedArray()/toArrayBuffer() function - var rval; - if(count) { - // read count bytes - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if(count === 0) { - rval = ''; - } else { - // read all bytes, optimize to only copy when needed - rval = (this.read === 0) ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; -}; - -/** - * Gets a binary encoded string of the bytes from this buffer without - * modifying the read pointer. - * - * @param count the number of bytes to get, omit to get all. - * - * @return a string full of binary encoded characters. - */ -util$1.DataBuffer.prototype.bytes = function(count) { - // TODO: deprecate this method, it is poorly named, add "getString()" - return (typeof(count) === 'undefined' ? - this.data.slice(this.read) : - this.data.slice(this.read, this.read + count)); -}; - -/** - * Gets a byte at the given index without modifying the read pointer. - * - * @param i the byte index. - * - * @return the byte. - */ -util$1.DataBuffer.prototype.at = function(i) { - return this.data.getUint8(this.read + i); -}; - -/** - * Puts a byte at the given index without modifying the read pointer. - * - * @param i the byte index. - * @param b the byte to put. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.setAt = function(i, b) { - this.data.setUint8(i, b); - return this; -}; - -/** - * Gets the last byte without modifying the read pointer. - * - * @return the last byte. - */ -util$1.DataBuffer.prototype.last = function() { - return this.data.getUint8(this.write - 1); -}; - -/** - * Creates a copy of this buffer. - * - * @return the copy. - */ -util$1.DataBuffer.prototype.copy = function() { - return new util$1.DataBuffer(this); -}; - -/** - * Compacts this buffer. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.compact = function() { - if(this.read > 0) { - var src = new Uint8Array(this.data.buffer, this.read); - var dst = new Uint8Array(src.byteLength); - dst.set(src); - this.data = new DataView(dst); - this.write -= this.read; - this.read = 0; - } - return this; -}; - -/** - * Clears this buffer. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.clear = function() { - this.data = new DataView(new ArrayBuffer(0)); - this.read = this.write = 0; - return this; -}; - -/** - * Shortens this buffer by triming bytes off of the end of this buffer. - * - * @param count the number of bytes to trim off. - * - * @return this buffer. - */ -util$1.DataBuffer.prototype.truncate = function(count) { - this.write = Math.max(0, this.length() - count); - this.read = Math.min(this.read, this.write); - return this; -}; - -/** - * Converts this buffer to a hexadecimal string. - * - * @return a hexadecimal string. - */ -util$1.DataBuffer.prototype.toHex = function() { - var rval = ''; - for(var i = this.read; i < this.data.byteLength; ++i) { - var b = this.data.getUint8(i); - if(b < 16) { - rval += '0'; - } - rval += b.toString(16); - } - return rval; -}; - -/** - * Converts this buffer to a string, using the given encoding. If no - * encoding is given, 'utf8' (UTF-8) is used. - * - * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', - * 'base64' (default: 'utf8'). - * - * @return a string representation of the bytes in this buffer. - */ -util$1.DataBuffer.prototype.toString = function(encoding) { - var view = new Uint8Array(this.data, this.read, this.length()); - encoding = encoding || 'utf8'; - - // encode to string - if(encoding === 'binary' || encoding === 'raw') { - return util$1.binary.raw.encode(view); - } - if(encoding === 'hex') { - return util$1.binary.hex.encode(view); - } - if(encoding === 'base64') { - return util$1.binary.base64.encode(view); - } - - // decode to text - if(encoding === 'utf8') { - return util$1.text.utf8.decode(view); - } - if(encoding === 'utf16') { - return util$1.text.utf16.decode(view); - } - - throw new Error('Invalid encoding: ' + encoding); -}; - -/** End Buffer w/UInt8Array backing */ - -/** - * Creates a buffer that stores bytes. A value may be given to populate the - * buffer with data. This value can either be string of encoded bytes or a - * regular string of characters. When passing a string of binary encoded - * bytes, the encoding `raw` should be given. This is also the default. When - * passing a string of characters, the encoding `utf8` should be given. - * - * @param [input] a string with encoded bytes to store in the buffer. - * @param [encoding] (default: 'raw', other: 'utf8'). - */ -util$1.createBuffer = function(input, encoding) { - // TODO: deprecate, use new ByteBuffer() instead - encoding = encoding || 'raw'; - if(input !== undefined && encoding === 'utf8') { - input = util$1.encodeUtf8(input); - } - return new util$1.ByteBuffer(input); -}; - -/** - * Fills a string with a particular value. If you want the string to be a byte - * string, pass in String.fromCharCode(theByte). - * - * @param c the character to fill the string with, use String.fromCharCode - * to fill the string with a byte value. - * @param n the number of characters of value c to fill with. - * - * @return the filled string. - */ -util$1.fillString = function(c, n) { - var s = ''; - while(n > 0) { - if(n & 1) { - s += c; - } - n >>>= 1; - if(n > 0) { - c += c; - } - } - return s; -}; - -/** - * Performs a per byte XOR between two byte strings and returns the result as a - * string of bytes. - * - * @param s1 first string of bytes. - * @param s2 second string of bytes. - * @param n the number of bytes to XOR. - * - * @return the XOR'd result. - */ -util$1.xorBytes = function(s1, s2, n) { - var s3 = ''; - var b = ''; - var t = ''; - var i = 0; - var c = 0; - for(; n > 0; --n, ++i) { - b = s1.charCodeAt(i) ^ s2.charCodeAt(i); - if(c >= 10) { - s3 += t; - t = ''; - c = 0; - } - t += String.fromCharCode(b); - ++c; - } - s3 += t; - return s3; -}; - -/** - * Converts a hex string into a 'binary' encoded string of bytes. - * - * @param hex the hexadecimal string to convert. - * - * @return the binary-encoded string of bytes. - */ -util$1.hexToBytes = function(hex) { - // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." - var rval = ''; - var i = 0; - if(hex.length & 1 == 1) { - // odd number of characters, convert first character alone - i = 1; - rval += String.fromCharCode(parseInt(hex[0], 16)); - } - // convert 2 characters (1 byte) at a time - for(; i < hex.length; i += 2) { - rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - } - return rval; -}; - -/** - * Converts a 'binary' encoded string of bytes to hex. - * - * @param bytes the byte string to convert. - * - * @return the string of hexadecimal characters. - */ -util$1.bytesToHex = function(bytes) { - // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." - return util$1.createBuffer(bytes).toHex(); -}; - -/** - * Converts an 32-bit integer to 4-big-endian byte string. - * - * @param i the integer. - * - * @return the byte string. - */ -util$1.int32ToBytes = function(i) { - return ( - String.fromCharCode(i >> 24 & 0xFF) + - String.fromCharCode(i >> 16 & 0xFF) + - String.fromCharCode(i >> 8 & 0xFF) + - String.fromCharCode(i & 0xFF)); -}; - -// base64 characters, reverse mapping -var _base64 = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -var _base64Idx = [ -/*43 -43 = 0*/ -/*'+', 1, 2, 3,'/' */ - 62, -1, -1, -1, 63, - -/*'0','1','2','3','4','5','6','7','8','9' */ - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, - -/*15, 16, 17,'=', 19, 20, 21 */ - -1, -1, -1, 64, -1, -1, -1, - -/*65 - 43 = 22*/ -/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, - -/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ - 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, - -/*91 - 43 = 48 */ -/*48, 49, 50, 51, 52, 53 */ - -1, -1, -1, -1, -1, -1, - -/*97 - 43 = 54*/ -/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ - 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, - -/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 -]; - -// base58 characters (Bitcoin alphabet) -var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - -/** - * Base64 encodes a 'binary' encoded string of bytes. - * - * @param input the binary encoded string of bytes to base64-encode. - * @param maxline the maximum number of encoded characters per line to use, - * defaults to none. - * - * @return the base64-encoded output. - */ -util$1.encode64 = function(input, maxline) { - // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." - var line = ''; - var output = ''; - var chr1, chr2, chr3; - var i = 0; - while(i < input.length) { - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - - // encode 4 character group - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); - if(isNaN(chr2)) { - line += '=='; - } else { - line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); - line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); - } - - if(maxline && line.length > maxline) { - output += line.substr(0, maxline) + '\r\n'; - line = line.substr(maxline); - } - } - output += line; - return output; -}; - -/** - * Base64 decodes a string into a 'binary' encoded string of bytes. - * - * @param input the base64-encoded input. - * - * @return the binary encoded string. - */ -util$1.decode64 = function(input) { - // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." - - // remove all non-base64 characters - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); - - var output = ''; - var enc1, enc2, enc3, enc4; - var i = 0; - - while(i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - - output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); - if(enc3 !== 64) { - // decoded at least 2 bytes - output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); - if(enc4 !== 64) { - // decoded 3 bytes - output += String.fromCharCode(((enc3 & 3) << 6) | enc4); - } - } - } - - return output; -}; - -/** - * Encodes the given string of characters (a standard JavaScript - * string) as a binary encoded string where the bytes represent - * a UTF-8 encoded string of characters. Non-ASCII characters will be - * encoded as multiple bytes according to UTF-8. - * - * @param str a standard string of characters to encode. - * - * @return the binary encoded string. - */ -util$1.encodeUtf8 = function(str) { - return unescape(encodeURIComponent(str)); -}; - -/** - * Decodes a binary encoded string that contains bytes that - * represent a UTF-8 encoded string of characters -- into a - * string of characters (a standard JavaScript string). - * - * @param str the binary encoded string to decode. - * - * @return the resulting standard string of characters. - */ -util$1.decodeUtf8 = function(str) { - return decodeURIComponent(escape(str)); -}; - -// binary encoding/decoding tools -// FIXME: Experimental. Do not use yet. -util$1.binary = { - raw: {}, - hex: {}, - base64: {}, - base58: {}, - baseN : { - encode: baseN.encode, - decode: baseN.decode - } -}; - -/** - * Encodes a Uint8Array as a binary-encoded string. This encoding uses - * a value between 0 and 255 for each character. - * - * @param bytes the Uint8Array to encode. - * - * @return the binary-encoded string. - */ -util$1.binary.raw.encode = function(bytes) { - return String.fromCharCode.apply(null, bytes); -}; - -/** - * Decodes a binary-encoded string to a Uint8Array. This encoding uses - * a value between 0 and 255 for each character. - * - * @param str the binary-encoded string to decode. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util$1.binary.raw.decode = function(str, output, offset) { - var out = output; - if(!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for(var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? (j - offset) : out; -}; - -/** - * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or - * ByteBuffer as a string of hexadecimal characters. - * - * @param bytes the bytes to convert. - * - * @return the string of hexadecimal characters. - */ -util$1.binary.hex.encode = util$1.bytesToHex; - -/** - * Decodes a hex-encoded string to a Uint8Array. - * - * @param hex the hexadecimal string to convert. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util$1.binary.hex.decode = function(hex, output, offset) { - var out = output; - if(!out) { - out = new Uint8Array(Math.ceil(hex.length / 2)); - } - offset = offset || 0; - var i = 0, j = offset; - if(hex.length & 1) { - // odd number of characters, convert first character alone - i = 1; - out[j++] = parseInt(hex[0], 16); - } - // convert 2 characters (1 byte) at a time - for(; i < hex.length; i += 2) { - out[j++] = parseInt(hex.substr(i, 2), 16); - } - return output ? (j - offset) : out; -}; - -/** - * Base64-encodes a Uint8Array. - * - * @param input the Uint8Array to encode. - * @param maxline the maximum number of encoded characters per line to use, - * defaults to none. - * - * @return the base64-encoded output string. - */ -util$1.binary.base64.encode = function(input, maxline) { - var line = ''; - var output = ''; - var chr1, chr2, chr3; - var i = 0; - while(i < input.byteLength) { - chr1 = input[i++]; - chr2 = input[i++]; - chr3 = input[i++]; - - // encode 4 character group - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); - if(isNaN(chr2)) { - line += '=='; - } else { - line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); - line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); - } - - if(maxline && line.length > maxline) { - output += line.substr(0, maxline) + '\r\n'; - line = line.substr(maxline); - } - } - output += line; - return output; -}; - -/** - * Decodes a base64-encoded string to a Uint8Array. - * - * @param input the base64-encoded input string. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util$1.binary.base64.decode = function(input, output, offset) { - var out = output; - if(!out) { - out = new Uint8Array(Math.ceil(input.length / 4) * 3); - } - - // remove all non-base64 characters - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); - - offset = offset || 0; - var enc1, enc2, enc3, enc4; - var i = 0, j = offset; - - while(i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - - out[j++] = (enc1 << 2) | (enc2 >> 4); - if(enc3 !== 64) { - // decoded at least 2 bytes - out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); - if(enc4 !== 64) { - // decoded 3 bytes - out[j++] = ((enc3 & 3) << 6) | enc4; - } - } - } - - // make sure result is the exact decoded length - return output ? (j - offset) : out.subarray(0, j); -}; - -// add support for base58 encoding/decoding with Bitcoin alphabet -util$1.binary.base58.encode = function(input, maxline) { - return util$1.binary.baseN.encode(input, _base58, maxline); -}; -util$1.binary.base58.decode = function(input, maxline) { - return util$1.binary.baseN.decode(input, _base58, maxline); -}; - -// text encoding/decoding tools -// FIXME: Experimental. Do not use yet. -util$1.text = { - utf8: {}, - utf16: {} -}; - -/** - * Encodes the given string as UTF-8 in a Uint8Array. - * - * @param str the string to encode. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util$1.text.utf8.encode = function(str, output, offset) { - str = util$1.encodeUtf8(str); - var out = output; - if(!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for(var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? (j - offset) : out; -}; - -/** - * Decodes the UTF-8 contents from a Uint8Array. - * - * @param bytes the Uint8Array to decode. - * - * @return the resulting string. - */ -util$1.text.utf8.decode = function(bytes) { - return util$1.decodeUtf8(String.fromCharCode.apply(null, bytes)); -}; - -/** - * Encodes the given string as UTF-16 in a Uint8Array. - * - * @param str the string to encode. - * @param [output] an optional Uint8Array to write the output to; if it - * is too small, an exception will be thrown. - * @param [offset] the start offset for writing to the output (default: 0). - * - * @return the Uint8Array or the number of bytes written if output was given. - */ -util$1.text.utf16.encode = function(str, output, offset) { - var out = output; - if(!out) { - out = new Uint8Array(str.length * 2); - } - var view = new Uint16Array(out.buffer); - offset = offset || 0; - var j = offset; - var k = offset; - for(var i = 0; i < str.length; ++i) { - view[k++] = str.charCodeAt(i); - j += 2; - } - return output ? (j - offset) : out; -}; - -/** - * Decodes the UTF-16 contents from a Uint8Array. - * - * @param bytes the Uint8Array to decode. - * - * @return the resulting string. - */ -util$1.text.utf16.decode = function(bytes) { - return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); -}; - -/** - * Deflates the given data using a flash interface. - * - * @param api the flash interface. - * @param bytes the data. - * @param raw true to return only raw deflate data, false to include zlib - * header and trailer. - * - * @return the deflated data as a string. - */ -util$1.deflate = function(api, bytes, raw) { - bytes = util$1.decode64(api.deflate(util$1.encode64(bytes)).rval); - - // strip zlib header and trailer if necessary - if(raw) { - // zlib header is 2 bytes (CMF,FLG) where FLG indicates that - // there is a 4-byte DICT (alder-32) block before the data if - // its 5th bit is set - var start = 2; - var flg = bytes.charCodeAt(1); - if(flg & 0x20) { - start = 6; - } - // zlib trailer is 4 bytes of adler-32 - bytes = bytes.substring(start, bytes.length - 4); - } - - return bytes; -}; - -/** - * Inflates the given data using a flash interface. - * - * @param api the flash interface. - * @param bytes the data. - * @param raw true if the incoming data has no zlib header or trailer and is - * raw DEFLATE data. - * - * @return the inflated data as a string, null on error. - */ -util$1.inflate = function(api, bytes, raw) { - // TODO: add zlib header and trailer if necessary/possible - var rval = api.inflate(util$1.encode64(bytes)).rval; - return (rval === null) ? null : util$1.decode64(rval); -}; - -/** - * Sets a storage object. - * - * @param api the storage interface. - * @param id the storage ID to use. - * @param obj the storage object, null to remove. - */ -var _setStorageObject = function(api, id, obj) { - if(!api) { - throw new Error('WebStorage not available.'); - } - - var rval; - if(obj === null) { - rval = api.removeItem(id); - } else { - // json-encode and base64-encode object - obj = util$1.encode64(JSON.stringify(obj)); - rval = api.setItem(id, obj); - } - - // handle potential flash error - if(typeof(rval) !== 'undefined' && rval.rval !== true) { - var error = new Error(rval.error.message); - error.id = rval.error.id; - error.name = rval.error.name; - throw error; - } -}; - -/** - * Gets a storage object. - * - * @param api the storage interface. - * @param id the storage ID to use. - * - * @return the storage object entry or null if none exists. - */ -var _getStorageObject = function(api, id) { - if(!api) { - throw new Error('WebStorage not available.'); - } - - // get the existing entry - var rval = api.getItem(id); - - /* Note: We check api.init because we can't do (api == localStorage) - on IE because of "Class doesn't support Automation" exception. Only - the flash api has an init method so this works too, but we need a - better solution in the future. */ - - // flash returns item wrapped in an object, handle special case - if(api.init) { - if(rval.rval === null) { - if(rval.error) { - var error = new Error(rval.error.message); - error.id = rval.error.id; - error.name = rval.error.name; - throw error; - } - // no error, but also no item - rval = null; - } else { - rval = rval.rval; - } - } - - // handle decoding - if(rval !== null) { - // base64-decode and json-decode data - rval = JSON.parse(util$1.decode64(rval)); - } - - return rval; -}; - -/** - * Stores an item in local storage. - * - * @param api the storage interface. - * @param id the storage ID to use. - * @param key the key for the item. - * @param data the data for the item (any javascript object/primitive). - */ -var _setItem = function(api, id, key, data) { - // get storage object - var obj = _getStorageObject(api, id); - if(obj === null) { - // create a new storage object - obj = {}; - } - // update key - obj[key] = data; - - // set storage object - _setStorageObject(api, id, obj); -}; - -/** - * Gets an item from local storage. - * - * @param api the storage interface. - * @param id the storage ID to use. - * @param key the key for the item. - * - * @return the item. - */ -var _getItem = function(api, id, key) { - // get storage object - var rval = _getStorageObject(api, id); - if(rval !== null) { - // return data at key - rval = (key in rval) ? rval[key] : null; - } - - return rval; -}; - -/** - * Removes an item from local storage. - * - * @param api the storage interface. - * @param id the storage ID to use. - * @param key the key for the item. - */ -var _removeItem = function(api, id, key) { - // get storage object - var obj = _getStorageObject(api, id); - if(obj !== null && key in obj) { - // remove key - delete obj[key]; - - // see if entry has no keys remaining - var empty = true; - for(var prop in obj) { - empty = false; - break; - } - if(empty) { - // remove entry entirely if no keys are left - obj = null; - } - - // set storage object - _setStorageObject(api, id, obj); - } -}; - -/** - * Clears the local disk storage identified by the given ID. - * - * @param api the storage interface. - * @param id the storage ID to use. - */ -var _clearItems = function(api, id) { - _setStorageObject(api, id, null); -}; - -/** - * Calls a storage function. - * - * @param func the function to call. - * @param args the arguments for the function. - * @param location the location argument. - * - * @return the return value from the function. - */ -var _callStorageFunction = function(func, args, location) { - var rval = null; - - // default storage types - if(typeof(location) === 'undefined') { - location = ['web', 'flash']; - } - - // apply storage types in order of preference - var type; - var done = false; - var exception = null; - for(var idx in location) { - type = location[idx]; - try { - if(type === 'flash' || type === 'both') { - if(args[0] === null) { - throw new Error('Flash local storage not available.'); - } - rval = func.apply(this, args); - done = (type === 'flash'); - } - if(type === 'web' || type === 'both') { - args[0] = localStorage; - rval = func.apply(this, args); - done = true; - } - } catch(ex) { - exception = ex; - } - if(done) { - break; - } - } - - if(!done) { - throw exception; - } - - return rval; -}; - -/** - * Stores an item on local disk. - * - * The available types of local storage include 'flash', 'web', and 'both'. - * - * The type 'flash' refers to flash local storage (SharedObject). In order - * to use flash local storage, the 'api' parameter must be valid. The type - * 'web' refers to WebStorage, if supported by the browser. The type 'both' - * refers to storing using both 'flash' and 'web', not just one or the - * other. - * - * The location array should list the storage types to use in order of - * preference: - * - * ['flash']: flash only storage - * ['web']: web only storage - * ['both']: try to store in both - * ['flash','web']: store in flash first, but if not available, 'web' - * ['web','flash']: store in web first, but if not available, 'flash' - * - * The location array defaults to: ['web', 'flash'] - * - * @param api the flash interface, null to use only WebStorage. - * @param id the storage ID to use. - * @param key the key for the item. - * @param data the data for the item (any javascript object/primitive). - * @param location an array with the preferred types of storage to use. - */ -util$1.setItem = function(api, id, key, data, location) { - _callStorageFunction(_setItem, arguments, location); -}; - -/** - * Gets an item on local disk. - * - * Set setItem() for details on storage types. - * - * @param api the flash interface, null to use only WebStorage. - * @param id the storage ID to use. - * @param key the key for the item. - * @param location an array with the preferred types of storage to use. - * - * @return the item. - */ -util$1.getItem = function(api, id, key, location) { - return _callStorageFunction(_getItem, arguments, location); -}; - -/** - * Removes an item on local disk. - * - * Set setItem() for details on storage types. - * - * @param api the flash interface. - * @param id the storage ID to use. - * @param key the key for the item. - * @param location an array with the preferred types of storage to use. - */ -util$1.removeItem = function(api, id, key, location) { - _callStorageFunction(_removeItem, arguments, location); -}; - -/** - * Clears the local disk storage identified by the given ID. - * - * Set setItem() for details on storage types. - * - * @param api the flash interface if flash is available. - * @param id the storage ID to use. - * @param location an array with the preferred types of storage to use. - */ -util$1.clearItems = function(api, id, location) { - _callStorageFunction(_clearItems, arguments, location); -}; - -/** - * Parses the scheme, host, and port from an http(s) url. - * - * @param str the url string. - * - * @return the parsed url object or null if the url is invalid. - */ -util$1.parseUrl = function(str) { - // FIXME: this regex looks a bit broken - var regex = /^(https?):\/\/([^:&^\/]*):?(\d*)(.*)$/g; - regex.lastIndex = 0; - var m = regex.exec(str); - var url = (m === null) ? null : { - full: str, - scheme: m[1], - host: m[2], - port: m[3], - path: m[4] - }; - if(url) { - url.fullHost = url.host; - if(url.port) { - if(url.port !== 80 && url.scheme === 'http') { - url.fullHost += ':' + url.port; - } else if(url.port !== 443 && url.scheme === 'https') { - url.fullHost += ':' + url.port; - } - } else if(url.scheme === 'http') { - url.port = 80; - } else if(url.scheme === 'https') { - url.port = 443; - } - url.full = url.scheme + '://' + url.fullHost; - } - return url; -}; - -/* Storage for query variables */ -var _queryVariables = null; - -/** - * Returns the window location query variables. Query is parsed on the first - * call and the same object is returned on subsequent calls. The mapping - * is from keys to an array of values. Parameters without values will have - * an object key set but no value added to the value array. Values are - * unescaped. - * - * ...?k1=v1&k2=v2: - * { - * "k1": ["v1"], - * "k2": ["v2"] - * } - * - * ...?k1=v1&k1=v2: - * { - * "k1": ["v1", "v2"] - * } - * - * ...?k1=v1&k2: - * { - * "k1": ["v1"], - * "k2": [] - * } - * - * ...?k1=v1&k1: - * { - * "k1": ["v1"] - * } - * - * ...?k1&k1: - * { - * "k1": [] - * } - * - * @param query the query string to parse (optional, default to cached - * results from parsing window location search query). - * - * @return object mapping keys to variables. - */ -util$1.getQueryVariables = function(query) { - var parse = function(q) { - var rval = {}; - var kvpairs = q.split('&'); - for(var i = 0; i < kvpairs.length; i++) { - var pos = kvpairs[i].indexOf('='); - var key; - var val; - if(pos > 0) { - key = kvpairs[i].substring(0, pos); - val = kvpairs[i].substring(pos + 1); - } else { - key = kvpairs[i]; - val = null; - } - if(!(key in rval)) { - rval[key] = []; - } - // disallow overriding object prototype keys - if(!(key in Object.prototype) && val !== null) { - rval[key].push(unescape(val)); - } - } - return rval; - }; - - var rval; - if(typeof(query) === 'undefined') { - // set cached variables if needed - if(_queryVariables === null) { - if(typeof(window) !== 'undefined' && window.location && window.location.search) { - // parse window search query - _queryVariables = parse(window.location.search.substring(1)); - } else { - // no query variables available - _queryVariables = {}; - } - } - rval = _queryVariables; - } else { - // parse given query - rval = parse(query); - } - return rval; -}; - -/** - * Parses a fragment into a path and query. This method will take a URI - * fragment and break it up as if it were the main URI. For example: - * /bar/baz?a=1&b=2 - * results in: - * { - * path: ["bar", "baz"], - * query: {"k1": ["v1"], "k2": ["v2"]} - * } - * - * @return object with a path array and query object. - */ -util$1.parseFragment = function(fragment) { - // default to whole fragment - var fp = fragment; - var fq = ''; - // split into path and query if possible at the first '?' - var pos = fragment.indexOf('?'); - if(pos > 0) { - fp = fragment.substring(0, pos); - fq = fragment.substring(pos + 1); - } - // split path based on '/' and ignore first element if empty - var path = fp.split('/'); - if(path.length > 0 && path[0] === '') { - path.shift(); - } - // convert query into object - var query = (fq === '') ? {} : util$1.getQueryVariables(fq); - - return { - pathString: fp, - queryString: fq, - path: path, - query: query - }; -}; - -/** - * Makes a request out of a URI-like request string. This is intended to - * be used where a fragment id (after a URI '#') is parsed as a URI with - * path and query parts. The string should have a path beginning and - * delimited by '/' and optional query parameters following a '?'. The - * query should be a standard URL set of key value pairs delimited by - * '&'. For backwards compatibility the initial '/' on the path is not - * required. The request object has the following API, (fully described - * in the method code): - * { - * path: . - * query: , - * getPath(i): get part or all of the split path array, - * getQuery(k, i): get part or all of a query key array, - * getQueryLast(k, _default): get last element of a query key array. - * } - * - * @return object with request parameters. - */ -util$1.makeRequest = function(reqString) { - var frag = util$1.parseFragment(reqString); - var req = { - // full path string - path: frag.pathString, - // full query string - query: frag.queryString, - /** - * Get path or element in path. - * - * @param i optional path index. - * - * @return path or part of path if i provided. - */ - getPath: function(i) { - return (typeof(i) === 'undefined') ? frag.path : frag.path[i]; - }, - /** - * Get query, values for a key, or value for a key index. - * - * @param k optional query key. - * @param i optional query key index. - * - * @return query, values for a key, or value for a key index. - */ - getQuery: function(k, i) { - var rval; - if(typeof(k) === 'undefined') { - rval = frag.query; - } else { - rval = frag.query[k]; - if(rval && typeof(i) !== 'undefined') { - rval = rval[i]; - } - } - return rval; - }, - getQueryLast: function(k, _default) { - var rval; - var vals = req.getQuery(k); - if(vals) { - rval = vals[vals.length - 1]; - } else { - rval = _default; - } - return rval; - } - }; - return req; -}; - -/** - * Makes a URI out of a path, an object with query parameters, and a - * fragment. Uses jQuery.param() internally for query string creation. - * If the path is an array, it will be joined with '/'. - * - * @param path string path or array of strings. - * @param query object with query parameters. (optional) - * @param fragment fragment string. (optional) - * - * @return string object with request parameters. - */ -util$1.makeLink = function(path, query, fragment) { - // join path parts if needed - path = jQuery.isArray(path) ? path.join('/') : path; - - var qstr = jQuery.param(query || {}); - fragment = fragment || ''; - return path + - ((qstr.length > 0) ? ('?' + qstr) : '') + - ((fragment.length > 0) ? ('#' + fragment) : ''); -}; - -/** - * Check if an object is empty. - * - * Taken from: - * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 - * - * @param object the object to check. - */ -util$1.isEmpty = function(obj) { - for(var prop in obj) { - if(obj.hasOwnProperty(prop)) { - return false; - } - } - return true; -}; - -/** - * Format with simple printf-style interpolation. - * - * %%: literal '%' - * %s,%o: convert next argument into a string. - * - * @param format the string to format. - * @param ... arguments to interpolate into the format string. - */ -util$1.format = function(format) { - var re = /%./g; - // current match - var match; - // current part - var part; - // current arg index - var argi = 0; - // collected parts to recombine later - var parts = []; - // last index found - var last = 0; - // loop while matches remain - while((match = re.exec(format))) { - part = format.substring(last, re.lastIndex - 2); - // don't add empty strings (ie, parts between %s%s) - if(part.length > 0) { - parts.push(part); - } - last = re.lastIndex; - // switch on % code - var code = match[0][1]; - switch(code) { - case 's': - case 'o': - // check if enough arguments were given - if(argi < arguments.length) { - parts.push(arguments[argi++ + 1]); - } else { - parts.push(''); - } - break; - // FIXME: do proper formating for numbers, etc - //case 'f': - //case 'd': - case '%': - parts.push('%'); - break; - default: - parts.push('<%' + code + '?>'); - } - } - // add trailing part of format string - parts.push(format.substring(last)); - return parts.join(''); -}; - -/** - * Formats a number. - * - * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ - */ -util$1.formatNumber = function(number, decimals, dec_point, thousands_sep) { - // http://kevin.vanzonneveld.net - // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) - // + bugfix by: Michael White (http://crestidg.com) - // + bugfix by: Benjamin Lupton - // + bugfix by: Allan Jensen (http://www.winternet.no) - // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) - // * example 1: number_format(1234.5678, 2, '.', ''); - // * returns 1: 1234.57 - - var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; - var d = dec_point === undefined ? ',' : dec_point; - var t = thousands_sep === undefined ? - '.' : thousands_sep, s = n < 0 ? '-' : ''; - var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; - var j = (i.length > 3) ? i.length % 3 : 0; - return s + (j ? i.substr(0, j) + t : '') + - i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + - (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); -}; - -/** - * Formats a byte size. - * - * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ - */ -util$1.formatSize = function(size) { - if(size >= 1073741824) { - size = util$1.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; - } else if(size >= 1048576) { - size = util$1.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; - } else if(size >= 1024) { - size = util$1.formatNumber(size / 1024, 0) + ' KiB'; - } else { - size = util$1.formatNumber(size, 0) + ' bytes'; - } - return size; -}; - -/** - * Converts an IPv4 or IPv6 string representation into bytes (in network order). - * - * @param ip the IPv4 or IPv6 address to convert. - * - * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't - * be parsed. - */ -util$1.bytesFromIP = function(ip) { - if(ip.indexOf('.') !== -1) { - return util$1.bytesFromIPv4(ip); - } - if(ip.indexOf(':') !== -1) { - return util$1.bytesFromIPv6(ip); - } - return null; -}; - -/** - * Converts an IPv4 string representation into bytes (in network order). - * - * @param ip the IPv4 address to convert. - * - * @return the 4-byte address or null if the address can't be parsed. - */ -util$1.bytesFromIPv4 = function(ip) { - ip = ip.split('.'); - if(ip.length !== 4) { - return null; - } - var b = util$1.createBuffer(); - for(var i = 0; i < ip.length; ++i) { - var num = parseInt(ip[i], 10); - if(isNaN(num)) { - return null; - } - b.putByte(num); - } - return b.getBytes(); -}; - -/** - * Converts an IPv6 string representation into bytes (in network order). - * - * @param ip the IPv6 address to convert. - * - * @return the 16-byte address or null if the address can't be parsed. - */ -util$1.bytesFromIPv6 = function(ip) { - var blanks = 0; - ip = ip.split(':').filter(function(e) { - if(e.length === 0) ++blanks; - return true; - }); - var zeros = (8 - ip.length + blanks) * 2; - var b = util$1.createBuffer(); - for(var i = 0; i < 8; ++i) { - if(!ip[i] || ip[i].length === 0) { - b.fillWithByte(0, zeros); - zeros = 0; - continue; - } - var bytes = util$1.hexToBytes(ip[i]); - if(bytes.length < 2) { - b.putByte(0); - } - b.putBytes(bytes); - } - return b.getBytes(); -}; - -/** - * Converts 4-bytes into an IPv4 string representation or 16-bytes into - * an IPv6 string representation. The bytes must be in network order. - * - * @param bytes the bytes to convert. - * - * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, - * respectively, are given, otherwise null. - */ -util$1.bytesToIP = function(bytes) { - if(bytes.length === 4) { - return util$1.bytesToIPv4(bytes); - } - if(bytes.length === 16) { - return util$1.bytesToIPv6(bytes); - } - return null; -}; - -/** - * Converts 4-bytes into an IPv4 string representation. The bytes must be - * in network order. - * - * @param bytes the bytes to convert. - * - * @return the IPv4 string representation or null for an invalid # of bytes. - */ -util$1.bytesToIPv4 = function(bytes) { - if(bytes.length !== 4) { - return null; - } - var ip = []; - for(var i = 0; i < bytes.length; ++i) { - ip.push(bytes.charCodeAt(i)); - } - return ip.join('.'); -}; - -/** - * Converts 16-bytes into an IPv16 string representation. The bytes must be - * in network order. - * - * @param bytes the bytes to convert. - * - * @return the IPv16 string representation or null for an invalid # of bytes. - */ -util$1.bytesToIPv6 = function(bytes) { - if(bytes.length !== 16) { - return null; - } - var ip = []; - var zeroGroups = []; - var zeroMaxGroup = 0; - for(var i = 0; i < bytes.length; i += 2) { - var hex = util$1.bytesToHex(bytes[i] + bytes[i + 1]); - // canonicalize zero representation - while(hex[0] === '0' && hex !== '0') { - hex = hex.substr(1); - } - if(hex === '0') { - var last = zeroGroups[zeroGroups.length - 1]; - var idx = ip.length; - if(!last || idx !== last.end + 1) { - zeroGroups.push({start: idx, end: idx}); - } else { - last.end = idx; - if((last.end - last.start) > - (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { - zeroMaxGroup = zeroGroups.length - 1; - } - } - } - ip.push(hex); - } - if(zeroGroups.length > 0) { - var group = zeroGroups[zeroMaxGroup]; - // only shorten group of length > 0 - if(group.end - group.start > 0) { - ip.splice(group.start, group.end - group.start + 1, ''); - if(group.start === 0) { - ip.unshift(''); - } - if(group.end === 7) { - ip.push(''); - } - } - } - return ip.join(':'); -}; - -/** - * Estimates the number of processes that can be run concurrently. If - * creating Web Workers, keep in mind that the main JavaScript process needs - * its own core. - * - * @param options the options to use: - * update true to force an update (not use the cached value). - * @param callback(err, max) called once the operation completes. - */ -util$1.estimateCores = function(options, callback) { - if(typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - if('cores' in util$1 && !options.update) { - return callback(null, util$1.cores); - } - if(typeof navigator !== 'undefined' && - 'hardwareConcurrency' in navigator && - navigator.hardwareConcurrency > 0) { - util$1.cores = navigator.hardwareConcurrency; - return callback(null, util$1.cores); - } - if(typeof Worker === 'undefined') { - // workers not available - util$1.cores = 1; - return callback(null, util$1.cores); - } - if(typeof Blob === 'undefined') { - // can't estimate, default to 2 - util$1.cores = 2; - return callback(null, util$1.cores); - } - - // create worker concurrency estimation code as blob - var blobUrl = URL.createObjectURL(new Blob(['(', - function() { - self.addEventListener('message', function(e) { - // run worker for 4 ms - var st = Date.now(); - var et = st + 4; - self.postMessage({st: st, et: et}); - }); - }.toString(), - ')()'], {type: 'application/javascript'})); - - // take 5 samples using 16 workers - sample([], 5, 16); - - function sample(max, samples, numWorkers) { - if(samples === 0) { - // get overlap average - var avg = Math.floor(max.reduce(function(avg, x) { - return avg + x; - }, 0) / max.length); - util$1.cores = Math.max(1, avg); - URL.revokeObjectURL(blobUrl); - return callback(null, util$1.cores); - } - map(numWorkers, function(err, results) { - max.push(reduce(numWorkers, results)); - sample(max, samples - 1, numWorkers); - }); - } - - function map(numWorkers, callback) { - var workers = []; - var results = []; - for(var i = 0; i < numWorkers; ++i) { - var worker = new Worker(blobUrl); - worker.addEventListener('message', function(e) { - results.push(e.data); - if(results.length === numWorkers) { - for(var i = 0; i < numWorkers; ++i) { - workers[i].terminate(); - } - callback(null, results); - } - }); - workers.push(worker); - } - for(var i = 0; i < numWorkers; ++i) { - workers[i].postMessage(i); - } - } - - function reduce(numWorkers, results) { - // find overlapping time windows - var overlaps = []; - for(var n = 0; n < numWorkers; ++n) { - var r1 = results[n]; - var overlap = overlaps[n] = []; - for(var i = 0; i < numWorkers; ++i) { - if(n === i) { - continue; - } - var r2 = results[i]; - if((r1.st > r2.st && r1.st < r2.et) || - (r2.st > r1.st && r2.st < r1.et)) { - overlap.push(i); - } - } - } - // get maximum overlaps ... don't include overlapping worker itself - // as the main JS process was also being scheduled during the work and - // would have to be subtracted from the estimate anyway - return overlaps.reduce(function(max, overlap) { - return Math.max(max, overlap.length); - }, 0); - } -}; - -/** - * Cipher base API. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ - -var forge$D = forge$F; - - -forge$D.cipher = forge$D.cipher || {}; - -// registered algorithms -forge$D.cipher.algorithms = forge$D.cipher.algorithms || {}; - -/** - * Creates a cipher object that can be used to encrypt data using the given - * algorithm and key. The algorithm may be provided as a string value for a - * previously registered algorithm or it may be given as a cipher algorithm - * API object. - * - * @param algorithm the algorithm to use, either a string or an algorithm API - * object. - * @param key the key to use, as a binary-encoded string of bytes or a - * byte buffer. - * - * @return the cipher. - */ -forge$D.cipher.createCipher = function(algorithm, key) { - var api = algorithm; - if(typeof api === 'string') { - api = forge$D.cipher.getAlgorithm(api); - if(api) { - api = api(); - } - } - if(!api) { - throw new Error('Unsupported algorithm: ' + algorithm); - } - - // assume block cipher - return new forge$D.cipher.BlockCipher({ - algorithm: api, - key: key, - decrypt: false - }); -}; - -/** - * Creates a decipher object that can be used to decrypt data using the given - * algorithm and key. The algorithm may be provided as a string value for a - * previously registered algorithm or it may be given as a cipher algorithm - * API object. - * - * @param algorithm the algorithm to use, either a string or an algorithm API - * object. - * @param key the key to use, as a binary-encoded string of bytes or a - * byte buffer. - * - * @return the cipher. - */ -forge$D.cipher.createDecipher = function(algorithm, key) { - var api = algorithm; - if(typeof api === 'string') { - api = forge$D.cipher.getAlgorithm(api); - if(api) { - api = api(); - } - } - if(!api) { - throw new Error('Unsupported algorithm: ' + algorithm); - } - - // assume block cipher - return new forge$D.cipher.BlockCipher({ - algorithm: api, - key: key, - decrypt: true - }); -}; - -/** - * Registers an algorithm by name. If the name was already registered, the - * algorithm API object will be overwritten. - * - * @param name the name of the algorithm. - * @param algorithm the algorithm API object. - */ -forge$D.cipher.registerAlgorithm = function(name, algorithm) { - name = name.toUpperCase(); - forge$D.cipher.algorithms[name] = algorithm; -}; - -/** - * Gets a registered algorithm by name. - * - * @param name the name of the algorithm. - * - * @return the algorithm, if found, null if not. - */ -forge$D.cipher.getAlgorithm = function(name) { - name = name.toUpperCase(); - if(name in forge$D.cipher.algorithms) { - return forge$D.cipher.algorithms[name]; - } - return null; -}; - -var BlockCipher = forge$D.cipher.BlockCipher = function(options) { - this.algorithm = options.algorithm; - this.mode = this.algorithm.mode; - this.blockSize = this.mode.blockSize; - this._finish = false; - this._input = null; - this.output = null; - this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; - this._decrypt = options.decrypt; - this.algorithm.initialize(options); -}; - -/** - * Starts or restarts the encryption or decryption process, whichever - * was previously configured. - * - * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array - * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in - * bytes, then it must be Nb (16) bytes in length. If the IV is given in as - * 32-bit integers, then it must be 4 integers long. - * - * Note: an IV is not required or used in ECB mode. - * - * For GCM-mode, the IV must be given as a binary-encoded string of bytes or - * a byte buffer. The number of bytes should be 12 (96 bits) as recommended - * by NIST SP-800-38D but another length may be given. - * - * @param options the options to use: - * iv the initialization vector to use as a binary-encoded string of - * bytes, null to reuse the last ciphered block from a previous - * update() (this "residue" method is for legacy support only). - * additionalData additional authentication data as a binary-encoded - * string of bytes, for 'GCM' mode, (default: none). - * tagLength desired length of authentication tag, in bits, for - * 'GCM' mode (0-128, default: 128). - * tag the authentication tag to check if decrypting, as a - * binary-encoded string of bytes. - * output the output the buffer to write to, null to create one. - */ -BlockCipher.prototype.start = function(options) { - options = options || {}; - var opts = {}; - for(var key in options) { - opts[key] = options[key]; - } - opts.decrypt = this._decrypt; - this._finish = false; - this._input = forge$D.util.createBuffer(); - this.output = options.output || forge$D.util.createBuffer(); - this.mode.start(opts); -}; - -/** - * Updates the next block according to the cipher mode. - * - * @param input the buffer to read from. - */ -BlockCipher.prototype.update = function(input) { - if(input) { - // input given, so empty it into the input buffer - this._input.putBuffer(input); - } - - // do cipher operation until it needs more input and not finished - while(!this._op.call(this.mode, this._input, this.output, this._finish) && - !this._finish) {} - - // free consumed memory from input buffer - this._input.compact(); -}; - -/** - * Finishes encrypting or decrypting. - * - * @param pad a padding function to use in CBC mode, null for default, - * signature(blockSize, buffer, decrypt). - * - * @return true if successful, false on error. - */ -BlockCipher.prototype.finish = function(pad) { - // backwards-compatibility w/deprecated padding API - // Note: will overwrite padding functions even after another start() call - if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) { - this.mode.pad = function(input) { - return pad(this.blockSize, input, false); - }; - this.mode.unpad = function(output) { - return pad(this.blockSize, output, true); - }; - } - - // build options for padding and afterFinish functions - var options = {}; - options.decrypt = this._decrypt; - - // get # of bytes that won't fill a block - options.overflow = this._input.length() % this.blockSize; - - if(!this._decrypt && this.mode.pad) { - if(!this.mode.pad(this._input, options)) { - return false; - } - } - - // do final update - this._finish = true; - this.update(); - - if(this._decrypt && this.mode.unpad) { - if(!this.mode.unpad(this.output, options)) { - return false; - } - } - - if(this.mode.afterFinish) { - if(!this.mode.afterFinish(this.output, options)) { - return false; - } - } - - return true; -}; - -/** - * Supported cipher modes. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ - -var forge$C = forge$F; - - -forge$C.cipher = forge$C.cipher || {}; - -// supported cipher modes -var modes = forge$C.cipher.modes = forge$C.cipher.modes || {}; - -/** Electronic codebook (ECB) (Don't use this; it's not secure) **/ - -modes.ecb = function(options) { - options = options || {}; - this.name = 'ECB'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); -}; - -modes.ecb.prototype.start = function(options) {}; - -modes.ecb.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - if(input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - - // get next block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - - // encrypt block - this.cipher.encrypt(this._inBlock, this._outBlock); - - // write output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } -}; - -modes.ecb.prototype.decrypt = function(input, output, finish) { - // not enough input to decrypt - if(input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - - // get next block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - - // decrypt block - this.cipher.decrypt(this._inBlock, this._outBlock); - - // write output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } -}; - -modes.ecb.prototype.pad = function(input, options) { - // add PKCS#7 padding to block (each pad byte is the - // value of the number of pad bytes) - var padding = (input.length() === this.blockSize ? - this.blockSize : (this.blockSize - input.length())); - input.fillWithByte(padding, padding); - return true; -}; - -modes.ecb.prototype.unpad = function(output, options) { - // check for error: input data not a multiple of blockSize - if(options.overflow > 0) { - return false; - } - - // ensure padding byte count is valid - var len = output.length(); - var count = output.at(len - 1); - if(count > (this.blockSize << 2)) { - return false; - } - - // trim off padding bytes - output.truncate(count); - return true; -}; - -/** Cipher-block Chaining (CBC) **/ - -modes.cbc = function(options) { - options = options || {}; - this.name = 'CBC'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); -}; - -modes.cbc.prototype.start = function(options) { - // Note: legacy support for using IV residue (has security flaws) - // if IV is null, reuse block from previous processing - if(options.iv === null) { - // must have a previous block - if(!this._prev) { - throw new Error('Invalid IV parameter.'); - } - this._iv = this._prev.slice(0); - } else if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } else { - // save IV as "previous" block - this._iv = transformIV(options.iv, this.blockSize); - this._prev = this._iv.slice(0); - } -}; - -modes.cbc.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - if(input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - - // get next block - // CBC XOR's IV (or previous block) with plaintext - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._prev[i] ^ input.getInt32(); - } - - // encrypt block - this.cipher.encrypt(this._inBlock, this._outBlock); - - // write output, save previous block - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - this._prev = this._outBlock; -}; - -modes.cbc.prototype.decrypt = function(input, output, finish) { - // not enough input to decrypt - if(input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - - // get next block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - - // decrypt block - this.cipher.decrypt(this._inBlock, this._outBlock); - - // write output, save previous ciphered block - // CBC XOR's IV (or previous block) with ciphertext - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._prev[i] ^ this._outBlock[i]); - } - this._prev = this._inBlock.slice(0); -}; - -modes.cbc.prototype.pad = function(input, options) { - // add PKCS#7 padding to block (each pad byte is the - // value of the number of pad bytes) - var padding = (input.length() === this.blockSize ? - this.blockSize : (this.blockSize - input.length())); - input.fillWithByte(padding, padding); - return true; -}; - -modes.cbc.prototype.unpad = function(output, options) { - // check for error: input data not a multiple of blockSize - if(options.overflow > 0) { - return false; - } - - // ensure padding byte count is valid - var len = output.length(); - var count = output.at(len - 1); - if(count > (this.blockSize << 2)) { - return false; - } - - // trim off padding bytes - output.truncate(count); - return true; -}; - -/** Cipher feedback (CFB) **/ - -modes.cfb = function(options) { - options = options || {}; - this.name = 'CFB'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialBlock = new Array(this._ints); - this._partialOutput = forge$C.util.createBuffer(); - this._partialBytes = 0; -}; - -modes.cfb.prototype.start = function(options) { - if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } - // use IV as first input - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; -}; - -modes.cfb.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - var inputLength = input.length(); - if(inputLength === 0) { - return true; - } - - // encrypt block - this.cipher.encrypt(this._inBlock, this._outBlock); - - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output, write input as output - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; - output.putInt32(this._inBlock[i]); - } - return; - } - - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - - // XOR input with output, write input as partial output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; - this._partialOutput.putInt32(this._partialBlock[i]); - } - - if(partialBytes > 0) { - // block still incomplete, restore input buffer - input.read -= this.blockSize; - } else { - // block complete, update input block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } - - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - - if(partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; - } - - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; -}; - -modes.cfb.prototype.decrypt = function(input, output, finish) { - // not enough input to decrypt - var inputLength = input.length(); - if(inputLength === 0) { - return true; - } - - // encrypt block (CFB always uses encryption mode) - this.cipher.encrypt(this._inBlock, this._outBlock); - - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output, write input as output - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - output.putInt32(this._inBlock[i] ^ this._outBlock[i]); - } - return; - } - - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - - // XOR input with output, write input as partial output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32(); - this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); - } - - if(partialBytes > 0) { - // block still incomplete, restore input buffer - input.read -= this.blockSize; - } else { - // block complete, update input block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } - - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - - if(partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; - } - - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; -}; - -/** Output feedback (OFB) **/ - -modes.ofb = function(options) { - options = options || {}; - this.name = 'OFB'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge$C.util.createBuffer(); - this._partialBytes = 0; -}; - -modes.ofb.prototype.start = function(options) { - if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } - // use IV as first input - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; -}; - -modes.ofb.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - var inputLength = input.length(); - if(input.length() === 0) { - return true; - } - - // encrypt block (OFB always uses encryption mode) - this.cipher.encrypt(this._inBlock, this._outBlock); - - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output and update next input - for(var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - this._inBlock[i] = this._outBlock[i]; - } - return; - } - - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - - // XOR input with output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - - if(partialBytes > 0) { - // block still incomplete, restore input buffer - input.read -= this.blockSize; - } else { - // block complete, update input block - for(var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._outBlock[i]; - } - } - - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - - if(partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; - } - - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; -}; - -modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; - -/** Counter (CTR) **/ - -modes.ctr = function(options) { - options = options || {}; - this.name = 'CTR'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge$C.util.createBuffer(); - this._partialBytes = 0; -}; - -modes.ctr.prototype.start = function(options) { - if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } - // use IV as first input - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; -}; - -modes.ctr.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - var inputLength = input.length(); - if(inputLength === 0) { - return true; - } - - // encrypt block (CTR always uses encryption mode) - this.cipher.encrypt(this._inBlock, this._outBlock); - - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - } - } else { - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - - // XOR input with output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - - if(partialBytes > 0) { - // block still incomplete, restore input buffer - input.read -= this.blockSize; - } - - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - - if(partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; - } - - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; - } - - // block complete, increment counter (input block) - inc32(this._inBlock); -}; - -modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; - -/** Galois/Counter Mode (GCM) **/ - -modes.gcm = function(options) { - options = options || {}; - this.name = 'GCM'; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - this._partialOutput = forge$C.util.createBuffer(); - this._partialBytes = 0; - - // R is actually this value concatenated with 120 more zero bits, but - // we only XOR against R so the other zeros have no effect -- we just - // apply this value to the first integer in a block - this._R = 0xE1000000; -}; - -modes.gcm.prototype.start = function(options) { - if(!('iv' in options)) { - throw new Error('Invalid IV parameter.'); - } - // ensure IV is a byte buffer - var iv = forge$C.util.createBuffer(options.iv); - - // no ciphered data processed yet - this._cipherLength = 0; - - // default additional data is none - var additionalData; - if('additionalData' in options) { - additionalData = forge$C.util.createBuffer(options.additionalData); - } else { - additionalData = forge$C.util.createBuffer(); - } - - // default tag length is 128 bits - if('tagLength' in options) { - this._tagLength = options.tagLength; - } else { - this._tagLength = 128; - } - - // if tag is given, ensure tag matches tag length - this._tag = null; - if(options.decrypt) { - // save tag to check later - this._tag = forge$C.util.createBuffer(options.tag).getBytes(); - if(this._tag.length !== (this._tagLength / 8)) { - throw new Error('Authentication tag does not match tag length.'); - } - } - - // create tmp storage for hash calculation - this._hashBlock = new Array(this._ints); - - // no tag generated yet - this.tag = null; - - // generate hash subkey - // (apply block cipher to "zero" block) - this._hashSubkey = new Array(this._ints); - this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); - - // generate table M - // use 4-bit tables (32 component decomposition of a 16 byte value) - // 8-bit tables take more space and are known to have security - // vulnerabilities (in native implementations) - this.componentBits = 4; - this._m = this.generateHashTable(this._hashSubkey, this.componentBits); - - // Note: support IV length different from 96 bits? (only supporting - // 96 bits is recommended by NIST SP-800-38D) - // generate J_0 - var ivLength = iv.length(); - if(ivLength === 12) { - // 96-bit IV - this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; - } else { - // IV is NOT 96-bits - this._j0 = [0, 0, 0, 0]; - while(iv.length() > 0) { - this._j0 = this.ghash( - this._hashSubkey, this._j0, - [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); - } - this._j0 = this.ghash( - this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); - } - - // generate ICB (initial counter block) - this._inBlock = this._j0.slice(0); - inc32(this._inBlock); - this._partialBytes = 0; - - // consume authentication data - additionalData = forge$C.util.createBuffer(additionalData); - // save additional data length as a BE 64-bit number - this._aDataLength = from64To32(additionalData.length() * 8); - // pad additional data to 128 bit (16 byte) block size - var overflow = additionalData.length() % this.blockSize; - if(overflow) { - additionalData.fillWithByte(0, this.blockSize - overflow); - } - this._s = [0, 0, 0, 0]; - while(additionalData.length() > 0) { - this._s = this.ghash(this._hashSubkey, this._s, [ - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32() - ]); - } -}; - -modes.gcm.prototype.encrypt = function(input, output, finish) { - // not enough input to encrypt - var inputLength = input.length(); - if(inputLength === 0) { - return true; - } - - // encrypt block - this.cipher.encrypt(this._inBlock, this._outBlock); - - // handle full block - if(this._partialBytes === 0 && inputLength >= this.blockSize) { - // XOR input with output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^= input.getInt32()); - } - this._cipherLength += this.blockSize; - } else { - // handle partial block - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if(partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - - // XOR input with output - this._partialOutput.clear(); - for(var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - - if(partialBytes <= 0 || finish) { - // handle overflow prior to hashing - if(finish) { - // get block overflow - var overflow = inputLength % this.blockSize; - this._cipherLength += overflow; - // truncate for hash function - this._partialOutput.truncate(this.blockSize - overflow); - } else { - this._cipherLength += this.blockSize; - } - - // get output block for hashing - for(var i = 0; i < this._ints; ++i) { - this._outBlock[i] = this._partialOutput.getInt32(); - } - this._partialOutput.read -= this.blockSize; - } - - // skip any previous partial bytes - if(this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - - if(partialBytes > 0 && !finish) { - // block still incomplete, restore input buffer, get partial output, - // and return early - input.read -= this.blockSize; - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes)); - this._partialBytes = partialBytes; - return true; - } - - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes)); - this._partialBytes = 0; - } - - // update hash block S - this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); - - // increment counter (input block) - inc32(this._inBlock); -}; - -modes.gcm.prototype.decrypt = function(input, output, finish) { - // not enough input to decrypt - var inputLength = input.length(); - if(inputLength < this.blockSize && !(finish && inputLength > 0)) { - return true; - } - - // encrypt block (GCM always uses encryption mode) - this.cipher.encrypt(this._inBlock, this._outBlock); - - // increment counter (input block) - inc32(this._inBlock); - - // update hash block S - this._hashBlock[0] = input.getInt32(); - this._hashBlock[1] = input.getInt32(); - this._hashBlock[2] = input.getInt32(); - this._hashBlock[3] = input.getInt32(); - this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); - - // XOR hash input with output - for(var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); - } - - // increment cipher data length - if(inputLength < this.blockSize) { - this._cipherLength += inputLength % this.blockSize; - } else { - this._cipherLength += this.blockSize; - } -}; - -modes.gcm.prototype.afterFinish = function(output, options) { - var rval = true; - - // handle overflow - if(options.decrypt && options.overflow) { - output.truncate(this.blockSize - options.overflow); - } - - // handle authentication tag - this.tag = forge$C.util.createBuffer(); - - // concatenate additional data length with cipher length - var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); - - // include lengths in hash - this._s = this.ghash(this._hashSubkey, this._s, lengths); - - // do GCTR(J_0, S) - var tag = []; - this.cipher.encrypt(this._j0, tag); - for(var i = 0; i < this._ints; ++i) { - this.tag.putInt32(this._s[i] ^ tag[i]); - } - - // trim tag to length - this.tag.truncate(this.tag.length() % (this._tagLength / 8)); - - // check authentication tag - if(options.decrypt && this.tag.bytes() !== this._tag) { - rval = false; - } - - return rval; -}; - -/** - * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois - * field multiplication. The field, GF(2^128), is defined by the polynomial: - * - * x^128 + x^7 + x^2 + x + 1 - * - * Which is represented in little-endian binary form as: 11100001 (0xe1). When - * the value of a coefficient is 1, a bit is set. The value R, is the - * concatenation of this value and 120 zero bits, yielding a 128-bit value - * which matches the block size. - * - * This function will multiply two elements (vectors of bytes), X and Y, in - * the field GF(2^128). The result is initialized to zero. For each bit of - * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd) - * by the current value of Y. For each bit, the value of Y will be raised by - * a power of x (multiplied by the polynomial x). This can be achieved by - * shifting Y once to the right. If the current value of Y, prior to being - * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial. - * Otherwise, we must divide by R after shifting to find the remainder. - * - * @param x the first block to multiply by the second. - * @param y the second block to multiply by the first. - * - * @return the block result of the multiplication. - */ -modes.gcm.prototype.multiply = function(x, y) { - var z_i = [0, 0, 0, 0]; - var v_i = y.slice(0); - - // calculate Z_128 (block has 128 bits) - for(var i = 0; i < 128; ++i) { - // if x_i is 0, Z_{i+1} = Z_i (unchanged) - // else Z_{i+1} = Z_i ^ V_i - // get x_i by finding 32-bit int position, then left shift 1 by remainder - var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32)); - if(x_i) { - z_i[0] ^= v_i[0]; - z_i[1] ^= v_i[1]; - z_i[2] ^= v_i[2]; - z_i[3] ^= v_i[3]; - } - - // if LSB(V_i) is 1, V_i = V_i >> 1 - // else V_i = (V_i >> 1) ^ R - this.pow(v_i, v_i); - } - - return z_i; -}; - -modes.gcm.prototype.pow = function(x, out) { - // if LSB(x) is 1, x = x >>> 1 - // else x = (x >>> 1) ^ R - var lsb = x[3] & 1; - - // always do x >>> 1: - // starting with the rightmost integer, shift each integer to the right - // one bit, pulling in the bit from the integer to the left as its top - // most bit (do this for the last 3 integers) - for(var i = 3; i > 0; --i) { - out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); - } - // shift the first integer normally - out[0] = x[0] >>> 1; - - // if lsb was not set, then polynomial had a degree of 127 and doesn't - // need to divided; otherwise, XOR with R to find the remainder; we only - // need to XOR the first integer since R technically ends w/120 zero bits - if(lsb) { - out[0] ^= this._R; - } -}; - -modes.gcm.prototype.tableMultiply = function(x) { - // assumes 4-bit tables are used - var z = [0, 0, 0, 0]; - for(var i = 0; i < 32; ++i) { - var idx = (i / 8) | 0; - var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF; - var ah = this._m[i][x_i]; - z[0] ^= ah[0]; - z[1] ^= ah[1]; - z[2] ^= ah[2]; - z[3] ^= ah[3]; - } - return z; -}; - -/** - * A continuing version of the GHASH algorithm that operates on a single - * block. The hash block, last hash value (Ym) and the new block to hash - * are given. - * - * @param h the hash block. - * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash. - * @param x the block to hash. - * - * @return the hashed value (Ym). - */ -modes.gcm.prototype.ghash = function(h, y, x) { - y[0] ^= x[0]; - y[1] ^= x[1]; - y[2] ^= x[2]; - y[3] ^= x[3]; - return this.tableMultiply(y); - //return this.multiply(y, h); -}; - -/** - * Precomputes a table for multiplying against the hash subkey. This - * mechanism provides a substantial speed increase over multiplication - * performed without a table. The table-based multiplication this table is - * for solves X * H by multiplying each component of X by H and then - * composing the results together using XOR. - * - * This function can be used to generate tables with different bit sizes - * for the components, however, this implementation assumes there are - * 32 components of X (which is a 16 byte vector), therefore each component - * takes 4-bits (so the table is constructed with bits=4). - * - * @param h the hash subkey. - * @param bits the bit size for a component. - */ -modes.gcm.prototype.generateHashTable = function(h, bits) { - // TODO: There are further optimizations that would use only the - // first table M_0 (or some variant) along with a remainder table; - // this can be explored in the future - var multiplier = 8 / bits; - var perInt = 4 * multiplier; - var size = 16 * multiplier; - var m = new Array(size); - for(var i = 0; i < size; ++i) { - var tmp = [0, 0, 0, 0]; - var idx = (i / perInt) | 0; - var shft = ((perInt - 1 - (i % perInt)) * bits); - tmp[idx] = (1 << (bits - 1)) << shft; - m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); - } - return m; -}; - -/** - * Generates a table for multiplying against the hash subkey for one - * particular component (out of all possible component values). - * - * @param mid the pre-multiplied value for the middle key of the table. - * @param bits the bit size for a component. - */ -modes.gcm.prototype.generateSubHashTable = function(mid, bits) { - // compute the table quickly by minimizing the number of - // POW operations -- they only need to be performed for powers of 2, - // all other entries can be composed from those powers using XOR - var size = 1 << bits; - var half = size >>> 1; - var m = new Array(size); - m[half] = mid.slice(0); - var i = half >>> 1; - while(i > 0) { - // raise m0[2 * i] and store in m0[i] - this.pow(m[2 * i], m[i] = []); - i >>= 1; - } - i = 2; - while(i < half) { - for(var j = 1; j < i; ++j) { - var m_i = m[i]; - var m_j = m[j]; - m[i + j] = [ - m_i[0] ^ m_j[0], - m_i[1] ^ m_j[1], - m_i[2] ^ m_j[2], - m_i[3] ^ m_j[3] - ]; - } - i *= 2; - } - m[0] = [0, 0, 0, 0]; - /* Note: We could avoid storing these by doing composition during multiply - calculate top half using composition by speed is preferred. */ - for(i = half + 1; i < size; ++i) { - var c = m[i ^ half]; - m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; - } - return m; -}; - -/** Utility functions */ - -function transformIV(iv, blockSize) { - if(typeof iv === 'string') { - // convert iv string into byte buffer - iv = forge$C.util.createBuffer(iv); - } - - if(forge$C.util.isArray(iv) && iv.length > 4) { - // convert iv byte array into byte buffer - var tmp = iv; - iv = forge$C.util.createBuffer(); - for(var i = 0; i < tmp.length; ++i) { - iv.putByte(tmp[i]); - } - } - - if(iv.length() < blockSize) { - throw new Error( - 'Invalid IV length; got ' + iv.length() + - ' bytes and expected ' + blockSize + ' bytes.'); - } - - if(!forge$C.util.isArray(iv)) { - // convert iv byte buffer into 32-bit integer array - var ints = []; - var blocks = blockSize / 4; - for(var i = 0; i < blocks; ++i) { - ints.push(iv.getInt32()); - } - iv = ints; - } - - return iv; -} - -function inc32(block) { - // increment last 32 bits of block only - block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF; -} - -function from64To32(num) { - // convert 64-bit number to two BE Int32s - return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; -} - -/** - * Advanced Encryption Standard (AES) implementation. - * - * This implementation is based on the public domain library 'jscrypto' which - * was written by: - * - * Emily Stark (estark@stanford.edu) - * Mike Hamburg (mhamburg@stanford.edu) - * Dan Boneh (dabo@cs.stanford.edu) - * - * Parts of this code are based on the OpenSSL implementation of AES: - * http://www.openssl.org - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ - -var forge$B = forge$F; - - - - -/* AES API */ -forge$B.aes = forge$B.aes || {}; - -/** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('AES-', key); - * cipher.start({iv: iv}); - * - * Creates an AES cipher object to encrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as a string of bytes, an array of bytes, - * a byte buffer, or an array of 32-bit words. - * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge$B.aes.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher$1({ - key: key, - output: output, - decrypt: false, - mode: mode - }); - cipher.start(iv); - return cipher; -}; - -/** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('AES-', key); - * - * Creates an AES cipher object to encrypt data using the given symmetric key. - * - * The key may be given as a string of bytes, an array of bytes, a - * byte buffer, or an array of 32-bit words. - * - * @param key the symmetric key to use. - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge$B.aes.createEncryptionCipher = function(key, mode) { - return _createCipher$1({ - key: key, - output: null, - decrypt: false, - mode: mode - }); -}; - -/** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('AES-', key); - * decipher.start({iv: iv}); - * - * Creates an AES cipher object to decrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as a string of bytes, an array of bytes, - * a byte buffer, or an array of 32-bit words. - * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge$B.aes.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher$1({ - key: key, - output: output, - decrypt: true, - mode: mode - }); - cipher.start(iv); - return cipher; -}; - -/** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('AES-', key); - * - * Creates an AES cipher object to decrypt data using the given symmetric key. - * - * The key may be given as a string of bytes, an array of bytes, a - * byte buffer, or an array of 32-bit words. - * - * @param key the symmetric key to use. - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge$B.aes.createDecryptionCipher = function(key, mode) { - return _createCipher$1({ - key: key, - output: null, - decrypt: true, - mode: mode - }); -}; - -/** - * Creates a new AES cipher algorithm object. - * - * @param name the name of the algorithm. - * @param mode the mode factory function. - * - * @return the AES algorithm object. - */ -forge$B.aes.Algorithm = function(name, mode) { - if(!init) { - initialize(); - } - var self = this; - self.name = name; - self.mode = new mode({ - blockSize: 16, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock$1(self._w, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock$1(self._w, inBlock, outBlock, true); - } - } - }); - self._init = false; -}; - -/** - * Initializes this AES algorithm by expanding its key. - * - * @param options the options to use. - * key the key to use with this algorithm. - * decrypt true if the algorithm should be initialized for decryption, - * false for encryption. - */ -forge$B.aes.Algorithm.prototype.initialize = function(options) { - if(this._init) { - return; - } - - var key = options.key; - var tmp; - - /* Note: The key may be a string of bytes, an array of bytes, a byte - buffer, or an array of 32-bit integers. If the key is in bytes, then - it must be 16, 24, or 32 bytes in length. If it is in 32-bit - integers, it must be 4, 6, or 8 integers long. */ - - if(typeof key === 'string' && - (key.length === 16 || key.length === 24 || key.length === 32)) { - // convert key string into byte buffer - key = forge$B.util.createBuffer(key); - } else if(forge$B.util.isArray(key) && - (key.length === 16 || key.length === 24 || key.length === 32)) { - // convert key integer array into byte buffer - tmp = key; - key = forge$B.util.createBuffer(); - for(var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - - // convert key byte buffer into 32-bit integer array - if(!forge$B.util.isArray(key)) { - tmp = key; - key = []; - - // key lengths of 16, 24, 32 bytes allowed - var len = tmp.length(); - if(len === 16 || len === 24 || len === 32) { - len = len >>> 2; - for(var i = 0; i < len; ++i) { - key.push(tmp.getInt32()); - } - } - } - - // key must be an array of 32-bit integers by now - if(!forge$B.util.isArray(key) || - !(key.length === 4 || key.length === 6 || key.length === 8)) { - throw new Error('Invalid key parameter.'); - } - - // encryption operation is always used for these modes - var mode = this.mode.name; - var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1); - - // do key expansion - this._w = _expandKey(key, options.decrypt && !encryptOp); - this._init = true; -}; - -/** - * Expands a key. Typically only used for testing. - * - * @param key the symmetric key to expand, as an array of 32-bit words. - * @param decrypt true to expand for decryption, false for encryption. - * - * @return the expanded key. - */ -forge$B.aes._expandKey = function(key, decrypt) { - if(!init) { - initialize(); - } - return _expandKey(key, decrypt); -}; - -/** - * Updates a single block. Typically only used for testing. - * - * @param w the expanded key to use. - * @param input an array of block-size 32-bit words. - * @param output an array of block-size 32-bit words. - * @param decrypt true to decrypt, false to encrypt. - */ -forge$B.aes._updateBlock = _updateBlock$1; - -/** Register AES algorithms **/ - -registerAlgorithm$1('AES-ECB', forge$B.cipher.modes.ecb); -registerAlgorithm$1('AES-CBC', forge$B.cipher.modes.cbc); -registerAlgorithm$1('AES-CFB', forge$B.cipher.modes.cfb); -registerAlgorithm$1('AES-OFB', forge$B.cipher.modes.ofb); -registerAlgorithm$1('AES-CTR', forge$B.cipher.modes.ctr); -registerAlgorithm$1('AES-GCM', forge$B.cipher.modes.gcm); - -function registerAlgorithm$1(name, mode) { - var factory = function() { - return new forge$B.aes.Algorithm(name, mode); - }; - forge$B.cipher.registerAlgorithm(name, factory); -} - -/** AES implementation **/ - -var init = false; // not yet initialized -var Nb = 4; // number of words comprising the state (AES = 4) -var sbox; // non-linear substitution table used in key expansion -var isbox; // inversion of sbox -var rcon; // round constant word array -var mix; // mix-columns table -var imix; // inverse mix-columns table - -/** - * Performs initialization, ie: precomputes tables to optimize for speed. - * - * One way to understand how AES works is to imagine that 'addition' and - * 'multiplication' are interfaces that require certain mathematical - * properties to hold true (ie: they are associative) but they might have - * different implementations and produce different kinds of results ... - * provided that their mathematical properties remain true. AES defines - * its own methods of addition and multiplication but keeps some important - * properties the same, ie: associativity and distributivity. The - * explanation below tries to shed some light on how AES defines addition - * and multiplication of bytes and 32-bit words in order to perform its - * encryption and decryption algorithms. - * - * The basics: - * - * The AES algorithm views bytes as binary representations of polynomials - * that have either 1 or 0 as the coefficients. It defines the addition - * or subtraction of two bytes as the XOR operation. It also defines the - * multiplication of two bytes as a finite field referred to as GF(2^8) - * (Note: 'GF' means "Galois Field" which is a field that contains a finite - * number of elements so GF(2^8) has 256 elements). - * - * This means that any two bytes can be represented as binary polynomials; - * when they multiplied together and modularly reduced by an irreducible - * polynomial of the 8th degree, the results are the field GF(2^8). The - * specific irreducible polynomial that AES uses in hexadecimal is 0x11b. - * This multiplication is associative with 0x01 as the identity: - * - * (b * 0x01 = GF(b, 0x01) = b). - * - * The operation GF(b, 0x02) can be performed at the byte level by left - * shifting b once and then XOR'ing it (to perform the modular reduction) - * with 0x11b if b is >= 128. Repeated application of the multiplication - * of 0x02 can be used to implement the multiplication of any two bytes. - * - * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can - * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these - * factors can each be multiplied by 0x57 and then added together. To do - * the multiplication, values for 0x57 multiplied by each of these 3 factors - * can be precomputed and stored in a table. To add them, the values from - * the table are XOR'd together. - * - * AES also defines addition and multiplication of words, that is 4-byte - * numbers represented as polynomials of 3 degrees where the coefficients - * are the values of the bytes. - * - * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0. - * - * Addition is performed by XOR'ing like powers of x. Multiplication - * is performed in two steps, the first is an algebriac expansion as - * you would do normally (where addition is XOR). But the result is - * a polynomial larger than 3 degrees and thus it cannot fit in a word. So - * next the result is modularly reduced by an AES-specific polynomial of - * degree 4 which will always produce a polynomial of less than 4 degrees - * such that it will fit in a word. In AES, this polynomial is x^4 + 1. - * - * The modular product of two polynomials 'a' and 'b' is thus: - * - * d(x) = d3x^3 + d2x^2 + d1x + d0 - * with - * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3) - * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3) - * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3) - * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3) - * - * As a matrix: - * - * [d0] = [a0 a3 a2 a1][b0] - * [d1] [a1 a0 a3 a2][b1] - * [d2] [a2 a1 a0 a3][b2] - * [d3] [a3 a2 a1 a0][b3] - * - * Special polynomials defined by AES (0x02 == {02}): - * a(x) = {03}x^3 + {01}x^2 + {01}x + {02} - * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}. - * - * These polynomials are used in the MixColumns() and InverseMixColumns() - * operations, respectively, to cause each element in the state to affect - * the output (referred to as diffusing). - * - * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the - * polynomial x3. - * - * The ShiftRows() method modifies the last 3 rows in the state (where - * the state is 4 words with 4 bytes per word) by shifting bytes cyclically. - * The 1st byte in the second row is moved to the end of the row. The 1st - * and 2nd bytes in the third row are moved to the end of the row. The 1st, - * 2nd, and 3rd bytes are moved in the fourth row. - * - * More details on how AES arithmetic works: - * - * In the polynomial representation of binary numbers, XOR performs addition - * and subtraction and multiplication in GF(2^8) denoted as GF(a, b) - * corresponds with the multiplication of polynomials modulo an irreducible - * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply - * polynomial 'a' with polynomial 'b' and then do a modular reduction by - * an AES-specific irreducible polynomial of degree 8. - * - * A polynomial is irreducible if its only divisors are one and itself. For - * the AES algorithm, this irreducible polynomial is: - * - * m(x) = x^8 + x^4 + x^3 + x + 1, - * - * or {01}{1b} in hexadecimal notation, where each coefficient is a bit: - * 100011011 = 283 = 0x11b. - * - * For example, GF(0x57, 0x83) = 0xc1 because - * - * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1 - * 0x85 = 131 = 10000101 = x^7 + x + 1 - * - * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1) - * = x^13 + x^11 + x^9 + x^8 + x^7 + - * x^7 + x^5 + x^3 + x^2 + x + - * x^6 + x^4 + x^2 + x + 1 - * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y - * y modulo (x^8 + x^4 + x^3 + x + 1) - * = x^7 + x^6 + 1. - * - * The modular reduction by m(x) guarantees the result will be a binary - * polynomial of less than degree 8, so that it can fit in a byte. - * - * The operation to multiply a binary polynomial b with x (the polynomial - * x in binary representation is 00000010) is: - * - * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1 - * - * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the - * most significant bit is 0 in b) then the result is already reduced. If - * it is 1, then we can reduce it by subtracting m(x) via an XOR. - * - * It follows that multiplication by x (00000010 or 0x02) can be implemented - * by performing a left shift followed by a conditional bitwise XOR with - * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by - * higher powers of x can be implemented by repeated application of xtime(). - * - * By adding intermediate results, multiplication by any constant can be - * implemented. For instance: - * - * GF(0x57, 0x13) = 0xfe because: - * - * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1) - * - * Note: We XOR with 0x11b instead of 0x1b because in javascript our - * datatype for b can be larger than 1 byte, so a left shift will not - * automatically eliminate bits that overflow a byte ... by XOR'ing the - * overflow bit with 1 (the extra one from 0x11b) we zero it out. - * - * GF(0x57, 0x02) = xtime(0x57) = 0xae - * GF(0x57, 0x04) = xtime(0xae) = 0x47 - * GF(0x57, 0x08) = xtime(0x47) = 0x8e - * GF(0x57, 0x10) = xtime(0x8e) = 0x07 - * - * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10)) - * - * And by the distributive property (since XOR is addition and GF() is - * multiplication): - * - * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10) - * = 0x57 ^ 0xae ^ 0x07 - * = 0xfe. - */ -function initialize() { - init = true; - - /* Populate the Rcon table. These are the values given by - [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02) - in the field of GF(2^8), where i starts at 1. - - rcon[0] = [0x00, 0x00, 0x00, 0x00] - rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1 - rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2 - ... - rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B - rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36 - - We only store the first byte because it is the only one used. - */ - rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]; - - // compute xtime table which maps i onto GF(i, 0x02) - var xtime = new Array(256); - for(var i = 0; i < 128; ++i) { - xtime[i] = i << 1; - xtime[i + 128] = (i + 128) << 1 ^ 0x11B; - } - - // compute all other tables - sbox = new Array(256); - isbox = new Array(256); - mix = new Array(4); - imix = new Array(4); - for(var i = 0; i < 4; ++i) { - mix[i] = new Array(256); - imix[i] = new Array(256); - } - var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; - for(var i = 0; i < 256; ++i) { - /* We need to generate the SubBytes() sbox and isbox tables so that - we can perform byte substitutions. This requires us to traverse - all of the elements in GF, find their multiplicative inverses, - and apply to each the following affine transformation: - - bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^ - b(i + 7) mod 8 ^ ci - for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the - ith bit of a byte c with the value {63} or {01100011}. - - It is possible to traverse every possible value in a Galois field - using what is referred to as a 'generator'. There are many - generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully - traverse GF we iterate 255 times, multiplying by our generator - each time. - - On each iteration we can determine the multiplicative inverse for - the current element. - - Suppose there is an element in GF 'e'. For a given generator 'g', - e = g^x. The multiplicative inverse of e is g^(255 - x). It turns - out that if use the inverse of a generator as another generator - it will produce all of the corresponding multiplicative inverses - at the same time. For this reason, we choose 5 as our inverse - generator because it only requires 2 multiplies and 1 add and its - inverse, 82, requires relatively few operations as well. - - In order to apply the affine transformation, the multiplicative - inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a - bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and - 'x'. Then 's' is left shifted and the high bit of 's' is made the - low bit. The resulting value is stored in 's'. Then 'x' is XOR'd - with 's' and stored in 'x'. On each subsequent iteration the same - operation is performed. When 4 iterations are complete, 'x' is - XOR'd with 'c' (0x63) and the transformed value is stored in 'x'. - For example: - - s = 01000001 - x = 01000001 - - iteration 1: s = 10000010, x ^= s - iteration 2: s = 00000101, x ^= s - iteration 3: s = 00001010, x ^= s - iteration 4: s = 00010100, x ^= s - x ^= 0x63 - - This can be done with a loop where s = (s << 1) | (s >> 7). However, - it can also be done by using a single 16-bit (in this case 32-bit) - number 'sx'. Since XOR is an associative operation, we can set 'sx' - to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times. - The most significant bits will flow into the high 8 bit positions - and be correctly XOR'd with one another. All that remains will be - to cycle the high 8 bits by XOR'ing them all with the lower 8 bits - afterwards. - - At the same time we're populating sbox and isbox we can precompute - the multiplication we'll need to do to do MixColumns() later. - */ - - // apply affine transformation - sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); - sx = (sx >> 8) ^ (sx & 255) ^ 0x63; - - // update tables - sbox[e] = sx; - isbox[sx] = e; - - /* Mixing columns is done using matrix multiplication. The columns - that are to be mixed are each a single word in the current state. - The state has Nb columns (4 columns). Therefore each column is a - 4 byte word. So to mix the columns in a single column 'c' where - its rows are r0, r1, r2, and r3, we use the following matrix - multiplication: - - [2 3 1 1]*[r0,c]=[r'0,c] - [1 2 3 1] [r1,c] [r'1,c] - [1 1 2 3] [r2,c] [r'2,c] - [3 1 1 2] [r3,c] [r'3,c] - - r0, r1, r2, and r3 are each 1 byte of one of the words in the - state (a column). To do matrix multiplication for each mixed - column c' we multiply the corresponding row from the left matrix - with the corresponding column from the right matrix. In total, we - get 4 equations: - - r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c - r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c - r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c - r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c - - As usual, the multiplication is as previously defined and the - addition is XOR. In order to optimize mixing columns we can store - the multiplication results in tables. If you think of the whole - column as a word (it might help to visualize by mentally rotating - the equations above by counterclockwise 90 degrees) then you can - see that it would be useful to map the multiplications performed on - each byte (r0, r1, r2, r3) onto a word as well. For instance, we - could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the - highest 8 bits and 3*r0 in the lowest 8 bits (with the other two - respectively in the middle). This means that a table can be - constructed that uses r0 as an index to the word. We can do the - same with r1, r2, and r3, creating a total of 4 tables. - - To construct a full c', we can just look up each byte of c in - their respective tables and XOR the results together. - - Also, to build each table we only have to calculate the word - for 2,1,1,3 for every byte ... which we can do on each iteration - of this loop since we will iterate over every byte. After we have - calculated 2,1,1,3 we can get the results for the other tables - by cycling the byte at the end to the beginning. For instance - we can take the result of table 2,1,1,3 and produce table 3,2,1,1 - by moving the right most byte to the left most position just like - how you can imagine the 3 moved out of 2,1,1,3 and to the front - to produce 3,2,1,1. - - There is another optimization in that the same multiples of - the current element we need in order to advance our generator - to the next iteration can be reused in performing the 2,1,1,3 - calculation. We also calculate the inverse mix column tables, - with e,9,d,b being the inverse of 2,1,1,3. - - When we're done, and we need to actually mix columns, the first - byte of each state word should be put through mix[0] (2,1,1,3), - the second through mix[1] (3,2,1,1) and so forth. Then they should - be XOR'd together to produce the fully mixed column. - */ - - // calculate mix and imix table values - sx2 = xtime[sx]; - e2 = xtime[e]; - e4 = xtime[e2]; - e8 = xtime[e4]; - me = - (sx2 << 24) ^ // 2 - (sx << 16) ^ // 1 - (sx << 8) ^ // 1 - (sx ^ sx2); // 3 - ime = - (e2 ^ e4 ^ e8) << 24 ^ // E (14) - (e ^ e8) << 16 ^ // 9 - (e ^ e4 ^ e8) << 8 ^ // D (13) - (e ^ e2 ^ e8); // B (11) - // produce each of the mix tables by rotating the 2,1,1,3 value - for(var n = 0; n < 4; ++n) { - mix[n][e] = me; - imix[n][sx] = ime; - // cycle the right most byte to the left most position - // ie: 2,1,1,3 becomes 3,2,1,1 - me = me << 24 | me >>> 8; - ime = ime << 24 | ime >>> 8; - } - - // get next element and inverse - if(e === 0) { - // 1 is the inverse of 1 - e = ei = 1; - } else { - // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator) - // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator) - e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; - ei ^= xtime[xtime[ei]]; - } - } -} - -/** - * Generates a key schedule using the AES key expansion algorithm. - * - * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion - * routine to generate a key schedule. The Key Expansion generates a total - * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words, - * and each of the Nr rounds requires Nb words of key data. The resulting - * key schedule consists of a linear array of 4-byte words, denoted [wi ], - * with i in the range 0 <= i < Nb(Nr + 1). - * - * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk) - * AES-128 (Nb=4, Nk=4, Nr=10) - * AES-192 (Nb=4, Nk=6, Nr=12) - * AES-256 (Nb=4, Nk=8, Nr=14) - * Note: Nr=Nk+6. - * - * Nb is the number of columns (32-bit words) comprising the State (or - * number of bytes in a block). For AES, Nb=4. - * - * @param key the key to schedule (as an array of 32-bit words). - * @param decrypt true to modify the key schedule to decrypt, false not to. - * - * @return the generated key schedule. - */ -function _expandKey(key, decrypt) { - // copy the key's words to initialize the key schedule - var w = key.slice(0); - - /* RotWord() will rotate a word, moving the first byte to the last - byte's position (shifting the other bytes left). - - We will be getting the value of Rcon at i / Nk. 'i' will iterate - from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in - a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from - 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will - increase by 1. We use a counter iNk to keep track of this. - */ - - // go through the rounds expanding the key - var temp, iNk = 1; - var Nk = w.length; - var Nr1 = Nk + 6 + 1; - var end = Nb * Nr1; - for(var i = Nk; i < end; ++i) { - temp = w[i - 1]; - if(i % Nk === 0) { - // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] - temp = - sbox[temp >>> 16 & 255] << 24 ^ - sbox[temp >>> 8 & 255] << 16 ^ - sbox[temp & 255] << 8 ^ - sbox[temp >>> 24] ^ (rcon[iNk] << 24); - iNk++; - } else if(Nk > 6 && (i % Nk === 4)) { - // temp = SubWord(temp) - temp = - sbox[temp >>> 24] << 24 ^ - sbox[temp >>> 16 & 255] << 16 ^ - sbox[temp >>> 8 & 255] << 8 ^ - sbox[temp & 255]; - } - w[i] = w[i - Nk] ^ temp; - } - - /* When we are updating a cipher block we always use the code path for - encryption whether we are decrypting or not (to shorten code and - simplify the generation of look up tables). However, because there - are differences in the decryption algorithm, other than just swapping - in different look up tables, we must transform our key schedule to - account for these changes: - - 1. The decryption algorithm gets its key rounds in reverse order. - 2. The decryption algorithm adds the round key before mixing columns - instead of afterwards. - - We don't need to modify our key schedule to handle the first case, - we can just traverse the key schedule in reverse order when decrypting. - - The second case requires a little work. - - The tables we built for performing rounds will take an input and then - perform SubBytes() and MixColumns() or, for the decrypt version, - InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires - us to AddRoundKey() before InvMixColumns(). This means we'll need to - apply some transformations to the round key to inverse-mix its columns - so they'll be correct for moving AddRoundKey() to after the state has - had its columns inverse-mixed. - - To inverse-mix the columns of the state when we're decrypting we use a - lookup table that will apply InvSubBytes() and InvMixColumns() at the - same time. However, the round key's bytes are not inverse-substituted - in the decryption algorithm. To get around this problem, we can first - substitute the bytes in the round key so that when we apply the - transformation via the InvSubBytes()+InvMixColumns() table, it will - undo our substitution leaving us with the original value that we - want -- and then inverse-mix that value. - - This change will correctly alter our key schedule so that we can XOR - each round key with our already transformed decryption state. This - allows us to use the same code path as the encryption algorithm. - - We make one more change to the decryption key. Since the decryption - algorithm runs in reverse from the encryption algorithm, we reverse - the order of the round keys to avoid having to iterate over the key - schedule backwards when running the encryption algorithm later in - decryption mode. In addition to reversing the order of the round keys, - we also swap each round key's 2nd and 4th rows. See the comments - section where rounds are performed for more details about why this is - done. These changes are done inline with the other substitution - described above. - */ - if(decrypt) { - var tmp; - var m0 = imix[0]; - var m1 = imix[1]; - var m2 = imix[2]; - var m3 = imix[3]; - var wnew = w.slice(0); - end = w.length; - for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { - // do not sub the first or last round key (round keys are Nb - // words) as no column mixing is performed before they are added, - // but do change the key order - if(i === 0 || i === (end - Nb)) { - wnew[i] = w[wi]; - wnew[i + 1] = w[wi + 3]; - wnew[i + 2] = w[wi + 2]; - wnew[i + 3] = w[wi + 1]; - } else { - // substitute each round key byte because the inverse-mix - // table will inverse-substitute it (effectively cancel the - // substitution because round key bytes aren't sub'd in - // decryption mode) and swap indexes 3 and 1 - for(var n = 0; n < Nb; ++n) { - tmp = w[wi + n]; - wnew[i + (3&-n)] = - m0[sbox[tmp >>> 24]] ^ - m1[sbox[tmp >>> 16 & 255]] ^ - m2[sbox[tmp >>> 8 & 255]] ^ - m3[sbox[tmp & 255]]; - } - } - } - w = wnew; - } - - return w; -} - -/** - * Updates a single block (16 bytes) using AES. The update will either - * encrypt or decrypt the block. - * - * @param w the key schedule. - * @param input the input block (an array of 32-bit words). - * @param output the updated output block. - * @param decrypt true to decrypt the block, false to encrypt it. - */ -function _updateBlock$1(w, input, output, decrypt) { - /* - Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) - begin - byte state[4,Nb] - state = in - AddRoundKey(state, w[0, Nb-1]) - for round = 1 step 1 to Nr-1 - SubBytes(state) - ShiftRows(state) - MixColumns(state) - AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) - end for - SubBytes(state) - ShiftRows(state) - AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - out = state - end - - InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) - begin - byte state[4,Nb] - state = in - AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - for round = Nr-1 step -1 downto 1 - InvShiftRows(state) - InvSubBytes(state) - AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) - InvMixColumns(state) - end for - InvShiftRows(state) - InvSubBytes(state) - AddRoundKey(state, w[0, Nb-1]) - out = state - end - */ - - // Encrypt: AddRoundKey(state, w[0, Nb-1]) - // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - var Nr = w.length / 4 - 1; - var m0, m1, m2, m3, sub; - if(decrypt) { - m0 = imix[0]; - m1 = imix[1]; - m2 = imix[2]; - m3 = imix[3]; - sub = isbox; - } else { - m0 = mix[0]; - m1 = mix[1]; - m2 = mix[2]; - m3 = mix[3]; - sub = sbox; - } - var a, b, c, d, a2, b2, c2; - a = input[0] ^ w[0]; - b = input[decrypt ? 3 : 1] ^ w[1]; - c = input[2] ^ w[2]; - d = input[decrypt ? 1 : 3] ^ w[3]; - var i = 3; - - /* In order to share code we follow the encryption algorithm when both - encrypting and decrypting. To account for the changes required in the - decryption algorithm, we use different lookup tables when decrypting - and use a modified key schedule to account for the difference in the - order of transformations applied when performing rounds. We also get - key rounds in reverse order (relative to encryption). */ - for(var round = 1; round < Nr; ++round) { - /* As described above, we'll be using table lookups to perform the - column mixing. Each column is stored as a word in the state (the - array 'input' has one column as a word at each index). In order to - mix a column, we perform these transformations on each row in c, - which is 1 byte in each word. The new column for c0 is c'0: - - m0 m1 m2 m3 - r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0 - r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0 - r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0 - r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0 - - So using mix tables where c0 is a word with r0 being its upper - 8 bits and r3 being its lower 8 bits: - - m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0] - ... - m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3] - - Therefore to mix the columns in each word in the state we - do the following (& 255 omitted for brevity): - c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] - - However, before mixing, the algorithm requires us to perform - ShiftRows(). The ShiftRows() transformation cyclically shifts the - last 3 rows of the state over different offsets. The first row - (r = 0) is not shifted. - - s'_r,c = s_r,(c + shift(r, Nb) mod Nb - for 0 < r < 4 and 0 <= c < Nb and - shift(1, 4) = 1 - shift(2, 4) = 2 - shift(3, 4) = 3. - - This causes the first byte in r = 1 to be moved to the end of - the row, the first 2 bytes in r = 2 to be moved to the end of - the row, the first 3 bytes in r = 3 to be moved to the end of - the row: - - r1: [c0 c1 c2 c3] => [c1 c2 c3 c0] - r2: [c0 c1 c2 c3] [c2 c3 c0 c1] - r3: [c0 c1 c2 c3] [c3 c0 c1 c2] - - We can make these substitutions inline with our column mixing to - generate an updated set of equations to produce each word in the - state (note the columns have changed positions): - - c0 c1 c2 c3 => c0 c1 c2 c3 - c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte) - c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes) - c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes) - - Therefore: - - c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3 - c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3 - c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3 - c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3 - - c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0 - c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0 - c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0 - c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0 - - ... and so forth for c'2 and c'3. The important distinction is - that the columns are cycling, with c0 being used with the m0 - map when calculating c0, but c1 being used with the m0 map when - calculating c1 ... and so forth. - - When performing the inverse we transform the mirror image and - skip the bottom row, instead of the top one, and move upwards: - - c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption - c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes) - c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption - c3 c2 c1 c0 c3 c2 c1 c0 - - If you compare the resulting matrices for ShiftRows()+MixColumns() - and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are - different (in encrypt mode vs. decrypt mode). So in order to use - the same code to handle both encryption and decryption, we will - need to do some mapping. - - If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be - a row number in the state, then the resulting matrix in encryption - mode for applying the above transformations would be: - - r1: a b c d - r2: b c d a - r3: c d a b - r4: d a b c - - If we did the same in decryption mode we would get: - - r1: a d c b - r2: b a d c - r3: c b a d - r4: d c b a - - If instead we swap d and b (set b=c3 and d=c1), then we get: - - r1: a b c d - r2: d a b c - r3: c d a b - r4: b c d a - - Now the 1st and 3rd rows are the same as the encryption matrix. All - we need to do then to make the mapping exactly the same is to swap - the 2nd and 4th rows when in decryption mode. To do this without - having to do it on each iteration, we swapped the 2nd and 4th rows - in the decryption key schedule. We also have to do the swap above - when we first pull in the input and when we set the final output. */ - a2 = - m0[a >>> 24] ^ - m1[b >>> 16 & 255] ^ - m2[c >>> 8 & 255] ^ - m3[d & 255] ^ w[++i]; - b2 = - m0[b >>> 24] ^ - m1[c >>> 16 & 255] ^ - m2[d >>> 8 & 255] ^ - m3[a & 255] ^ w[++i]; - c2 = - m0[c >>> 24] ^ - m1[d >>> 16 & 255] ^ - m2[a >>> 8 & 255] ^ - m3[b & 255] ^ w[++i]; - d = - m0[d >>> 24] ^ - m1[a >>> 16 & 255] ^ - m2[b >>> 8 & 255] ^ - m3[c & 255] ^ w[++i]; - a = a2; - b = b2; - c = c2; - } - - /* - Encrypt: - SubBytes(state) - ShiftRows(state) - AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) - - Decrypt: - InvShiftRows(state) - InvSubBytes(state) - AddRoundKey(state, w[0, Nb-1]) - */ - // Note: rows are shifted inline - output[0] = - (sub[a >>> 24] << 24) ^ - (sub[b >>> 16 & 255] << 16) ^ - (sub[c >>> 8 & 255] << 8) ^ - (sub[d & 255]) ^ w[++i]; - output[decrypt ? 3 : 1] = - (sub[b >>> 24] << 24) ^ - (sub[c >>> 16 & 255] << 16) ^ - (sub[d >>> 8 & 255] << 8) ^ - (sub[a & 255]) ^ w[++i]; - output[2] = - (sub[c >>> 24] << 24) ^ - (sub[d >>> 16 & 255] << 16) ^ - (sub[a >>> 8 & 255] << 8) ^ - (sub[b & 255]) ^ w[++i]; - output[decrypt ? 1 : 3] = - (sub[d >>> 24] << 24) ^ - (sub[a >>> 16 & 255] << 16) ^ - (sub[b >>> 8 & 255] << 8) ^ - (sub[c & 255]) ^ w[++i]; -} - -/** - * Deprecated. Instead, use: - * - * forge.cipher.createCipher('AES-', key); - * forge.cipher.createDecipher('AES-', key); - * - * Creates a deprecated AES cipher object. This object's mode will default to - * CBC (cipher-block-chaining). - * - * The key and iv may be given as a string of bytes, an array of bytes, a - * byte buffer, or an array of 32-bit words. - * - * @param options the options to use. - * key the symmetric key to use. - * output the buffer to write to. - * decrypt true for decryption, false for encryption. - * mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -function _createCipher$1(options) { - options = options || {}; - var mode = (options.mode || 'CBC').toUpperCase(); - var algorithm = 'AES-' + mode; - - var cipher; - if(options.decrypt) { - cipher = forge$B.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge$B.cipher.createCipher(algorithm, options.key); - } - - // backwards compatible start API - var start = cipher.start; - cipher.start = function(iv, options) { - // backwards compatibility: support second arg as output buffer - var output = null; - if(options instanceof forge$B.util.ByteBuffer) { - output = options; - options = {}; - } - options = options || {}; - options.output = output; - options.iv = iv; - start.call(cipher, options); - }; - - return cipher; -} - -/** - * Object IDs for ASN.1. - * - * @author Dave Longley - * - * Copyright (c) 2010-2013 Digital Bazaar, Inc. - */ - -var forge$A = forge$F; - -forge$A.pki = forge$A.pki || {}; -var oids$2 = forge$A.pki.oids = forge$A.oids = forge$A.oids || {}; - -// set id to name mapping and name to id mapping -function _IN(id, name) { - oids$2[id] = name; - oids$2[name] = id; -} -// set id to name mapping only -function _I_(id, name) { - oids$2[id] = name; -} - -// algorithm OIDs -_IN('1.2.840.113549.1.1.1', 'rsaEncryption'); -// Note: md2 & md4 not implemented -//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption'); -//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption'); -_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption'); -_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption'); -_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP'); -_IN('1.2.840.113549.1.1.8', 'mgf1'); -_IN('1.2.840.113549.1.1.9', 'pSpecified'); -_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS'); -_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption'); -_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption'); -_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption'); -// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519 -_IN('1.3.101.112', 'EdDSA25519'); - -_IN('1.2.840.10040.4.3', 'dsa-with-sha1'); - -_IN('1.3.14.3.2.7', 'desCBC'); - -_IN('1.3.14.3.2.26', 'sha1'); -_IN('2.16.840.1.101.3.4.2.1', 'sha256'); -_IN('2.16.840.1.101.3.4.2.2', 'sha384'); -_IN('2.16.840.1.101.3.4.2.3', 'sha512'); -_IN('1.2.840.113549.2.5', 'md5'); - -// pkcs#7 content types -_IN('1.2.840.113549.1.7.1', 'data'); -_IN('1.2.840.113549.1.7.2', 'signedData'); -_IN('1.2.840.113549.1.7.3', 'envelopedData'); -_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData'); -_IN('1.2.840.113549.1.7.5', 'digestedData'); -_IN('1.2.840.113549.1.7.6', 'encryptedData'); - -// pkcs#9 oids -_IN('1.2.840.113549.1.9.1', 'emailAddress'); -_IN('1.2.840.113549.1.9.2', 'unstructuredName'); -_IN('1.2.840.113549.1.9.3', 'contentType'); -_IN('1.2.840.113549.1.9.4', 'messageDigest'); -_IN('1.2.840.113549.1.9.5', 'signingTime'); -_IN('1.2.840.113549.1.9.6', 'counterSignature'); -_IN('1.2.840.113549.1.9.7', 'challengePassword'); -_IN('1.2.840.113549.1.9.8', 'unstructuredAddress'); -_IN('1.2.840.113549.1.9.14', 'extensionRequest'); - -_IN('1.2.840.113549.1.9.20', 'friendlyName'); -_IN('1.2.840.113549.1.9.21', 'localKeyId'); -_IN('1.2.840.113549.1.9.22.1', 'x509Certificate'); - -// pkcs#12 safe bags -_IN('1.2.840.113549.1.12.10.1.1', 'keyBag'); -_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag'); -_IN('1.2.840.113549.1.12.10.1.3', 'certBag'); -_IN('1.2.840.113549.1.12.10.1.4', 'crlBag'); -_IN('1.2.840.113549.1.12.10.1.5', 'secretBag'); -_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag'); - -// password-based-encryption for pkcs#12 -_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2'); -_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2'); - -_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4'); -_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4'); -_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC'); -_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC'); -_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC'); -_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC'); - -// hmac OIDs -_IN('1.2.840.113549.2.7', 'hmacWithSHA1'); -_IN('1.2.840.113549.2.8', 'hmacWithSHA224'); -_IN('1.2.840.113549.2.9', 'hmacWithSHA256'); -_IN('1.2.840.113549.2.10', 'hmacWithSHA384'); -_IN('1.2.840.113549.2.11', 'hmacWithSHA512'); - -// symmetric key algorithm oids -_IN('1.2.840.113549.3.7', 'des-EDE3-CBC'); -_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC'); -_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC'); -_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC'); - -// certificate issuer/subject OIDs -_IN('2.5.4.3', 'commonName'); -_IN('2.5.4.5', 'serialName'); -_IN('2.5.4.6', 'countryName'); -_IN('2.5.4.7', 'localityName'); -_IN('2.5.4.8', 'stateOrProvinceName'); -_IN('2.5.4.9', 'streetAddress'); -_IN('2.5.4.10', 'organizationName'); -_IN('2.5.4.11', 'organizationalUnitName'); -_IN('2.5.4.13', 'description'); -_IN('2.5.4.15', 'businessCategory'); -_IN('2.5.4.17', 'postalCode'); -_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName'); -_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName'); - -// X.509 extension OIDs -_IN('2.16.840.1.113730.1.1', 'nsCertType'); -_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used -_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35 -_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15 -_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32 -_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15 -_I_('2.5.29.5', 'policyMapping'); // deprecated use .33 -_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30 -_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17 -_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18 -_I_('2.5.29.9', 'subjectDirectoryAttributes'); -_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19 -_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30 -_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36 -_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19 -_IN('2.5.29.14', 'subjectKeyIdentifier'); -_IN('2.5.29.15', 'keyUsage'); -_I_('2.5.29.16', 'privateKeyUsagePeriod'); -_IN('2.5.29.17', 'subjectAltName'); -_IN('2.5.29.18', 'issuerAltName'); -_IN('2.5.29.19', 'basicConstraints'); -_I_('2.5.29.20', 'cRLNumber'); -_I_('2.5.29.21', 'cRLReason'); -_I_('2.5.29.22', 'expirationDate'); -_I_('2.5.29.23', 'instructionCode'); -_I_('2.5.29.24', 'invalidityDate'); -_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31 -_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28 -_I_('2.5.29.27', 'deltaCRLIndicator'); -_I_('2.5.29.28', 'issuingDistributionPoint'); -_I_('2.5.29.29', 'certificateIssuer'); -_I_('2.5.29.30', 'nameConstraints'); -_IN('2.5.29.31', 'cRLDistributionPoints'); -_IN('2.5.29.32', 'certificatePolicies'); -_I_('2.5.29.33', 'policyMappings'); -_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36 -_IN('2.5.29.35', 'authorityKeyIdentifier'); -_I_('2.5.29.36', 'policyConstraints'); -_IN('2.5.29.37', 'extKeyUsage'); -_I_('2.5.29.46', 'freshestCRL'); -_I_('2.5.29.54', 'inhibitAnyPolicy'); - -// extKeyUsage purposes -_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList'); -_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess'); -_IN('1.3.6.1.5.5.7.3.1', 'serverAuth'); -_IN('1.3.6.1.5.5.7.3.2', 'clientAuth'); -_IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); -_IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); -_IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); - -/** - * Javascript implementation of Abstract Syntax Notation Number One. - * - * @author Dave Longley - * - * Copyright (c) 2010-2015 Digital Bazaar, Inc. - * - * An API for storing data using the Abstract Syntax Notation Number One - * format using DER (Distinguished Encoding Rules) encoding. This encoding is - * commonly used to store data for PKI, i.e. X.509 Certificates, and this - * implementation exists for that purpose. - * - * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract - * syntax of information without restricting the way the information is encoded - * for transmission. It provides a standard that allows for open systems - * communication. ASN.1 defines the syntax of information data and a number of - * simple data types as well as a notation for describing them and specifying - * values for them. - * - * The RSA algorithm creates public and private keys that are often stored in - * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This - * class provides the most basic functionality required to store and load DSA - * keys that are encoded according to ASN.1. - * - * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules) - * and DER (Distinguished Encoding Rules). DER is just a subset of BER that - * has stricter requirements for how data must be encoded. - * - * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type) - * and a byte array for the value of this ASN1 structure which may be data or a - * list of ASN.1 structures. - * - * Each ASN.1 structure using BER is (Tag-Length-Value): - * - * | byte 0 | bytes X | bytes Y | - * |--------|---------|---------- - * | tag | length | value | - * - * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to - * be two or more octets, but that is not supported by this class. A tag is - * only 1 byte. Bits 1-5 give the tag number (ie the data type within a - * particular 'class'), 6 indicates whether or not the ASN.1 value is - * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If - * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set, - * then the class is APPLICATION. If only bit 8 is set, then the class is - * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE. - * The tag numbers for the data types for the class UNIVERSAL are listed below: - * - * UNIVERSAL 0 Reserved for use by the encoding rules - * UNIVERSAL 1 Boolean type - * UNIVERSAL 2 Integer type - * UNIVERSAL 3 Bitstring type - * UNIVERSAL 4 Octetstring type - * UNIVERSAL 5 Null type - * UNIVERSAL 6 Object identifier type - * UNIVERSAL 7 Object descriptor type - * UNIVERSAL 8 External type and Instance-of type - * UNIVERSAL 9 Real type - * UNIVERSAL 10 Enumerated type - * UNIVERSAL 11 Embedded-pdv type - * UNIVERSAL 12 UTF8String type - * UNIVERSAL 13 Relative object identifier type - * UNIVERSAL 14-15 Reserved for future editions - * UNIVERSAL 16 Sequence and Sequence-of types - * UNIVERSAL 17 Set and Set-of types - * UNIVERSAL 18-22, 25-30 Character string types - * UNIVERSAL 23-24 Time types - * - * The length of an ASN.1 structure is specified after the tag identifier. - * There is a definite form and an indefinite form. The indefinite form may - * be used if the encoding is constructed and not all immediately available. - * The indefinite form is encoded using a length byte with only the 8th bit - * set. The end of the constructed object is marked using end-of-contents - * octets (two zero bytes). - * - * The definite form looks like this: - * - * The length may take up 1 or more bytes, it depends on the length of the - * value of the ASN.1 structure. DER encoding requires that if the ASN.1 - * structure has a value that has a length greater than 127, more than 1 byte - * will be used to store its length, otherwise just one byte will be used. - * This is strict. - * - * In the case that the length of the ASN.1 value is less than 127, 1 octet - * (byte) is used to store the "short form" length. The 8th bit has a value of - * 0 indicating the length is "short form" and not "long form" and bits 7-1 - * give the length of the data. (The 8th bit is the left-most, most significant - * bit: also known as big endian or network format). - * - * In the case that the length of the ASN.1 value is greater than 127, 2 to - * 127 octets (bytes) are used to store the "long form" length. The first - * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1 - * give the number of additional octets. All following octets are in base 256 - * with the most significant digit first (typical big-endian binary unsigned - * integer storage). So, for instance, if the length of a value was 257, the - * first byte would be set to: - * - * 10000010 = 130 = 0x82. - * - * This indicates there are 2 octets (base 256) for the length. The second and - * third bytes (the octets just mentioned) would store the length in base 256: - * - * octet 2: 00000001 = 1 * 256^1 = 256 - * octet 3: 00000001 = 1 * 256^0 = 1 - * total = 257 - * - * The algorithm for converting a js integer value of 257 to base-256 is: - * - * var value = 257; - * var bytes = []; - * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first - * bytes[1] = value & 0xFF; // least significant byte last - * - * On the ASN.1 UNIVERSAL Object Identifier (OID) type: - * - * An OID can be written like: "value1.value2.value3...valueN" - * - * The DER encoding rules: - * - * The first byte has the value 40 * value1 + value2. - * The following bytes, if any, encode the remaining values. Each value is - * encoded in base 128, most significant digit first (big endian), with as - * few digits as possible, and the most significant bit of each byte set - * to 1 except the last in each value's encoding. For example: Given the - * OID "1.2.840.113549", its DER encoding is (remember each byte except the - * last one in each encoding is OR'd with 0x80): - * - * byte 1: 40 * 1 + 2 = 42 = 0x2A. - * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648 - * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D - * - * The final value is: 0x2A864886F70D. - * The full OID (including ASN.1 tag and length of 6 bytes) is: - * 0x06062A864886F70D - */ - -var forge$z = forge$F; - - - -/* ASN.1 API */ -var asn1$8 = forge$z.asn1 = forge$z.asn1 || {}; - -/** - * ASN.1 classes. - */ -asn1$8.Class = { - UNIVERSAL: 0x00, - APPLICATION: 0x40, - CONTEXT_SPECIFIC: 0x80, - PRIVATE: 0xC0 -}; - -/** - * ASN.1 types. Not all types are supported by this implementation, only - * those necessary to implement a simple PKI are implemented. - */ -asn1$8.Type = { - NONE: 0, - BOOLEAN: 1, - INTEGER: 2, - BITSTRING: 3, - OCTETSTRING: 4, - NULL: 5, - OID: 6, - ODESC: 7, - EXTERNAL: 8, - REAL: 9, - ENUMERATED: 10, - EMBEDDED: 11, - UTF8: 12, - ROID: 13, - SEQUENCE: 16, - SET: 17, - PRINTABLESTRING: 19, - IA5STRING: 22, - UTCTIME: 23, - GENERALIZEDTIME: 24, - BMPSTRING: 30 -}; - -/** - * Creates a new asn1 object. - * - * @param tagClass the tag class for the object. - * @param type the data type (tag number) for the object. - * @param constructed true if the asn1 object is in constructed form. - * @param value the value for the object, if it is not constructed. - * @param [options] the options to use: - * [bitStringContents] the plain BIT STRING content including padding - * byte. - * - * @return the asn1 object. - */ -asn1$8.create = function(tagClass, type, constructed, value, options) { - /* An asn1 object has a tagClass, a type, a constructed flag, and a - value. The value's type depends on the constructed flag. If - constructed, it will contain a list of other asn1 objects. If not, - it will contain the ASN.1 value as an array of bytes formatted - according to the ASN.1 data type. */ - - // remove undefined values - if(forge$z.util.isArray(value)) { - var tmp = []; - for(var i = 0; i < value.length; ++i) { - if(value[i] !== undefined) { - tmp.push(value[i]); - } - } - value = tmp; - } - - var obj = { - tagClass: tagClass, - type: type, - constructed: constructed, - composed: constructed || forge$z.util.isArray(value), - value: value - }; - if(options && 'bitStringContents' in options) { - // TODO: copy byte buffer if it's a buffer not a string - obj.bitStringContents = options.bitStringContents; - // TODO: add readonly flag to avoid this overhead - // save copy to detect changes - obj.original = asn1$8.copy(obj); - } - return obj; -}; - -/** - * Copies an asn1 object. - * - * @param obj the asn1 object. - * @param [options] copy options: - * [excludeBitStringContents] true to not copy bitStringContents - * - * @return the a copy of the asn1 object. - */ -asn1$8.copy = function(obj, options) { - var copy; - - if(forge$z.util.isArray(obj)) { - copy = []; - for(var i = 0; i < obj.length; ++i) { - copy.push(asn1$8.copy(obj[i], options)); - } - return copy; - } - - if(typeof obj === 'string') { - // TODO: copy byte buffer if it's a buffer not a string - return obj; - } - - copy = { - tagClass: obj.tagClass, - type: obj.type, - constructed: obj.constructed, - composed: obj.composed, - value: asn1$8.copy(obj.value, options) - }; - if(options && !options.excludeBitStringContents) { - // TODO: copy byte buffer if it's a buffer not a string - copy.bitStringContents = obj.bitStringContents; - } - return copy; -}; - -/** - * Compares asn1 objects for equality. - * - * Note this function does not run in constant time. - * - * @param obj1 the first asn1 object. - * @param obj2 the second asn1 object. - * @param [options] compare options: - * [includeBitStringContents] true to compare bitStringContents - * - * @return true if the asn1 objects are equal. - */ -asn1$8.equals = function(obj1, obj2, options) { - if(forge$z.util.isArray(obj1)) { - if(!forge$z.util.isArray(obj2)) { - return false; - } - if(obj1.length !== obj2.length) { - return false; - } - for(var i = 0; i < obj1.length; ++i) { - if(!asn1$8.equals(obj1[i], obj2[i])) { - return false; - } - } - return true; - } - - if(typeof obj1 !== typeof obj2) { - return false; - } - - if(typeof obj1 === 'string') { - return obj1 === obj2; - } - - var equal = obj1.tagClass === obj2.tagClass && - obj1.type === obj2.type && - obj1.constructed === obj2.constructed && - obj1.composed === obj2.composed && - asn1$8.equals(obj1.value, obj2.value); - if(options && options.includeBitStringContents) { - equal = equal && (obj1.bitStringContents === obj2.bitStringContents); - } - - return equal; -}; - -/** - * Gets the length of a BER-encoded ASN.1 value. - * - * In case the length is not specified, undefined is returned. - * - * @param b the BER-encoded ASN.1 byte buffer, starting with the first - * length byte. - * - * @return the length of the BER-encoded ASN.1 value or undefined. - */ -asn1$8.getBerValueLength = function(b) { - // TODO: move this function and related DER/BER functions to a der.js - // file; better abstract ASN.1 away from der/ber. - var b2 = b.getByte(); - if(b2 === 0x80) { - return undefined; - } - - // see if the length is "short form" or "long form" (bit 8 set) - var length; - var longForm = b2 & 0x80; - if(!longForm) { - // length is just the first byte - length = b2; - } else { - // the number of bytes the length is specified in bits 7 through 1 - // and each length byte is in big-endian base-256 - length = b.getInt((b2 & 0x7F) << 3); - } - return length; -}; - -/** - * Check if the byte buffer has enough bytes. Throws an Error if not. - * - * @param bytes the byte buffer to parse from. - * @param remaining the bytes remaining in the current parsing state. - * @param n the number of bytes the buffer must have. - */ -function _checkBufferLength(bytes, remaining, n) { - if(n > remaining) { - var error = new Error('Too few bytes to parse DER.'); - error.available = bytes.length(); - error.remaining = remaining; - error.requested = n; - throw error; - } -} - -/** - * Gets the length of a BER-encoded ASN.1 value. - * - * In case the length is not specified, undefined is returned. - * - * @param bytes the byte buffer to parse from. - * @param remaining the bytes remaining in the current parsing state. - * - * @return the length of the BER-encoded ASN.1 value or undefined. - */ -var _getValueLength = function(bytes, remaining) { - // TODO: move this function and related DER/BER functions to a der.js - // file; better abstract ASN.1 away from der/ber. - // fromDer already checked that this byte exists - var b2 = bytes.getByte(); - remaining--; - if(b2 === 0x80) { - return undefined; - } - - // see if the length is "short form" or "long form" (bit 8 set) - var length; - var longForm = b2 & 0x80; - if(!longForm) { - // length is just the first byte - length = b2; - } else { - // the number of bytes the length is specified in bits 7 through 1 - // and each length byte is in big-endian base-256 - var longFormBytes = b2 & 0x7F; - _checkBufferLength(bytes, remaining, longFormBytes); - length = bytes.getInt(longFormBytes << 3); - } - // FIXME: this will only happen for 32 bit getInt with high bit set - if(length < 0) { - throw new Error('Negative length: ' + length); - } - return length; -}; - -/** - * Parses an asn1 object from a byte buffer in DER format. - * - * @param bytes the byte buffer to parse from. - * @param [strict] true to be strict when checking value lengths, false to - * allow truncated values (default: true). - * @param [options] object with options or boolean strict flag - * [strict] true to be strict when checking value lengths, false to - * allow truncated values (default: true). - * [decodeBitStrings] true to attempt to decode the content of - * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that - * without schema support to understand the data context this can - * erroneously decode values that happen to be valid ASN.1. This - * flag will be deprecated or removed as soon as schema support is - * available. (default: true) - * - * @return the parsed asn1 object. - */ -asn1$8.fromDer = function(bytes, options) { - if(options === undefined) { - options = { - strict: true, - decodeBitStrings: true - }; - } - if(typeof options === 'boolean') { - options = { - strict: options, - decodeBitStrings: true - }; - } - if(!('strict' in options)) { - options.strict = true; - } - if(!('decodeBitStrings' in options)) { - options.decodeBitStrings = true; - } - - // wrap in buffer if needed - if(typeof bytes === 'string') { - bytes = forge$z.util.createBuffer(bytes); - } - - return _fromDer(bytes, bytes.length(), 0, options); -}; - -/** - * Internal function to parse an asn1 object from a byte buffer in DER format. - * - * @param bytes the byte buffer to parse from. - * @param remaining the number of bytes remaining for this chunk. - * @param depth the current parsing depth. - * @param options object with same options as fromDer(). - * - * @return the parsed asn1 object. - */ -function _fromDer(bytes, remaining, depth, options) { - // temporary storage for consumption calculations - var start; - - // minimum length for ASN.1 DER structure is 2 - _checkBufferLength(bytes, remaining, 2); - - // get the first byte - var b1 = bytes.getByte(); - // consumed one byte - remaining--; - - // get the tag class - var tagClass = (b1 & 0xC0); - - // get the type (bits 1-5) - var type = b1 & 0x1F; - - // get the variable value length and adjust remaining bytes - start = bytes.length(); - var length = _getValueLength(bytes, remaining); - remaining -= start - bytes.length(); - - // ensure there are enough bytes to get the value - if(length !== undefined && length > remaining) { - if(options.strict) { - var error = new Error('Too few bytes to read ASN.1 value.'); - error.available = bytes.length(); - error.remaining = remaining; - error.requested = length; - throw error; - } - // Note: be lenient with truncated values and use remaining state bytes - length = remaining; - } - - // value storage - var value; - // possible BIT STRING contents storage - var bitStringContents; - - // constructed flag is bit 6 (32 = 0x20) of the first byte - var constructed = ((b1 & 0x20) === 0x20); - if(constructed) { - // parse child asn1 objects from the value - value = []; - if(length === undefined) { - // asn1 object of indefinite length, read until end tag - for(;;) { - _checkBufferLength(bytes, remaining, 2); - if(bytes.bytes(2) === String.fromCharCode(0, 0)) { - bytes.getBytes(2); - remaining -= 2; - break; - } - start = bytes.length(); - value.push(_fromDer(bytes, remaining, depth + 1, options)); - remaining -= start - bytes.length(); - } - } else { - // parsing asn1 object of definite length - while(length > 0) { - start = bytes.length(); - value.push(_fromDer(bytes, length, depth + 1, options)); - remaining -= start - bytes.length(); - length -= start - bytes.length(); - } - } - } - - // if a BIT STRING, save the contents including padding - if(value === undefined && tagClass === asn1$8.Class.UNIVERSAL && - type === asn1$8.Type.BITSTRING) { - bitStringContents = bytes.bytes(length); - } - - // determine if a non-constructed value should be decoded as a composed - // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs) - // can be used this way. - if(value === undefined && options.decodeBitStrings && - tagClass === asn1$8.Class.UNIVERSAL && - // FIXME: OCTET STRINGs not yet supported here - // .. other parts of forge expect to decode OCTET STRINGs manually - (type === asn1$8.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) && - length > 1) { - // save read position - var savedRead = bytes.read; - var savedRemaining = remaining; - var unused = 0; - if(type === asn1$8.Type.BITSTRING) { - /* The first octet gives the number of bits by which the length of the - bit string is less than the next multiple of eight (this is called - the "number of unused bits"). - - The second and following octets give the value of the bit string - converted to an octet string. */ - _checkBufferLength(bytes, remaining, 1); - unused = bytes.getByte(); - remaining--; - } - // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs - if(unused === 0) { - try { - // attempt to parse child asn1 object from the value - // (stored in array to signal composed value) - start = bytes.length(); - var subOptions = { - // enforce strict mode to avoid parsing ASN.1 from plain data - verbose: options.verbose, - strict: true, - decodeBitStrings: true - }; - var composed = _fromDer(bytes, remaining, depth + 1, subOptions); - var used = start - bytes.length(); - remaining -= used; - if(type == asn1$8.Type.BITSTRING) { - used++; - } - - // if the data all decoded and the class indicates UNIVERSAL or - // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object - var tc = composed.tagClass; - if(used === length && - (tc === asn1$8.Class.UNIVERSAL || tc === asn1$8.Class.CONTEXT_SPECIFIC)) { - value = [composed]; - } - } catch(ex) { - } - } - if(value === undefined) { - // restore read position - bytes.read = savedRead; - remaining = savedRemaining; - } - } - - if(value === undefined) { - // asn1 not constructed or composed, get raw value - // TODO: do DER to OID conversion and vice-versa in .toDer? - - if(length === undefined) { - if(options.strict) { - throw new Error('Non-constructed ASN.1 object of indefinite length.'); - } - // be lenient and use remaining state bytes - length = remaining; - } - - if(type === asn1$8.Type.BMPSTRING) { - value = ''; - for(; length > 0; length -= 2) { - _checkBufferLength(bytes, remaining, 2); - value += String.fromCharCode(bytes.getInt16()); - remaining -= 2; - } - } else { - value = bytes.getBytes(length); - } - } - - // add BIT STRING contents if available - var asn1Options = bitStringContents === undefined ? null : { - bitStringContents: bitStringContents - }; - - // create and return asn1 object - return asn1$8.create(tagClass, type, constructed, value, asn1Options); -} - -/** - * Converts the given asn1 object to a buffer of bytes in DER format. - * - * @param asn1 the asn1 object to convert to bytes. - * - * @return the buffer of bytes. - */ -asn1$8.toDer = function(obj) { - var bytes = forge$z.util.createBuffer(); - - // build the first byte - var b1 = obj.tagClass | obj.type; - - // for storing the ASN.1 value - var value = forge$z.util.createBuffer(); - - // use BIT STRING contents if available and data not changed - var useBitStringContents = false; - if('bitStringContents' in obj) { - useBitStringContents = true; - if(obj.original) { - useBitStringContents = asn1$8.equals(obj, obj.original); - } - } - - if(useBitStringContents) { - value.putBytes(obj.bitStringContents); - } else if(obj.composed) { - // if composed, use each child asn1 object's DER bytes as value - // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed - // from other asn1 objects - if(obj.constructed) { - b1 |= 0x20; - } else { - // type is a bit string, add unused bits of 0x00 - value.putByte(0x00); - } - - // add all of the child DER bytes together - for(var i = 0; i < obj.value.length; ++i) { - if(obj.value[i] !== undefined) { - value.putBuffer(asn1$8.toDer(obj.value[i])); - } - } - } else { - // use asn1.value directly - if(obj.type === asn1$8.Type.BMPSTRING) { - for(var i = 0; i < obj.value.length; ++i) { - value.putInt16(obj.value.charCodeAt(i)); - } - } else { - // ensure integer is minimally-encoded - // TODO: should all leading bytes be stripped vs just one? - // .. ex '00 00 01' => '01'? - if(obj.type === asn1$8.Type.INTEGER && - obj.value.length > 1 && - // leading 0x00 for positive integer - ((obj.value.charCodeAt(0) === 0 && - (obj.value.charCodeAt(1) & 0x80) === 0) || - // leading 0xFF for negative integer - (obj.value.charCodeAt(0) === 0xFF && - (obj.value.charCodeAt(1) & 0x80) === 0x80))) { - value.putBytes(obj.value.substr(1)); - } else { - value.putBytes(obj.value); - } - } - } - - // add tag byte - bytes.putByte(b1); - - // use "short form" encoding - if(value.length() <= 127) { - // one byte describes the length - // bit 8 = 0 and bits 7-1 = length - bytes.putByte(value.length() & 0x7F); - } else { - // use "long form" encoding - // 2 to 127 bytes describe the length - // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes - // other bytes: length in base 256, big-endian - var len = value.length(); - var lenBytes = ''; - do { - lenBytes += String.fromCharCode(len & 0xFF); - len = len >>> 8; - } while(len > 0); - - // set first byte to # bytes used to store the length and turn on - // bit 8 to indicate long-form length is used - bytes.putByte(lenBytes.length | 0x80); - - // concatenate length bytes in reverse since they were generated - // little endian and we need big endian - for(var i = lenBytes.length - 1; i >= 0; --i) { - bytes.putByte(lenBytes.charCodeAt(i)); - } - } - - // concatenate value bytes - bytes.putBuffer(value); - return bytes; -}; - -/** - * Converts an OID dot-separated string to a byte buffer. The byte buffer - * contains only the DER-encoded value, not any tag or length bytes. - * - * @param oid the OID dot-separated string. - * - * @return the byte buffer. - */ -asn1$8.oidToDer = function(oid) { - // split OID into individual values - var values = oid.split('.'); - var bytes = forge$z.util.createBuffer(); - - // first byte is 40 * value1 + value2 - bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); - // other bytes are each value in base 128 with 8th bit set except for - // the last byte for each value - var last, valueBytes, value, b; - for(var i = 2; i < values.length; ++i) { - // produce value bytes in reverse because we don't know how many - // bytes it will take to store the value - last = true; - valueBytes = []; - value = parseInt(values[i], 10); - do { - b = value & 0x7F; - value = value >>> 7; - // if value is not last, then turn on 8th bit - if(!last) { - b |= 0x80; - } - valueBytes.push(b); - last = false; - } while(value > 0); - - // add value bytes in reverse (needs to be in big endian) - for(var n = valueBytes.length - 1; n >= 0; --n) { - bytes.putByte(valueBytes[n]); - } - } - - return bytes; -}; - -/** - * Converts a DER-encoded byte buffer to an OID dot-separated string. The - * byte buffer should contain only the DER-encoded value, not any tag or - * length bytes. - * - * @param bytes the byte buffer. - * - * @return the OID dot-separated string. - */ -asn1$8.derToOid = function(bytes) { - var oid; - - // wrap in buffer if needed - if(typeof bytes === 'string') { - bytes = forge$z.util.createBuffer(bytes); - } - - // first byte is 40 * value1 + value2 - var b = bytes.getByte(); - oid = Math.floor(b / 40) + '.' + (b % 40); - - // other bytes are each value in base 128 with 8th bit set except for - // the last byte for each value - var value = 0; - while(bytes.length() > 0) { - b = bytes.getByte(); - value = value << 7; - // not the last byte for the value - if(b & 0x80) { - value += b & 0x7F; - } else { - // last byte - oid += '.' + (value + b); - value = 0; - } - } - - return oid; -}; - -/** - * Converts a UTCTime value to a date. - * - * Note: GeneralizedTime has 4 digits for the year and is used for X.509 - * dates past 2049. Parsing that structure hasn't been implemented yet. - * - * @param utc the UTCTime value to convert. - * - * @return the date. - */ -asn1$8.utcTimeToDate = function(utc) { - /* The following formats can be used: - - YYMMDDhhmmZ - YYMMDDhhmm+hh'mm' - YYMMDDhhmm-hh'mm' - YYMMDDhhmmssZ - YYMMDDhhmmss+hh'mm' - YYMMDDhhmmss-hh'mm' - - Where: - - YY is the least significant two digits of the year - MM is the month (01 to 12) - DD is the day (01 to 31) - hh is the hour (00 to 23) - mm are the minutes (00 to 59) - ss are the seconds (00 to 59) - Z indicates that local time is GMT, + indicates that local time is - later than GMT, and - indicates that local time is earlier than GMT - hh' is the absolute value of the offset from GMT in hours - mm' is the absolute value of the offset from GMT in minutes */ - var date = new Date(); - - // if YY >= 50 use 19xx, if YY < 50 use 20xx - var year = parseInt(utc.substr(0, 2), 10); - year = (year >= 50) ? 1900 + year : 2000 + year; - var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month - var DD = parseInt(utc.substr(4, 2), 10); - var hh = parseInt(utc.substr(6, 2), 10); - var mm = parseInt(utc.substr(8, 2), 10); - var ss = 0; - - // not just YYMMDDhhmmZ - if(utc.length > 11) { - // get character after minutes - var c = utc.charAt(10); - var end = 10; - - // see if seconds are present - if(c !== '+' && c !== '-') { - // get seconds - ss = parseInt(utc.substr(10, 2), 10); - end += 2; - } - } - - // update date - date.setUTCFullYear(year, MM, DD); - date.setUTCHours(hh, mm, ss, 0); - - if(end) { - // get +/- after end of time - c = utc.charAt(end); - if(c === '+' || c === '-') { - // get hours+minutes offset - var hhoffset = parseInt(utc.substr(end + 1, 2), 10); - var mmoffset = parseInt(utc.substr(end + 4, 2), 10); - - // calculate offset in milliseconds - var offset = hhoffset * 60 + mmoffset; - offset *= 60000; - - // apply offset - if(c === '+') { - date.setTime(+date - offset); - } else { - date.setTime(+date + offset); - } - } - } - - return date; -}; - -/** - * Converts a GeneralizedTime value to a date. - * - * @param gentime the GeneralizedTime value to convert. - * - * @return the date. - */ -asn1$8.generalizedTimeToDate = function(gentime) { - /* The following formats can be used: - - YYYYMMDDHHMMSS - YYYYMMDDHHMMSS.fff - YYYYMMDDHHMMSSZ - YYYYMMDDHHMMSS.fffZ - YYYYMMDDHHMMSS+hh'mm' - YYYYMMDDHHMMSS.fff+hh'mm' - YYYYMMDDHHMMSS-hh'mm' - YYYYMMDDHHMMSS.fff-hh'mm' - - Where: - - YYYY is the year - MM is the month (01 to 12) - DD is the day (01 to 31) - hh is the hour (00 to 23) - mm are the minutes (00 to 59) - ss are the seconds (00 to 59) - .fff is the second fraction, accurate to three decimal places - Z indicates that local time is GMT, + indicates that local time is - later than GMT, and - indicates that local time is earlier than GMT - hh' is the absolute value of the offset from GMT in hours - mm' is the absolute value of the offset from GMT in minutes */ - var date = new Date(); - - var YYYY = parseInt(gentime.substr(0, 4), 10); - var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month - var DD = parseInt(gentime.substr(6, 2), 10); - var hh = parseInt(gentime.substr(8, 2), 10); - var mm = parseInt(gentime.substr(10, 2), 10); - var ss = parseInt(gentime.substr(12, 2), 10); - var fff = 0; - var offset = 0; - var isUTC = false; - - if(gentime.charAt(gentime.length - 1) === 'Z') { - isUTC = true; - } - - var end = gentime.length - 5, c = gentime.charAt(end); - if(c === '+' || c === '-') { - // get hours+minutes offset - var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); - var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); - - // calculate offset in milliseconds - offset = hhoffset * 60 + mmoffset; - offset *= 60000; - - // apply offset - if(c === '+') { - offset *= -1; - } - - isUTC = true; - } - - // check for second fraction - if(gentime.charAt(14) === '.') { - fff = parseFloat(gentime.substr(14), 10) * 1000; - } - - if(isUTC) { - date.setUTCFullYear(YYYY, MM, DD); - date.setUTCHours(hh, mm, ss, fff); - - // apply offset - date.setTime(+date + offset); - } else { - date.setFullYear(YYYY, MM, DD); - date.setHours(hh, mm, ss, fff); - } - - return date; -}; - -/** - * Converts a date to a UTCTime value. - * - * Note: GeneralizedTime has 4 digits for the year and is used for X.509 - * dates past 2049. Converting to a GeneralizedTime hasn't been - * implemented yet. - * - * @param date the date to convert. - * - * @return the UTCTime value. - */ -asn1$8.dateToUtcTime = function(date) { - // TODO: validate; currently assumes proper format - if(typeof date === 'string') { - return date; - } - - var rval = ''; - - // create format YYMMDDhhmmssZ - var format = []; - format.push(('' + date.getUTCFullYear()).substr(2)); - format.push('' + (date.getUTCMonth() + 1)); - format.push('' + date.getUTCDate()); - format.push('' + date.getUTCHours()); - format.push('' + date.getUTCMinutes()); - format.push('' + date.getUTCSeconds()); - - // ensure 2 digits are used for each format entry - for(var i = 0; i < format.length; ++i) { - if(format[i].length < 2) { - rval += '0'; - } - rval += format[i]; - } - rval += 'Z'; - - return rval; -}; - -/** - * Converts a date to a GeneralizedTime value. - * - * @param date the date to convert. - * - * @return the GeneralizedTime value as a string. - */ -asn1$8.dateToGeneralizedTime = function(date) { - // TODO: validate; currently assumes proper format - if(typeof date === 'string') { - return date; - } - - var rval = ''; - - // create format YYYYMMDDHHMMSSZ - var format = []; - format.push('' + date.getUTCFullYear()); - format.push('' + (date.getUTCMonth() + 1)); - format.push('' + date.getUTCDate()); - format.push('' + date.getUTCHours()); - format.push('' + date.getUTCMinutes()); - format.push('' + date.getUTCSeconds()); - - // ensure 2 digits are used for each format entry - for(var i = 0; i < format.length; ++i) { - if(format[i].length < 2) { - rval += '0'; - } - rval += format[i]; - } - rval += 'Z'; - - return rval; -}; - -/** - * Converts a javascript integer to a DER-encoded byte buffer to be used - * as the value for an INTEGER type. - * - * @param x the integer. - * - * @return the byte buffer. - */ -asn1$8.integerToDer = function(x) { - var rval = forge$z.util.createBuffer(); - if(x >= -0x80 && x < 0x80) { - return rval.putSignedInt(x, 8); - } - if(x >= -0x8000 && x < 0x8000) { - return rval.putSignedInt(x, 16); - } - if(x >= -0x800000 && x < 0x800000) { - return rval.putSignedInt(x, 24); - } - if(x >= -0x80000000 && x < 0x80000000) { - return rval.putSignedInt(x, 32); - } - var error = new Error('Integer too large; max is 32-bits.'); - error.integer = x; - throw error; -}; - -/** - * Converts a DER-encoded byte buffer to a javascript integer. This is - * typically used to decode the value of an INTEGER type. - * - * @param bytes the byte buffer. - * - * @return the integer. - */ -asn1$8.derToInteger = function(bytes) { - // wrap in buffer if needed - if(typeof bytes === 'string') { - bytes = forge$z.util.createBuffer(bytes); - } - - var n = bytes.length() * 8; - if(n > 32) { - throw new Error('Integer too large; max is 32-bits.'); - } - return bytes.getSignedInt(n); -}; - -/** - * Validates that the given ASN.1 object is at least a super set of the - * given ASN.1 structure. Only tag classes and types are checked. An - * optional map may also be provided to capture ASN.1 values while the - * structure is checked. - * - * To capture an ASN.1 value, set an object in the validator's 'capture' - * parameter to the key to use in the capture map. To capture the full - * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including - * the leading unused bits counter byte, specify 'captureBitStringContents'. - * To capture BIT STRING bytes, without the leading unused bits counter byte, - * specify 'captureBitStringValue'. - * - * Objects in the validator may set a field 'optional' to true to indicate - * that it isn't necessary to pass validation. - * - * @param obj the ASN.1 object to validate. - * @param v the ASN.1 structure validator. - * @param capture an optional map to capture values in. - * @param errors an optional array for storing validation errors. - * - * @return true on success, false on failure. - */ -asn1$8.validate = function(obj, v, capture, errors) { - var rval = false; - - // ensure tag class and type are the same if specified - if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') && - (obj.type === v.type || typeof(v.type) === 'undefined')) { - // ensure constructed flag is the same if specified - if(obj.constructed === v.constructed || - typeof(v.constructed) === 'undefined') { - rval = true; - - // handle sub values - if(v.value && forge$z.util.isArray(v.value)) { - var j = 0; - for(var i = 0; rval && i < v.value.length; ++i) { - rval = v.value[i].optional || false; - if(obj.value[j]) { - rval = asn1$8.validate(obj.value[j], v.value[i], capture, errors); - if(rval) { - ++j; - } else if(v.value[i].optional) { - rval = true; - } - } - if(!rval && errors) { - errors.push( - '[' + v.name + '] ' + - 'Tag class "' + v.tagClass + '", type "' + - v.type + '" expected value length "' + - v.value.length + '", got "' + - obj.value.length + '"'); - } - } - } - - if(rval && capture) { - if(v.capture) { - capture[v.capture] = obj.value; - } - if(v.captureAsn1) { - capture[v.captureAsn1] = obj; - } - if(v.captureBitStringContents && 'bitStringContents' in obj) { - capture[v.captureBitStringContents] = obj.bitStringContents; - } - if(v.captureBitStringValue && 'bitStringContents' in obj) { - if(obj.bitStringContents.length < 2) { - capture[v.captureBitStringValue] = ''; - } else { - // FIXME: support unused bits with data shifting - var unused = obj.bitStringContents.charCodeAt(0); - if(unused !== 0) { - throw new Error( - 'captureBitStringValue only supported for zero unused bits'); - } - capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); - } - } - } - } else if(errors) { - errors.push( - '[' + v.name + '] ' + - 'Expected constructed "' + v.constructed + '", got "' + - obj.constructed + '"'); - } - } else if(errors) { - if(obj.tagClass !== v.tagClass) { - errors.push( - '[' + v.name + '] ' + - 'Expected tag class "' + v.tagClass + '", got "' + - obj.tagClass + '"'); - } - if(obj.type !== v.type) { - errors.push( - '[' + v.name + '] ' + - 'Expected type "' + v.type + '", got "' + obj.type + '"'); - } - } - return rval; -}; - -// regex for testing for non-latin characters -var _nonLatinRegex = /[^\\u0000-\\u00ff]/; - -/** - * Pretty prints an ASN.1 object to a string. - * - * @param obj the object to write out. - * @param level the level in the tree. - * @param indentation the indentation to use. - * - * @return the string. - */ -asn1$8.prettyPrint = function(obj, level, indentation) { - var rval = ''; - - // set default level and indentation - level = level || 0; - indentation = indentation || 2; - - // start new line for deep levels - if(level > 0) { - rval += '\n'; - } - - // create indent - var indent = ''; - for(var i = 0; i < level * indentation; ++i) { - indent += ' '; - } - - // print class:type - rval += indent + 'Tag: '; - switch(obj.tagClass) { - case asn1$8.Class.UNIVERSAL: - rval += 'Universal:'; - break; - case asn1$8.Class.APPLICATION: - rval += 'Application:'; - break; - case asn1$8.Class.CONTEXT_SPECIFIC: - rval += 'Context-Specific:'; - break; - case asn1$8.Class.PRIVATE: - rval += 'Private:'; - break; - } - - if(obj.tagClass === asn1$8.Class.UNIVERSAL) { - rval += obj.type; - - // known types - switch(obj.type) { - case asn1$8.Type.NONE: - rval += ' (None)'; - break; - case asn1$8.Type.BOOLEAN: - rval += ' (Boolean)'; - break; - case asn1$8.Type.INTEGER: - rval += ' (Integer)'; - break; - case asn1$8.Type.BITSTRING: - rval += ' (Bit string)'; - break; - case asn1$8.Type.OCTETSTRING: - rval += ' (Octet string)'; - break; - case asn1$8.Type.NULL: - rval += ' (Null)'; - break; - case asn1$8.Type.OID: - rval += ' (Object Identifier)'; - break; - case asn1$8.Type.ODESC: - rval += ' (Object Descriptor)'; - break; - case asn1$8.Type.EXTERNAL: - rval += ' (External or Instance of)'; - break; - case asn1$8.Type.REAL: - rval += ' (Real)'; - break; - case asn1$8.Type.ENUMERATED: - rval += ' (Enumerated)'; - break; - case asn1$8.Type.EMBEDDED: - rval += ' (Embedded PDV)'; - break; - case asn1$8.Type.UTF8: - rval += ' (UTF8)'; - break; - case asn1$8.Type.ROID: - rval += ' (Relative Object Identifier)'; - break; - case asn1$8.Type.SEQUENCE: - rval += ' (Sequence)'; - break; - case asn1$8.Type.SET: - rval += ' (Set)'; - break; - case asn1$8.Type.PRINTABLESTRING: - rval += ' (Printable String)'; - break; - case asn1$8.Type.IA5String: - rval += ' (IA5String (ASCII))'; - break; - case asn1$8.Type.UTCTIME: - rval += ' (UTC time)'; - break; - case asn1$8.Type.GENERALIZEDTIME: - rval += ' (Generalized time)'; - break; - case asn1$8.Type.BMPSTRING: - rval += ' (BMP String)'; - break; - } - } else { - rval += obj.type; - } - - rval += '\n'; - rval += indent + 'Constructed: ' + obj.constructed + '\n'; - - if(obj.composed) { - var subvalues = 0; - var sub = ''; - for(var i = 0; i < obj.value.length; ++i) { - if(obj.value[i] !== undefined) { - subvalues += 1; - sub += asn1$8.prettyPrint(obj.value[i], level + 1, indentation); - if((i + 1) < obj.value.length) { - sub += ','; - } - } - } - rval += indent + 'Sub values: ' + subvalues + sub; - } else { - rval += indent + 'Value: '; - if(obj.type === asn1$8.Type.OID) { - var oid = asn1$8.derToOid(obj.value); - rval += oid; - if(forge$z.pki && forge$z.pki.oids) { - if(oid in forge$z.pki.oids) { - rval += ' (' + forge$z.pki.oids[oid] + ') '; - } - } - } - if(obj.type === asn1$8.Type.INTEGER) { - try { - rval += asn1$8.derToInteger(obj.value); - } catch(ex) { - rval += '0x' + forge$z.util.bytesToHex(obj.value); - } - } else if(obj.type === asn1$8.Type.BITSTRING) { - // TODO: shift bits as needed to display without padding - if(obj.value.length > 1) { - // remove unused bits field - rval += '0x' + forge$z.util.bytesToHex(obj.value.slice(1)); - } else { - rval += '(none)'; - } - // show unused bit count - if(obj.value.length > 0) { - var unused = obj.value.charCodeAt(0); - if(unused == 1) { - rval += ' (1 unused bit shown)'; - } else if(unused > 1) { - rval += ' (' + unused + ' unused bits shown)'; - } - } - } else if(obj.type === asn1$8.Type.OCTETSTRING) { - if(!_nonLatinRegex.test(obj.value)) { - rval += '(' + obj.value + ') '; - } - rval += '0x' + forge$z.util.bytesToHex(obj.value); - } else if(obj.type === asn1$8.Type.UTF8) { - rval += forge$z.util.decodeUtf8(obj.value); - } else if(obj.type === asn1$8.Type.PRINTABLESTRING || - obj.type === asn1$8.Type.IA5String) { - rval += obj.value; - } else if(_nonLatinRegex.test(obj.value)) { - rval += '0x' + forge$z.util.bytesToHex(obj.value); - } else if(obj.value.length === 0) { - rval += '[null]'; - } else { - rval += obj.value; - } - } - - return rval; -}; - -/** - * Node.js module for Forge message digests. - * - * @author Dave Longley - * - * Copyright 2011-2017 Digital Bazaar, Inc. - */ - -var forge$y = forge$F; - -forge$y.md = forge$y.md || {}; -forge$y.md.algorithms = forge$y.md.algorithms || {}; - -/** - * Hash-based Message Authentication Code implementation. Requires a message - * digest object that can be obtained, for example, from forge.md.sha1 or - * forge.md.md5. - * - * @author Dave Longley - * - * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved. - */ - -var forge$x = forge$F; - - - -/* HMAC API */ -var hmac = forge$x.hmac = forge$x.hmac || {}; - -/** - * Creates an HMAC object that uses the given message digest object. - * - * @return an HMAC object. - */ -hmac.create = function() { - // the hmac key to use - var _key = null; - - // the message digest to use - var _md = null; - - // the inner padding - var _ipadding = null; - - // the outer padding - var _opadding = null; - - // hmac context - var ctx = {}; - - /** - * Starts or restarts the HMAC with the given key and message digest. - * - * @param md the message digest to use, null to reuse the previous one, - * a string to use builtin 'sha1', 'md5', 'sha256'. - * @param key the key to use as a string, array of bytes, byte buffer, - * or null to reuse the previous key. - */ - ctx.start = function(md, key) { - if(md !== null) { - if(typeof md === 'string') { - // create builtin message digest - md = md.toLowerCase(); - if(md in forge$x.md.algorithms) { - _md = forge$x.md.algorithms[md].create(); - } else { - throw new Error('Unknown hash algorithm "' + md + '"'); - } - } else { - // store message digest - _md = md; - } - } - - if(key === null) { - // reuse previous key - key = _key; - } else { - if(typeof key === 'string') { - // convert string into byte buffer - key = forge$x.util.createBuffer(key); - } else if(forge$x.util.isArray(key)) { - // convert byte array into byte buffer - var tmp = key; - key = forge$x.util.createBuffer(); - for(var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - - // if key is longer than blocksize, hash it - var keylen = key.length(); - if(keylen > _md.blockLength) { - _md.start(); - _md.update(key.bytes()); - key = _md.digest(); - } - - // mix key into inner and outer padding - // ipadding = [0x36 * blocksize] ^ key - // opadding = [0x5C * blocksize] ^ key - _ipadding = forge$x.util.createBuffer(); - _opadding = forge$x.util.createBuffer(); - keylen = key.length(); - for(var i = 0; i < keylen; ++i) { - var tmp = key.at(i); - _ipadding.putByte(0x36 ^ tmp); - _opadding.putByte(0x5C ^ tmp); - } - - // if key is shorter than blocksize, add additional padding - if(keylen < _md.blockLength) { - var tmp = _md.blockLength - keylen; - for(var i = 0; i < tmp; ++i) { - _ipadding.putByte(0x36); - _opadding.putByte(0x5C); - } - } - _key = key; - _ipadding = _ipadding.bytes(); - _opadding = _opadding.bytes(); - } - - // digest is done like so: hash(opadding | hash(ipadding | message)) - - // prepare to do inner hash - // hash(ipadding | message) - _md.start(); - _md.update(_ipadding); - }; - - /** - * Updates the HMAC with the given message bytes. - * - * @param bytes the bytes to update with. - */ - ctx.update = function(bytes) { - _md.update(bytes); - }; - - /** - * Produces the Message Authentication Code (MAC). - * - * @return a byte buffer containing the digest value. - */ - ctx.getMac = function() { - // digest is done like so: hash(opadding | hash(ipadding | message)) - // here we do the outer hashing - var inner = _md.digest().bytes(); - _md.start(); - _md.update(_opadding); - _md.update(inner); - return _md.digest(); - }; - // alias for getMac - ctx.digest = ctx.getMac; - - return ctx; -}; - -/** - * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ - -var forge$w = forge$F; - - - -var md5 = forge$w.md5 = forge$w.md5 || {}; -forge$w.md.md5 = forge$w.md.algorithms.md5 = md5; - -/** - * Creates an MD5 message digest object. - * - * @return a message digest object. - */ -md5.create = function() { - // do initialization as necessary - if(!_initialized$3) { - _init$3(); - } - - // MD5 state contains four 32-bit integers - var _state = null; - - // input buffer - var _input = forge$w.util.createBuffer(); - - // used for word storage - var _w = new Array(16); - - // message digest object - var md = { - algorithm: 'md5', - blockLength: 64, - digestLength: 16, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - - /** - * Starts the digest. - * - * @return this digest object. - */ - md.start = function() { - // up to 56-bit message length for convenience - md.messageLength = 0; - - // full message length (set md.messageLength64 for backwards-compatibility) - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for(var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge$w.util.createBuffer(); - _state = { - h0: 0x67452301, - h1: 0xEFCDAB89, - h2: 0x98BADCFE, - h3: 0x10325476 - }; - return md; - }; - // start digest automatically for first time - md.start(); - - /** - * Updates the digest with the given message input. The given input can - * treated as raw input (no encoding will be applied) or an encoding of - * 'utf8' maybe given to encode the input using UTF-8. - * - * @param msg the message input to update with. - * @param encoding the encoding to use (default: 'raw', other: 'utf8'). - * - * @return this digest object. - */ - md.update = function(msg, encoding) { - if(encoding === 'utf8') { - msg = forge$w.util.encodeUtf8(msg); - } - - // update message length - var len = msg.length; - md.messageLength += len; - len = [(len / 0x100000000) >>> 0, len >>> 0]; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = (len[1] / 0x100000000) >>> 0; - } - - // add bytes to input buffer - _input.putBytes(msg); - - // process bytes - _update$3(_state, _w, _input); - - // compact input buffer every 2K or if empty - if(_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - - return md; - }; - - /** - * Produces the digest. - * - * @return a byte buffer containing the digest value. - */ - md.digest = function() { - /* Note: Here we copy the remaining bytes in the input buffer and - add the appropriate MD5 padding. Then we do the final update - on a copy of the state so that if the user wants to get - intermediate digests they can do so. */ - - /* Determine the number of bytes that must be added to the message - to ensure its length is congruent to 448 mod 512. In other words, - the data to be digested must be a multiple of 512 bits (or 128 bytes). - This data includes the message, some padding, and the length of the - message. Since the length of the message will be encoded as 8 bytes (64 - bits), that means that the last segment of the data must have 56 bytes - (448 bits) of message and padding. Therefore, the length of the message - plus the padding must be congruent to 448 mod 512 because - 512 - 128 = 448. - - In order to fill up the message length it must be filled with - padding that begins with 1 bit followed by all 0 bits. Padding - must *always* be present, so if the message length is already - congruent to 448 mod 512, then 512 padding bits must be added. */ - - var finalBlock = forge$w.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - - // compute remaining size to be digested (include message length size) - var remaining = ( - md.fullMessageLength[md.fullMessageLength.length - 1] + - md.messageLengthSize); - - // add padding for overflow blockSize - overflow - // _padding starts with 1 byte with first bit is set (byte value 128), then - // there may be up to (blockSize - 1) other pad bytes - var overflow = remaining & (md.blockLength - 1); - finalBlock.putBytes(_padding$3.substr(0, md.blockLength - overflow)); - - // serialize message length in bits in little-endian order; since length - // is stored in bytes we multiply by 8 and add carry - var bits, carry = 0; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - bits = md.fullMessageLength[i] * 8 + carry; - carry = (bits / 0x100000000) >>> 0; - finalBlock.putInt32Le(bits >>> 0); - } - - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3 - }; - _update$3(s2, _w, finalBlock); - var rval = forge$w.util.createBuffer(); - rval.putInt32Le(s2.h0); - rval.putInt32Le(s2.h1); - rval.putInt32Le(s2.h2); - rval.putInt32Le(s2.h3); - return rval; - }; - - return md; -}; - -// padding, constant tables for calculating md5 -var _padding$3 = null; -var _g = null; -var _r = null; -var _k$2 = null; -var _initialized$3 = false; - -/** - * Initializes the constant tables. - */ -function _init$3() { - // create padding - _padding$3 = String.fromCharCode(128); - _padding$3 += forge$w.util.fillString(String.fromCharCode(0x00), 64); - - // g values - _g = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, - 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, - 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9]; - - // rounds table - _r = [ - 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, - 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, - 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, - 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]; - - // get the result of abs(sin(i + 1)) as a 32-bit integer - _k$2 = new Array(64); - for(var i = 0; i < 64; ++i) { - _k$2[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000); - } - - // now initialized - _initialized$3 = true; -} - -/** - * Updates an MD5 state with the given byte buffer. - * - * @param s the MD5 state to update. - * @param w the array to use to store words. - * @param bytes the byte buffer to update with. - */ -function _update$3(s, w, bytes) { - // consume 512 bit (64 byte) chunks - var t, a, b, c, d, f, r, i; - var len = bytes.length(); - while(len >= 64) { - // initialize hash value for this chunk - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - - // round 1 - for(i = 0; i < 16; ++i) { - w[i] = bytes.getInt32Le(); - f = d ^ (b & (c ^ d)); - t = (a + f + _k$2[i] + w[i]); - r = _r[i]; - a = d; - d = c; - c = b; - b += (t << r) | (t >>> (32 - r)); - } - // round 2 - for(; i < 32; ++i) { - f = c ^ (d & (b ^ c)); - t = (a + f + _k$2[i] + w[_g[i]]); - r = _r[i]; - a = d; - d = c; - c = b; - b += (t << r) | (t >>> (32 - r)); - } - // round 3 - for(; i < 48; ++i) { - f = b ^ c ^ d; - t = (a + f + _k$2[i] + w[_g[i]]); - r = _r[i]; - a = d; - d = c; - c = b; - b += (t << r) | (t >>> (32 - r)); - } - // round 4 - for(; i < 64; ++i) { - f = c ^ (b | ~d); - t = (a + f + _k$2[i] + w[_g[i]]); - r = _r[i]; - a = d; - d = c; - c = b; - b += (t << r) | (t >>> (32 - r)); - } - - // update hash state - s.h0 = (s.h0 + a) | 0; - s.h1 = (s.h1 + b) | 0; - s.h2 = (s.h2 + c) | 0; - s.h3 = (s.h3 + d) | 0; - - len -= 64; - } -} - -/** - * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms. - * - * See: RFC 1421. - * - * @author Dave Longley - * - * Copyright (c) 2013-2014 Digital Bazaar, Inc. - * - * A Forge PEM object has the following fields: - * - * type: identifies the type of message (eg: "RSA PRIVATE KEY"). - * - * procType: identifies the type of processing performed on the message, - * it has two subfields: version and type, eg: 4,ENCRYPTED. - * - * contentDomain: identifies the type of content in the message, typically - * only uses the value: "RFC822". - * - * dekInfo: identifies the message encryption algorithm and mode and includes - * any parameters for the algorithm, it has two subfields: algorithm and - * parameters, eg: DES-CBC,F8143EDE5960C597. - * - * headers: contains all other PEM encapsulated headers -- where order is - * significant (for pairing data like recipient ID + key info). - * - * body: the binary-encoded body. - */ - -var forge$v = forge$F; - - -// shortcut for pem API -var pem = forge$v.pem = forge$v.pem || {}; - -/** - * Encodes (serializes) the given PEM object. - * - * @param msg the PEM message object to encode. - * @param options the options to use: - * maxline the maximum characters per line for the body, (default: 64). - * - * @return the PEM-formatted string. - */ -pem.encode = function(msg, options) { - options = options || {}; - var rval = '-----BEGIN ' + msg.type + '-----\r\n'; - - // encode special headers - var header; - if(msg.procType) { - header = { - name: 'Proc-Type', - values: [String(msg.procType.version), msg.procType.type] - }; - rval += foldHeader(header); - } - if(msg.contentDomain) { - header = {name: 'Content-Domain', values: [msg.contentDomain]}; - rval += foldHeader(header); - } - if(msg.dekInfo) { - header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]}; - if(msg.dekInfo.parameters) { - header.values.push(msg.dekInfo.parameters); - } - rval += foldHeader(header); - } - - if(msg.headers) { - // encode all other headers - for(var i = 0; i < msg.headers.length; ++i) { - rval += foldHeader(msg.headers[i]); - } - } - - // terminate header - if(msg.procType) { - rval += '\r\n'; - } - - // add body - rval += forge$v.util.encode64(msg.body, options.maxline || 64) + '\r\n'; - - rval += '-----END ' + msg.type + '-----\r\n'; - return rval; -}; - -/** - * Decodes (deserializes) all PEM messages found in the given string. - * - * @param str the PEM-formatted string to decode. - * - * @return the PEM message objects in an array. - */ -pem.decode = function(str) { - var rval = []; - - // split string into PEM messages (be lenient w/EOF on BEGIN line) - var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; - var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; - var rCRLF = /\r?\n/; - var match; - while(true) { - match = rMessage.exec(str); - if(!match) { - break; - } - - var msg = { - type: match[1], - procType: null, - contentDomain: null, - dekInfo: null, - headers: [], - body: forge$v.util.decode64(match[3]) - }; - rval.push(msg); - - // no headers - if(!match[2]) { - continue; - } - - // parse headers - var lines = match[2].split(rCRLF); - var li = 0; - while(match && li < lines.length) { - // get line, trim any rhs whitespace - var line = lines[li].replace(/\s+$/, ''); - - // RFC2822 unfold any following folded lines - for(var nl = li + 1; nl < lines.length; ++nl) { - var next = lines[nl]; - if(!/\s/.test(next[0])) { - break; - } - line += next; - li = nl; - } - - // parse header - match = line.match(rHeader); - if(match) { - var header = {name: match[1], values: []}; - var values = match[2].split(','); - for(var vi = 0; vi < values.length; ++vi) { - header.values.push(ltrim(values[vi])); - } - - // Proc-Type must be the first header - if(!msg.procType) { - if(header.name !== 'Proc-Type') { - throw new Error('Invalid PEM formatted message. The first ' + - 'encapsulated header must be "Proc-Type".'); - } else if(header.values.length !== 2) { - throw new Error('Invalid PEM formatted message. The "Proc-Type" ' + - 'header must have two subfields.'); - } - msg.procType = {version: values[0], type: values[1]}; - } else if(!msg.contentDomain && header.name === 'Content-Domain') { - // special-case Content-Domain - msg.contentDomain = values[0] || ''; - } else if(!msg.dekInfo && header.name === 'DEK-Info') { - // special-case DEK-Info - if(header.values.length === 0) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + - 'header must have at least one subfield.'); - } - msg.dekInfo = {algorithm: values[0], parameters: values[1] || null}; - } else { - msg.headers.push(header); - } - } - - ++li; - } - - if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + - 'header must be present if "Proc-Type" is "ENCRYPTED".'); - } - } - - if(rval.length === 0) { - throw new Error('Invalid PEM formatted message.'); - } - - return rval; -}; - -function foldHeader(header) { - var rval = header.name + ': '; - - // ensure values with CRLF are folded - var values = []; - var insertSpace = function(match, $1) { - return ' ' + $1; - }; - for(var i = 0; i < header.values.length; ++i) { - values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); - } - rval += values.join(',') + '\r\n'; - - // do folding - var length = 0; - var candidate = -1; - for(var i = 0; i < rval.length; ++i, ++length) { - if(length > 65 && candidate !== -1) { - var insert = rval[candidate]; - if(insert === ',') { - ++candidate; - rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate); - } else { - rval = rval.substr(0, candidate) + - '\r\n' + insert + rval.substr(candidate + 1); - } - length = (i - candidate - 1); - candidate = -1; - ++i; - } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') { - candidate = i; - } - } - - return rval; -} - -function ltrim(str) { - return str.replace(/^\s+/, ''); -} - -/** - * DES (Data Encryption Standard) implementation. - * - * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode. - * It is based on the BSD-licensed implementation by Paul Tero: - * - * Paul Tero, July 2001 - * http://www.tero.co.uk/des/ - * - * Optimised for performance with large blocks by - * Michael Hayworth, November 2001 - * http://www.netdealing.com - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @author Stefan Siegl - * @author Dave Longley - * - * Copyright (c) 2012 Stefan Siegl - * Copyright (c) 2012-2014 Digital Bazaar, Inc. - */ - -var forge$u = forge$F; - - - - -/* DES API */ -forge$u.des = forge$u.des || {}; - -/** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('DES-', key); - * cipher.start({iv: iv}); - * - * Creates an DES cipher object to encrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as binary-encoded strings of bytes or - * byte buffers. - * - * @param key the symmetric key to use (64 or 192 bits). - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC' if IV is - * given, 'ECB' if null). - * - * @return the cipher. - */ -forge$u.des.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key: key, - output: output, - decrypt: false, - mode: mode || (iv === null ? 'ECB' : 'CBC') - }); - cipher.start(iv); - return cipher; -}; - -/** - * Deprecated. Instead, use: - * - * var cipher = forge.cipher.createCipher('DES-', key); - * - * Creates an DES cipher object to encrypt data using the given symmetric key. - * - * The key may be given as a binary-encoded string of bytes or a byte buffer. - * - * @param key the symmetric key to use (64 or 192 bits). - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge$u.des.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key: key, - output: null, - decrypt: false, - mode: mode - }); -}; - -/** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('DES-', key); - * decipher.start({iv: iv}); - * - * Creates an DES cipher object to decrypt data using the given symmetric key. - * The output will be stored in the 'output' member of the returned cipher. - * - * The key and iv may be given as binary-encoded strings of bytes or - * byte buffers. - * - * @param key the symmetric key to use (64 or 192 bits). - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * @param mode the cipher mode to use (default: 'CBC' if IV is - * given, 'ECB' if null). - * - * @return the cipher. - */ -forge$u.des.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key: key, - output: output, - decrypt: true, - mode: mode || (iv === null ? 'ECB' : 'CBC') - }); - cipher.start(iv); - return cipher; -}; - -/** - * Deprecated. Instead, use: - * - * var decipher = forge.cipher.createDecipher('DES-', key); - * - * Creates an DES cipher object to decrypt data using the given symmetric key. - * - * The key may be given as a binary-encoded string of bytes or a byte buffer. - * - * @param key the symmetric key to use (64 or 192 bits). - * @param mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -forge$u.des.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key: key, - output: null, - decrypt: true, - mode: mode - }); -}; - -/** - * Creates a new DES cipher algorithm object. - * - * @param name the name of the algorithm. - * @param mode the mode factory function. - * - * @return the DES algorithm object. - */ -forge$u.des.Algorithm = function(name, mode) { - var self = this; - self.name = name; - self.mode = new mode({ - blockSize: 8, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self._keys, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self._keys, inBlock, outBlock, true); - } - } - }); - self._init = false; -}; - -/** - * Initializes this DES algorithm by expanding its key. - * - * @param options the options to use. - * key the key to use with this algorithm. - * decrypt true if the algorithm should be initialized for decryption, - * false for encryption. - */ -forge$u.des.Algorithm.prototype.initialize = function(options) { - if(this._init) { - return; - } - - var key = forge$u.util.createBuffer(options.key); - if(this.name.indexOf('3DES') === 0) { - if(key.length() !== 24) { - throw new Error('Invalid Triple-DES key size: ' + key.length() * 8); - } - } - - // do key expansion to 16 or 48 subkeys (single or triple DES) - this._keys = _createKeys(key); - this._init = true; -}; - -/** Register DES algorithms **/ - -registerAlgorithm('DES-ECB', forge$u.cipher.modes.ecb); -registerAlgorithm('DES-CBC', forge$u.cipher.modes.cbc); -registerAlgorithm('DES-CFB', forge$u.cipher.modes.cfb); -registerAlgorithm('DES-OFB', forge$u.cipher.modes.ofb); -registerAlgorithm('DES-CTR', forge$u.cipher.modes.ctr); - -registerAlgorithm('3DES-ECB', forge$u.cipher.modes.ecb); -registerAlgorithm('3DES-CBC', forge$u.cipher.modes.cbc); -registerAlgorithm('3DES-CFB', forge$u.cipher.modes.cfb); -registerAlgorithm('3DES-OFB', forge$u.cipher.modes.ofb); -registerAlgorithm('3DES-CTR', forge$u.cipher.modes.ctr); - -function registerAlgorithm(name, mode) { - var factory = function() { - return new forge$u.des.Algorithm(name, mode); - }; - forge$u.cipher.registerAlgorithm(name, factory); -} - -/** DES implementation **/ - -var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004]; -var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000]; -var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200]; -var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080]; -var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100]; -var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010]; -var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002]; -var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000]; - -/** - * Create necessary sub keys. - * - * @param key the 64-bit or 192-bit key. - * - * @return the expanded keys. - */ -function _createKeys(key) { - var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204], - pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101], - pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808], - pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000], - pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010], - pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420], - pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002], - pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800], - pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002], - pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408], - pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020], - pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200], - pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010], - pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105]; - - // how many iterations (1 for des, 3 for triple des) - // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys - var iterations = key.length() > 8 ? 3 : 1; - - // stores the return keys - var keys = []; - - // now define the left shifts which need to be done - var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - - var n = 0, tmp; - for(var j = 0; j < iterations; j++) { - var left = key.getInt32(); - var right = key.getInt32(); - - tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= tmp; - left ^= (tmp << 4); - - tmp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= tmp; - right ^= (tmp << -16); - - tmp = ((left >>> 2) ^ right) & 0x33333333; - right ^= tmp; - left ^= (tmp << 2); - - tmp = ((right >>> -16) ^ left) & 0x0000ffff; - left ^= tmp; - right ^= (tmp << -16); - - tmp = ((left >>> 1) ^ right) & 0x55555555; - right ^= tmp; - left ^= (tmp << 1); - - tmp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= tmp; - right ^= (tmp << 8); - - tmp = ((left >>> 1) ^ right) & 0x55555555; - right ^= tmp; - left ^= (tmp << 1); - - // right needs to be shifted and OR'd with last four bits of left - tmp = (left << 8) | ((right >>> 20) & 0x000000f0); - - // left needs to be put upside down - left = ((right << 24) | ((right << 8) & 0xff0000) | - ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0)); - right = tmp; - - // now go through and perform these shifts on the left and right keys - for(var i = 0; i < shifts.length; ++i) { - //shift the keys either one or two bits to the left - if(shifts[i]) { - left = (left << 2) | (left >>> 26); - right = (right << 2) | (right >>> 26); - } else { - left = (left << 1) | (left >>> 27); - right = (right << 1) | (right >>> 27); - } - left &= -0xf; - right &= -0xf; - - // now apply PC-2, in such a way that E is easier when encrypting or - // decrypting this conversion will look like PC-2 except only the last 6 - // bits of each byte are used rather than 48 consecutive bits and the - // order of lines will be according to how the S selection functions will - // be applied: S2, S4, S6, S8, S1, S3, S5, S7 - var lefttmp = ( - pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | - pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] | - pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | - pc2bytes6[(left >>> 4) & 0xf]); - var righttmp = ( - pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | - pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] | - pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | - pc2bytes13[(right >>> 4) & 0xf]); - tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff; - keys[n++] = lefttmp ^ tmp; - keys[n++] = righttmp ^ (tmp << 16); - } - } - - return keys; -} - -/** - * Updates a single block (1 byte) using DES. The update will either - * encrypt or decrypt the block. - * - * @param keys the expanded keys. - * @param input the input block (an array of 32-bit words). - * @param output the updated output block. - * @param decrypt true to decrypt the block, false to encrypt it. - */ -function _updateBlock(keys, input, output, decrypt) { - // set up loops for single or triple DES - var iterations = keys.length === 32 ? 3 : 9; - var looping; - if(iterations === 3) { - looping = decrypt ? [30, -2, -2] : [0, 32, 2]; - } else { - looping = (decrypt ? - [94, 62, -2, 32, 64, 2, 30, -2, -2] : - [0, 32, 2, 62, 30, -2, 64, 96, 2]); - } - - var tmp; - - var left = input[0]; - var right = input[1]; - - // first each 64 bit chunk of the message must be permuted according to IP - tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= tmp; - left ^= (tmp << 4); - - tmp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= tmp; - left ^= (tmp << 16); - - tmp = ((right >>> 2) ^ left) & 0x33333333; - left ^= tmp; - right ^= (tmp << 2); - - tmp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= tmp; - right ^= (tmp << 8); - - tmp = ((left >>> 1) ^ right) & 0x55555555; - right ^= tmp; - left ^= (tmp << 1); - - // rotate left 1 bit - left = ((left << 1) | (left >>> 31)); - right = ((right << 1) | (right >>> 31)); - - for(var j = 0; j < iterations; j += 3) { - var endloop = looping[j + 1]; - var loopinc = looping[j + 2]; - - // now go through and perform the encryption or decryption - for(var i = looping[j]; i != endloop; i += loopinc) { - var right1 = right ^ keys[i]; - var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; - - // passing these bytes through the S selection functions - tmp = left; - left = right; - right = tmp ^ ( - spfunction2[(right1 >>> 24) & 0x3f] | - spfunction4[(right1 >>> 16) & 0x3f] | - spfunction6[(right1 >>> 8) & 0x3f] | - spfunction8[right1 & 0x3f] | - spfunction1[(right2 >>> 24) & 0x3f] | - spfunction3[(right2 >>> 16) & 0x3f] | - spfunction5[(right2 >>> 8) & 0x3f] | - spfunction7[right2 & 0x3f]); - } - // unreverse left and right - tmp = left; - left = right; - right = tmp; - } - - // rotate right 1 bit - left = ((left >>> 1) | (left << 31)); - right = ((right >>> 1) | (right << 31)); - - // now perform IP-1, which is IP in the opposite direction - tmp = ((left >>> 1) ^ right) & 0x55555555; - right ^= tmp; - left ^= (tmp << 1); - - tmp = ((right >>> 8) ^ left) & 0x00ff00ff; - left ^= tmp; - right ^= (tmp << 8); - - tmp = ((right >>> 2) ^ left) & 0x33333333; - left ^= tmp; - right ^= (tmp << 2); - - tmp = ((left >>> 16) ^ right) & 0x0000ffff; - right ^= tmp; - left ^= (tmp << 16); - - tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; - right ^= tmp; - left ^= (tmp << 4); - - output[0] = left; - output[1] = right; -} - -/** - * Deprecated. Instead, use: - * - * forge.cipher.createCipher('DES-', key); - * forge.cipher.createDecipher('DES-', key); - * - * Creates a deprecated DES cipher object. This object's mode will default to - * CBC (cipher-block-chaining). - * - * The key may be given as a binary-encoded string of bytes or a byte buffer. - * - * @param options the options to use. - * key the symmetric key to use (64 or 192 bits). - * output the buffer to write to. - * decrypt true for decryption, false for encryption. - * mode the cipher mode to use (default: 'CBC'). - * - * @return the cipher. - */ -function _createCipher(options) { - options = options || {}; - var mode = (options.mode || 'CBC').toUpperCase(); - var algorithm = 'DES-' + mode; - - var cipher; - if(options.decrypt) { - cipher = forge$u.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge$u.cipher.createCipher(algorithm, options.key); - } - - // backwards compatible start API - var start = cipher.start; - cipher.start = function(iv, options) { - // backwards compatibility: support second arg as output buffer - var output = null; - if(options instanceof forge$u.util.ByteBuffer) { - output = options; - options = {}; - } - options = options || {}; - options.output = output; - options.iv = iv; - start.call(cipher, options); - }; - - return cipher; -} - -/** - * Password-Based Key-Derivation Function #2 implementation. - * - * See RFC 2898 for details. - * - * @author Dave Longley - * - * Copyright (c) 2010-2013 Digital Bazaar, Inc. - */ - -var forge$t = forge$F; - - - - -var pkcs5 = forge$t.pkcs5 = forge$t.pkcs5 || {}; - -var crypto; -if(forge$t.util.isNodejs && !forge$t.options.usePureJavaScript) { - crypto = require$$1__default; -} - -/** - * Derives a key from a password. - * - * @param p the password as a binary-encoded string of bytes. - * @param s the salt as a binary-encoded string of bytes. - * @param c the iteration count, a positive integer. - * @param dkLen the intended length, in bytes, of the derived key, - * (max: 2^32 - 1) * hash length of the PRF. - * @param [md] the message digest (or algorithm identifier as a string) to use - * in the PRF, defaults to SHA-1. - * @param [callback(err, key)] presence triggers asynchronous version, called - * once the operation completes. - * - * @return the derived key, as a binary-encoded string of bytes, for the - * synchronous version (if no callback is specified). - */ -forge$t.pbkdf2 = pkcs5.pbkdf2 = function( - p, s, c, dkLen, md, callback) { - if(typeof md === 'function') { - callback = md; - md = null; - } - - // use native implementation if possible and not disabled, note that - // some node versions only support SHA-1, others allow digest to be changed - if(forge$t.util.isNodejs && !forge$t.options.usePureJavaScript && - crypto.pbkdf2 && (md === null || typeof md !== 'object') && - (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) { - if(typeof md !== 'string') { - // default prf to SHA-1 - md = 'sha1'; - } - p = Buffer.from(p, 'binary'); - s = Buffer.from(s, 'binary'); - if(!callback) { - if(crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary'); - } - return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary'); - } - if(crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2(p, s, c, dkLen, function(err, key) { - if(err) { - return callback(err); - } - callback(null, key.toString('binary')); - }); - } - return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) { - if(err) { - return callback(err); - } - callback(null, key.toString('binary')); - }); - } - - if(typeof md === 'undefined' || md === null) { - // default prf to SHA-1 - md = 'sha1'; - } - if(typeof md === 'string') { - if(!(md in forge$t.md.algorithms)) { - throw new Error('Unknown hash algorithm: ' + md); - } - md = forge$t.md[md].create(); - } - - var hLen = md.digestLength; - - /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and - stop. */ - if(dkLen > (0xFFFFFFFF * hLen)) { - var err = new Error('Derived key is too long.'); - if(callback) { - return callback(err); - } - throw err; - } - - /* 2. Let len be the number of hLen-octet blocks in the derived key, - rounding up, and let r be the number of octets in the last - block: - - len = CEIL(dkLen / hLen), - r = dkLen - (len - 1) * hLen. */ - var len = Math.ceil(dkLen / hLen); - var r = dkLen - (len - 1) * hLen; - - /* 3. For each block of the derived key apply the function F defined - below to the password P, the salt S, the iteration count c, and - the block index to compute the block: - - T_1 = F(P, S, c, 1), - T_2 = F(P, S, c, 2), - ... - T_len = F(P, S, c, len), - - where the function F is defined as the exclusive-or sum of the - first c iterates of the underlying pseudorandom function PRF - applied to the password P and the concatenation of the salt S - and the block index i: - - F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c - - where - - u_1 = PRF(P, S || INT(i)), - u_2 = PRF(P, u_1), - ... - u_c = PRF(P, u_{c-1}). - - Here, INT(i) is a four-octet encoding of the integer i, most - significant octet first. */ - var prf = forge$t.hmac.create(); - prf.start(md, p); - var dk = ''; - var xor, u_c, u_c1; - - // sync version - if(!callback) { - for(var i = 1; i <= len; ++i) { - // PRF(P, S || INT(i)) (first iteration) - prf.start(null, null); - prf.update(s); - prf.update(forge$t.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - - // PRF(P, u_{c-1}) (other iterations) - for(var j = 2; j <= c; ++j) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - // F(p, s, c, i) - xor = forge$t.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - } - - /* 4. Concatenate the blocks and extract the first dkLen octets to - produce a derived key DK: - - DK = T_1 || T_2 || ... || T_len<0..r-1> */ - dk += (i < len) ? xor : xor.substr(0, r); - } - /* 5. Output the derived key DK. */ - return dk; - } - - // async version - var i = 1, j; - function outer() { - if(i > len) { - // done - return callback(null, dk); - } - - // PRF(P, S || INT(i)) (first iteration) - prf.start(null, null); - prf.update(s); - prf.update(forge$t.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - - // PRF(P, u_{c-1}) (other iterations) - j = 2; - inner(); - } - - function inner() { - if(j <= c) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - // F(p, s, c, i) - xor = forge$t.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - ++j; - return forge$t.util.setImmediate(inner); - } - - /* 4. Concatenate the blocks and extract the first dkLen octets to - produce a derived key DK: - - DK = T_1 || T_2 || ... || T_len<0..r-1> */ - dk += (i < len) ? xor : xor.substr(0, r); - - ++i; - outer(); - } - - outer(); -}; - -/** - * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. - * - * See FIPS 180-2 for details. - * - * @author Dave Longley - * - * Copyright (c) 2010-2015 Digital Bazaar, Inc. - */ - -var forge$s = forge$F; - - - -var sha256 = forge$s.sha256 = forge$s.sha256 || {}; -forge$s.md.sha256 = forge$s.md.algorithms.sha256 = sha256; - -/** - * Creates a SHA-256 message digest object. - * - * @return a message digest object. - */ -sha256.create = function() { - // do initialization as necessary - if(!_initialized$2) { - _init$2(); - } - - // SHA-256 state contains eight 32-bit integers - var _state = null; - - // input buffer - var _input = forge$s.util.createBuffer(); - - // used for word storage - var _w = new Array(64); - - // message digest object - var md = { - algorithm: 'sha256', - blockLength: 64, - digestLength: 32, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - - /** - * Starts the digest. - * - * @return this digest object. - */ - md.start = function() { - // up to 56-bit message length for convenience - md.messageLength = 0; - - // full message length (set md.messageLength64 for backwards-compatibility) - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for(var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge$s.util.createBuffer(); - _state = { - h0: 0x6A09E667, - h1: 0xBB67AE85, - h2: 0x3C6EF372, - h3: 0xA54FF53A, - h4: 0x510E527F, - h5: 0x9B05688C, - h6: 0x1F83D9AB, - h7: 0x5BE0CD19 - }; - return md; - }; - // start digest automatically for first time - md.start(); - - /** - * Updates the digest with the given message input. The given input can - * treated as raw input (no encoding will be applied) or an encoding of - * 'utf8' maybe given to encode the input using UTF-8. - * - * @param msg the message input to update with. - * @param encoding the encoding to use (default: 'raw', other: 'utf8'). - * - * @return this digest object. - */ - md.update = function(msg, encoding) { - if(encoding === 'utf8') { - msg = forge$s.util.encodeUtf8(msg); - } - - // update message length - var len = msg.length; - md.messageLength += len; - len = [(len / 0x100000000) >>> 0, len >>> 0]; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = ((len[1] / 0x100000000) >>> 0); - } - - // add bytes to input buffer - _input.putBytes(msg); - - // process bytes - _update$2(_state, _w, _input); - - // compact input buffer every 2K or if empty - if(_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - - return md; - }; - - /** - * Produces the digest. - * - * @return a byte buffer containing the digest value. - */ - md.digest = function() { - /* Note: Here we copy the remaining bytes in the input buffer and - add the appropriate SHA-256 padding. Then we do the final update - on a copy of the state so that if the user wants to get - intermediate digests they can do so. */ - - /* Determine the number of bytes that must be added to the message - to ensure its length is congruent to 448 mod 512. In other words, - the data to be digested must be a multiple of 512 bits (or 128 bytes). - This data includes the message, some padding, and the length of the - message. Since the length of the message will be encoded as 8 bytes (64 - bits), that means that the last segment of the data must have 56 bytes - (448 bits) of message and padding. Therefore, the length of the message - plus the padding must be congruent to 448 mod 512 because - 512 - 128 = 448. - - In order to fill up the message length it must be filled with - padding that begins with 1 bit followed by all 0 bits. Padding - must *always* be present, so if the message length is already - congruent to 448 mod 512, then 512 padding bits must be added. */ - - var finalBlock = forge$s.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - - // compute remaining size to be digested (include message length size) - var remaining = ( - md.fullMessageLength[md.fullMessageLength.length - 1] + - md.messageLengthSize); - - // add padding for overflow blockSize - overflow - // _padding starts with 1 byte with first bit is set (byte value 128), then - // there may be up to (blockSize - 1) other pad bytes - var overflow = remaining & (md.blockLength - 1); - finalBlock.putBytes(_padding$2.substr(0, md.blockLength - overflow)); - - // serialize message length in bits in big-endian order; since length - // is stored in bytes we multiply by 8 and add carry from next int - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = (next / 0x100000000) >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4, - h5: _state.h5, - h6: _state.h6, - h7: _state.h7 - }; - _update$2(s2, _w, finalBlock); - var rval = forge$s.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - rval.putInt32(s2.h5); - rval.putInt32(s2.h6); - rval.putInt32(s2.h7); - return rval; - }; - - return md; -}; - -// sha-256 padding bytes not initialized yet -var _padding$2 = null; -var _initialized$2 = false; - -// table of constants -var _k$1 = null; - -/** - * Initializes the constant tables. - */ -function _init$2() { - // create padding - _padding$2 = String.fromCharCode(128); - _padding$2 += forge$s.util.fillString(String.fromCharCode(0x00), 64); - - // create K table for SHA-256 - _k$1 = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; - - // now initialized - _initialized$2 = true; -} - -/** - * Updates a SHA-256 state with the given byte buffer. - * - * @param s the SHA-256 state to update. - * @param w the array to use to store words. - * @param bytes the byte buffer to update with. - */ -function _update$2(s, w, bytes) { - // consume 512 bit (64 byte) chunks - var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; - var len = bytes.length(); - while(len >= 64) { - // the w array will be populated with sixteen 32-bit big-endian words - // and then extended into 64 32-bit words according to SHA-256 - for(i = 0; i < 16; ++i) { - w[i] = bytes.getInt32(); - } - for(; i < 64; ++i) { - // XOR word 2 words ago rot right 17, rot right 19, shft right 10 - t1 = w[i - 2]; - t1 = - ((t1 >>> 17) | (t1 << 15)) ^ - ((t1 >>> 19) | (t1 << 13)) ^ - (t1 >>> 10); - // XOR word 15 words ago rot right 7, rot right 18, shft right 3 - t2 = w[i - 15]; - t2 = - ((t2 >>> 7) | (t2 << 25)) ^ - ((t2 >>> 18) | (t2 << 14)) ^ - (t2 >>> 3); - // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 - w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; - } - - // initialize hash value for this chunk - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - f = s.h5; - g = s.h6; - h = s.h7; - - // round function - for(i = 0; i < 64; ++i) { - // Sum1(e) - s1 = - ((e >>> 6) | (e << 26)) ^ - ((e >>> 11) | (e << 21)) ^ - ((e >>> 25) | (e << 7)); - // Ch(e, f, g) (optimized the same way as SHA-1) - ch = g ^ (e & (f ^ g)); - // Sum0(a) - s0 = - ((a >>> 2) | (a << 30)) ^ - ((a >>> 13) | (a << 19)) ^ - ((a >>> 22) | (a << 10)); - // Maj(a, b, c) (optimized the same way as SHA-1) - maj = (a & b) | (c & (a ^ b)); - - // main algorithm - t1 = h + s1 + ch + _k$1[i] + w[i]; - t2 = s0 + maj; - h = g; - g = f; - f = e; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - // can't truncate with `| 0` - e = (d + t1) >>> 0; - d = c; - c = b; - b = a; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - // can't truncate with `| 0` - a = (t1 + t2) >>> 0; - } - - // update hash state - s.h0 = (s.h0 + a) | 0; - s.h1 = (s.h1 + b) | 0; - s.h2 = (s.h2 + c) | 0; - s.h3 = (s.h3 + d) | 0; - s.h4 = (s.h4 + e) | 0; - s.h5 = (s.h5 + f) | 0; - s.h6 = (s.h6 + g) | 0; - s.h7 = (s.h7 + h) | 0; - len -= 64; - } -} - -/** - * A javascript implementation of a cryptographically-secure - * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed - * here though the use of SHA-256 is not enforced; when generating an - * a PRNG context, the hashing algorithm and block cipher used for - * the generator are specified via a plugin. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - */ - -var forge$r = forge$F; - - -var _crypto$1 = null; -if(forge$r.util.isNodejs && !forge$r.options.usePureJavaScript && - !process.versions['node-webkit']) { - _crypto$1 = require$$1__default; -} - -/* PRNG API */ -var prng = forge$r.prng = forge$r.prng || {}; - -/** - * Creates a new PRNG context. - * - * A PRNG plugin must be passed in that will provide: - * - * 1. A function that initializes the key and seed of a PRNG context. It - * will be given a 16 byte key and a 16 byte seed. Any key expansion - * or transformation of the seed from a byte string into an array of - * integers (or similar) should be performed. - * 2. The cryptographic function used by the generator. It takes a key and - * a seed. - * 3. A seed increment function. It takes the seed and returns seed + 1. - * 4. An api to create a message digest. - * - * For an example, see random.js. - * - * @param plugin the PRNG plugin to use. - */ -prng.create = function(plugin) { - var ctx = { - plugin: plugin, - key: null, - seed: null, - time: null, - // number of reseeds so far - reseeds: 0, - // amount of data generated so far - generated: 0, - // no initial key bytes - keyBytes: '' - }; - - // create 32 entropy pools (each is a message digest) - var md = plugin.md; - var pools = new Array(32); - for(var i = 0; i < 32; ++i) { - pools[i] = md.create(); - } - ctx.pools = pools; - - // entropy pools are written to cyclically, starting at index 0 - ctx.pool = 0; - - /** - * Generates random bytes. The bytes may be generated synchronously or - * asynchronously. Web workers must use the asynchronous interface or - * else the behavior is undefined. - * - * @param count the number of random bytes to generate. - * @param [callback(err, bytes)] called once the operation completes. - * - * @return count random bytes as a string. - */ - ctx.generate = function(count, callback) { - // do synchronously - if(!callback) { - return ctx.generateSync(count); - } - - // simple generator using counter-based CBC - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - var b = forge$r.util.createBuffer(); - - // paranoid deviation from Fortuna: - // reset key for every request to protect previously - // generated random bytes should the key be discovered; - // there is no 100ms based reseeding because of this - // forced reseed for every `generate` call - ctx.key = null; - - generate(); - - function generate(err) { - if(err) { - return callback(err); - } - - // sufficient bytes generated - if(b.length() >= count) { - return callback(null, b.getBytes(count)); - } - - // if amount of data generated is greater than 1 MiB, trigger reseed - if(ctx.generated > 0xfffff) { - ctx.key = null; - } - - if(ctx.key === null) { - // prevent stack overflow - return forge$r.util.nextTick(function() { - _reseed(generate); - }); - } - - // generate the random bytes - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - - // generate bytes for a new key and seed - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - - forge$r.util.setImmediate(generate); - } - }; - - /** - * Generates random bytes synchronously. - * - * @param count the number of random bytes to generate. - * - * @return count random bytes as a string. - */ - ctx.generateSync = function(count) { - // simple generator using counter-based CBC - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - - // paranoid deviation from Fortuna: - // reset key for every request to protect previously - // generated random bytes should the key be discovered; - // there is no 100ms based reseeding because of this - // forced reseed for every `generateSync` call - ctx.key = null; - - var b = forge$r.util.createBuffer(); - while(b.length() < count) { - // if amount of data generated is greater than 1 MiB, trigger reseed - if(ctx.generated > 0xfffff) { - ctx.key = null; - } - - if(ctx.key === null) { - _reseedSync(); - } - - // generate the random bytes - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - - // generate bytes for a new key and seed - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - } - - return b.getBytes(count); - }; - - /** - * Private function that asynchronously reseeds a generator. - * - * @param callback(err) called once the operation completes. - */ - function _reseed(callback) { - if(ctx.pools[0].messageLength >= 32) { - _seed(); - return callback(); - } - // not enough seed data... - var needed = (32 - ctx.pools[0].messageLength) << 5; - ctx.seedFile(needed, function(err, bytes) { - if(err) { - return callback(err); - } - ctx.collect(bytes); - _seed(); - callback(); - }); - } - - /** - * Private function that synchronously reseeds a generator. - */ - function _reseedSync() { - if(ctx.pools[0].messageLength >= 32) { - return _seed(); - } - // not enough seed data... - var needed = (32 - ctx.pools[0].messageLength) << 5; - ctx.collect(ctx.seedFileSync(needed)); - _seed(); - } - - /** - * Private function that seeds a generator once enough bytes are available. - */ - function _seed() { - // update reseed count - ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1; - - // goal is to update `key` via: - // key = hash(key + s) - // where 's' is all collected entropy from selected pools, then... - - // create a plugin-based message digest - var md = ctx.plugin.md.create(); - - // consume current key bytes - md.update(ctx.keyBytes); - - // digest the entropy of pools whose index k meet the - // condition 'n mod 2^k == 0' where n is the number of reseeds - var _2powK = 1; - for(var k = 0; k < 32; ++k) { - if(ctx.reseeds % _2powK === 0) { - md.update(ctx.pools[k].digest().getBytes()); - ctx.pools[k].start(); - } - _2powK = _2powK << 1; - } - - // get digest for key bytes - ctx.keyBytes = md.digest().getBytes(); - - // paranoid deviation from Fortuna: - // update `seed` via `seed = hash(key)` - // instead of initializing to zero once and only - // ever incrementing it - md.start(); - md.update(ctx.keyBytes); - var seedBytes = md.digest().getBytes(); - - // update state - ctx.key = ctx.plugin.formatKey(ctx.keyBytes); - ctx.seed = ctx.plugin.formatSeed(seedBytes); - ctx.generated = 0; - } - - /** - * The built-in default seedFile. This seedFile is used when entropy - * is needed immediately. - * - * @param needed the number of bytes that are needed. - * - * @return the random bytes. - */ - function defaultSeedFile(needed) { - // use window.crypto.getRandomValues strong source of entropy if available - var getRandomValues = null; - var globalScope = forge$r.util.globalScope; - var _crypto = globalScope.crypto || globalScope.msCrypto; - if(_crypto && _crypto.getRandomValues) { - getRandomValues = function(arr) { - return _crypto.getRandomValues(arr); - }; - } - - var b = forge$r.util.createBuffer(); - if(getRandomValues) { - while(b.length() < needed) { - // max byte length is 65536 before QuotaExceededError is thrown - // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues - var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); - var entropy = new Uint32Array(Math.floor(count)); - try { - getRandomValues(entropy); - for(var i = 0; i < entropy.length; ++i) { - b.putInt32(entropy[i]); - } - } catch(e) { - /* only ignore QuotaExceededError */ - if(!(typeof QuotaExceededError !== 'undefined' && - e instanceof QuotaExceededError)) { - throw e; - } - } - } - } - - // be sad and add some weak random data - if(b.length() < needed) { - /* Draws from Park-Miller "minimal standard" 31 bit PRNG, - implemented with David G. Carta's optimization: with 32 bit math - and without division (Public Domain). */ - var hi, lo, next; - var seed = Math.floor(Math.random() * 0x010000); - while(b.length() < needed) { - lo = 16807 * (seed & 0xFFFF); - hi = 16807 * (seed >> 16); - lo += (hi & 0x7FFF) << 16; - lo += hi >> 15; - lo = (lo & 0x7FFFFFFF) + (lo >> 31); - seed = lo & 0xFFFFFFFF; - - // consume lower 3 bytes of seed - for(var i = 0; i < 3; ++i) { - // throw in more pseudo random - next = seed >>> (i << 3); - next ^= Math.floor(Math.random() * 0x0100); - b.putByte(String.fromCharCode(next & 0xFF)); - } - } - } - - return b.getBytes(needed); - } - // initialize seed file APIs - if(_crypto$1) { - // use nodejs async API - ctx.seedFile = function(needed, callback) { - _crypto$1.randomBytes(needed, function(err, bytes) { - if(err) { - return callback(err); - } - callback(null, bytes.toString()); - }); - }; - // use nodejs sync API - ctx.seedFileSync = function(needed) { - return _crypto$1.randomBytes(needed).toString(); - }; - } else { - ctx.seedFile = function(needed, callback) { - try { - callback(null, defaultSeedFile(needed)); - } catch(e) { - callback(e); - } - }; - ctx.seedFileSync = defaultSeedFile; - } - - /** - * Adds entropy to a prng ctx's accumulator. - * - * @param bytes the bytes of entropy as a string. - */ - ctx.collect = function(bytes) { - // iterate over pools distributing entropy cyclically - var count = bytes.length; - for(var i = 0; i < count; ++i) { - ctx.pools[ctx.pool].update(bytes.substr(i, 1)); - ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1; - } - }; - - /** - * Collects an integer of n bits. - * - * @param i the integer entropy. - * @param n the number of bits in the integer. - */ - ctx.collectInt = function(i, n) { - var bytes = ''; - for(var x = 0; x < n; x += 8) { - bytes += String.fromCharCode((i >> x) & 0xFF); - } - ctx.collect(bytes); - }; - - /** - * Registers a Web Worker to receive immediate entropy from the main thread. - * This method is required until Web Workers can access the native crypto - * API. This method should be called twice for each created worker, once in - * the main thread, and once in the worker itself. - * - * @param worker the worker to register. - */ - ctx.registerWorker = function(worker) { - // worker receives random bytes - if(worker === self) { - ctx.seedFile = function(needed, callback) { - function listener(e) { - var data = e.data; - if(data.forge && data.forge.prng) { - self.removeEventListener('message', listener); - callback(data.forge.prng.err, data.forge.prng.bytes); - } - } - self.addEventListener('message', listener); - self.postMessage({forge: {prng: {needed: needed}}}); - }; - } else { - // main thread sends random bytes upon request - var listener = function(e) { - var data = e.data; - if(data.forge && data.forge.prng) { - ctx.seedFile(data.forge.prng.needed, function(err, bytes) { - worker.postMessage({forge: {prng: {err: err, bytes: bytes}}}); - }); - } - }; - // TODO: do we need to remove the event listener when the worker dies? - worker.addEventListener('message', listener); - } - }; - - return ctx; -}; - -/** - * An API for getting cryptographically-secure random bytes. The bytes are - * generated using the Fortuna algorithm devised by Bruce Schneier and - * Niels Ferguson. - * - * Getting strong random bytes is not yet easy to do in javascript. The only - * truish random entropy that can be collected is from the mouse, keyboard, or - * from timing with respect to page loads, etc. This generator makes a poor - * attempt at providing random bytes when those sources haven't yet provided - * enough entropy to initially seed or to reseed the PRNG. - * - * @author Dave Longley - * - * Copyright (c) 2009-2014 Digital Bazaar, Inc. - */ - -var forge$q = forge$F; - - - - - -(function() { - -// forge.random already defined -if(forge$q.random && forge$q.random.getBytes) { - return; -} - -(function(jQuery) { - -// the default prng plugin, uses AES-128 -var prng_aes = {}; -var _prng_aes_output = new Array(4); -var _prng_aes_buffer = forge$q.util.createBuffer(); -prng_aes.formatKey = function(key) { - // convert the key into 32-bit integers - var tmp = forge$q.util.createBuffer(key); - key = new Array(4); - key[0] = tmp.getInt32(); - key[1] = tmp.getInt32(); - key[2] = tmp.getInt32(); - key[3] = tmp.getInt32(); - - // return the expanded key - return forge$q.aes._expandKey(key, false); -}; -prng_aes.formatSeed = function(seed) { - // convert seed into 32-bit integers - var tmp = forge$q.util.createBuffer(seed); - seed = new Array(4); - seed[0] = tmp.getInt32(); - seed[1] = tmp.getInt32(); - seed[2] = tmp.getInt32(); - seed[3] = tmp.getInt32(); - return seed; -}; -prng_aes.cipher = function(key, seed) { - forge$q.aes._updateBlock(key, seed, _prng_aes_output, false); - _prng_aes_buffer.putInt32(_prng_aes_output[0]); - _prng_aes_buffer.putInt32(_prng_aes_output[1]); - _prng_aes_buffer.putInt32(_prng_aes_output[2]); - _prng_aes_buffer.putInt32(_prng_aes_output[3]); - return _prng_aes_buffer.getBytes(); -}; -prng_aes.increment = function(seed) { - // FIXME: do we care about carry or signed issues? - ++seed[3]; - return seed; -}; -prng_aes.md = forge$q.md.sha256; - -/** - * Creates a new PRNG. - */ -function spawnPrng() { - var ctx = forge$q.prng.create(prng_aes); - - /** - * Gets random bytes. If a native secure crypto API is unavailable, this - * method tries to make the bytes more unpredictable by drawing from data that - * can be collected from the user of the browser, eg: mouse movement. - * - * If a callback is given, this method will be called asynchronously. - * - * @param count the number of random bytes to get. - * @param [callback(err, bytes)] called once the operation completes. - * - * @return the random bytes in a string. - */ - ctx.getBytes = function(count, callback) { - return ctx.generate(count, callback); - }; - - /** - * Gets random bytes asynchronously. If a native secure crypto API is - * unavailable, this method tries to make the bytes more unpredictable by - * drawing from data that can be collected from the user of the browser, - * eg: mouse movement. - * - * @param count the number of random bytes to get. - * - * @return the random bytes in a string. - */ - ctx.getBytesSync = function(count) { - return ctx.generate(count); - }; - - return ctx; -} - -// create default prng context -var _ctx = spawnPrng(); - -// add other sources of entropy only if window.crypto.getRandomValues is not -// available -- otherwise this source will be automatically used by the prng -var getRandomValues = null; -var globalScope = forge$q.util.globalScope; -var _crypto = globalScope.crypto || globalScope.msCrypto; -if(_crypto && _crypto.getRandomValues) { - getRandomValues = function(arr) { - return _crypto.getRandomValues(arr); - }; -} - -if((!forge$q.util.isNodejs && !getRandomValues)) { - - // get load time entropy - _ctx.collectInt(+new Date(), 32); - - // add some entropy from navigator object - if(typeof(navigator) !== 'undefined') { - var _navBytes = ''; - for(var key in navigator) { - try { - if(typeof(navigator[key]) == 'string') { - _navBytes += navigator[key]; - } - } catch(e) { - /* Some navigator keys might not be accessible, e.g. the geolocation - attribute throws an exception if touched in Mozilla chrome:// - context. - - Silently ignore this and just don't use this as a source of - entropy. */ - } - } - _ctx.collect(_navBytes); - _navBytes = null; - } - - // add mouse and keyboard collectors if jquery is available - if(jQuery) { - // set up mouse entropy capture - jQuery().mousemove(function(e) { - // add mouse coords - _ctx.collectInt(e.clientX, 16); - _ctx.collectInt(e.clientY, 16); - }); - - // set up keyboard entropy capture - jQuery().keypress(function(e) { - _ctx.collectInt(e.charCode, 8); - }); - } -} - -/* Random API */ -if(!forge$q.random) { - forge$q.random = _ctx; -} else { - // extend forge.random with _ctx - for(var key in _ctx) { - forge$q.random[key] = _ctx[key]; - } -} - -// expose spawn PRNG -forge$q.random.createInstance = spawnPrng; - -})(typeof(jQuery) !== 'undefined' ? jQuery : null); - -})(); - -/** - * RC2 implementation. - * - * @author Stefan Siegl - * - * Copyright (c) 2012 Stefan Siegl - * - * Information on the RC2 cipher is available from RFC #2268, - * http://www.ietf.org/rfc/rfc2268.txt - */ - -var forge$p = forge$F; - - -var piTable = [ - 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, - 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, - 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0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x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, - 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad -]; - -var s = [1, 2, 3, 5]; - -/** - * Rotate a word left by given number of bits. - * - * Bits that are shifted out on the left are put back in on the right - * hand side. - * - * @param word The word to shift left. - * @param bits The number of bits to shift by. - * @return The rotated word. - */ -var rol = function(word, bits) { - return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits)); -}; - -/** - * Rotate a word right by given number of bits. - * - * Bits that are shifted out on the right are put back in on the left - * hand side. - * - * @param word The word to shift right. - * @param bits The number of bits to shift by. - * @return The rotated word. - */ -var ror = function(word, bits) { - return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff); -}; - -/* RC2 API */ -forge$p.rc2 = forge$p.rc2 || {}; - -/** - * Perform RC2 key expansion as per RFC #2268, section 2. - * - * @param key variable-length user key (between 1 and 128 bytes) - * @param effKeyBits number of effective key bits (default: 128) - * @return the expanded RC2 key (ByteBuffer of 128 bytes) - */ -forge$p.rc2.expandKey = function(key, effKeyBits) { - if(typeof key === 'string') { - key = forge$p.util.createBuffer(key); - } - effKeyBits = effKeyBits || 128; - - /* introduce variables that match the names used in RFC #2268 */ - var L = key; - var T = key.length(); - var T1 = effKeyBits; - var T8 = Math.ceil(T1 / 8); - var TM = 0xff >> (T1 & 0x07); - var i; - - for(i = T; i < 128; i++) { - L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]); - } - - L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); - - for(i = 127 - T8; i >= 0; i--) { - L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); - } - - return L; -}; - -/** - * Creates a RC2 cipher object. - * - * @param key the symmetric key to use (as base for key generation). - * @param bits the number of effective key bits. - * @param encrypt false for decryption, true for encryption. - * - * @return the cipher. - */ -var createCipher = function(key, bits, encrypt) { - var _finish = false, _input = null, _output = null, _iv = null; - var mixRound, mashRound; - var i, j, K = []; - - /* Expand key and fill into K[] Array */ - key = forge$p.rc2.expandKey(key, bits); - for(i = 0; i < 64; i++) { - K.push(key.getInt16Le()); - } - - if(encrypt) { - /** - * Perform one mixing round "in place". - * - * @param R Array of four words to perform mixing on. - */ - mixRound = function(R) { - for(i = 0; i < 4; i++) { - R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + - ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); - R[i] = rol(R[i], s[i]); - j++; - } - }; - - /** - * Perform one mashing round "in place". - * - * @param R Array of four words to perform mashing on. - */ - mashRound = function(R) { - for(i = 0; i < 4; i++) { - R[i] += K[R[(i + 3) % 4] & 63]; - } - }; - } else { - /** - * Perform one r-mixing round "in place". - * - * @param R Array of four words to perform mixing on. - */ - mixRound = function(R) { - for(i = 3; i >= 0; i--) { - R[i] = ror(R[i], s[i]); - R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + - ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); - j--; - } - }; - - /** - * Perform one r-mashing round "in place". - * - * @param R Array of four words to perform mashing on. - */ - mashRound = function(R) { - for(i = 3; i >= 0; i--) { - R[i] -= K[R[(i + 3) % 4] & 63]; - } - }; - } - - /** - * Run the specified cipher execution plan. - * - * This function takes four words from the input buffer, applies the IV on - * it (if requested) and runs the provided execution plan. - * - * The plan must be put together in form of a array of arrays. Where the - * outer one is simply a list of steps to perform and the inner one needs - * to have two elements: the first one telling how many rounds to perform, - * the second one telling what to do (i.e. the function to call). - * - * @param {Array} plan The plan to execute. - */ - var runPlan = function(plan) { - var R = []; - - /* Get data from input buffer and fill the four words into R */ - for(i = 0; i < 4; i++) { - var val = _input.getInt16Le(); - - if(_iv !== null) { - if(encrypt) { - /* We're encrypting, apply the IV first. */ - val ^= _iv.getInt16Le(); - } else { - /* We're decryption, keep cipher text for next block. */ - _iv.putInt16Le(val); - } - } - - R.push(val & 0xffff); - } - - /* Reset global "j" variable as per spec. */ - j = encrypt ? 0 : 63; - - /* Run execution plan. */ - for(var ptr = 0; ptr < plan.length; ptr++) { - for(var ctr = 0; ctr < plan[ptr][0]; ctr++) { - plan[ptr][1](R); - } - } - - /* Write back result to output buffer. */ - for(i = 0; i < 4; i++) { - if(_iv !== null) { - if(encrypt) { - /* We're encrypting in CBC-mode, feed back encrypted bytes into - IV buffer to carry it forward to next block. */ - _iv.putInt16Le(R[i]); - } else { - R[i] ^= _iv.getInt16Le(); - } - } - - _output.putInt16Le(R[i]); - } - }; - - /* Create cipher object */ - var cipher = null; - cipher = { - /** - * Starts or restarts the encryption or decryption process, whichever - * was previously configured. - * - * To use the cipher in CBC mode, iv may be given either as a string - * of bytes, or as a byte buffer. For ECB mode, give null as iv. - * - * @param iv the initialization vector to use, null for ECB mode. - * @param output the output the buffer to write to, null to create one. - */ - start: function(iv, output) { - if(iv) { - /* CBC mode */ - if(typeof iv === 'string') { - iv = forge$p.util.createBuffer(iv); - } - } - - _finish = false; - _input = forge$p.util.createBuffer(); - _output = output || new forge$p.util.createBuffer(); - _iv = iv; - - cipher.output = _output; - }, - - /** - * Updates the next block. - * - * @param input the buffer to read from. - */ - update: function(input) { - if(!_finish) { - // not finishing, so fill the input buffer with more input - _input.putBuffer(input); - } - - while(_input.length() >= 8) { - runPlan([ - [ 5, mixRound ], - [ 1, mashRound ], - [ 6, mixRound ], - [ 1, mashRound ], - [ 5, mixRound ] - ]); - } - }, - - /** - * Finishes encrypting or decrypting. - * - * @param pad a padding function to use, null for PKCS#7 padding, - * signature(blockSize, buffer, decrypt). - * - * @return true if successful, false on error. - */ - finish: function(pad) { - var rval = true; - - if(encrypt) { - if(pad) { - rval = pad(8, _input, !encrypt); - } else { - // add PKCS#7 padding to block (each pad byte is the - // value of the number of pad bytes) - var padding = (_input.length() === 8) ? 8 : (8 - _input.length()); - _input.fillWithByte(padding, padding); - } - } - - if(rval) { - // do final update - _finish = true; - cipher.update(); - } - - if(!encrypt) { - // check for error: input data not a multiple of block size - rval = (_input.length() === 0); - if(rval) { - if(pad) { - rval = pad(8, _output, !encrypt); - } else { - // ensure padding byte count is valid - var len = _output.length(); - var count = _output.at(len - 1); - - if(count > len) { - rval = false; - } else { - // trim off padding bytes - _output.truncate(count); - } - } - } - } - - return rval; - } - }; - - return cipher; -}; - -/** - * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the - * given symmetric key. The output will be stored in the 'output' member - * of the returned cipher. - * - * The key and iv may be given as a string of bytes or a byte buffer. - * The cipher is initialized to use 128 effective key bits. - * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * - * @return the cipher. - */ -forge$p.rc2.startEncrypting = function(key, iv, output) { - var cipher = forge$p.rc2.createEncryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; -}; - -/** - * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the - * given symmetric key. - * - * The key may be given as a string of bytes or a byte buffer. - * - * To start encrypting call start() on the cipher with an iv and optional - * output buffer. - * - * @param key the symmetric key to use. - * - * @return the cipher. - */ -forge$p.rc2.createEncryptionCipher = function(key, bits) { - return createCipher(key, bits, true); -}; - -/** - * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the - * given symmetric key. The output will be stored in the 'output' member - * of the returned cipher. - * - * The key and iv may be given as a string of bytes or a byte buffer. - * The cipher is initialized to use 128 effective key bits. - * - * @param key the symmetric key to use. - * @param iv the initialization vector to use. - * @param output the buffer to write to, null to create one. - * - * @return the cipher. - */ -forge$p.rc2.startDecrypting = function(key, iv, output) { - var cipher = forge$p.rc2.createDecryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; -}; - -/** - * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the - * given symmetric key. - * - * The key may be given as a string of bytes or a byte buffer. - * - * To start decrypting call start() on the cipher with an iv and optional - * output buffer. - * - * @param key the symmetric key to use. - * - * @return the cipher. - */ -forge$p.rc2.createDecryptionCipher = function(key, bits) { - return createCipher(key, bits, false); -}; - -// Copyright (c) 2005 Tom Wu -// All Rights Reserved. -// See "LICENSE" for details. - -// Basic JavaScript BN library - subset useful for RSA encryption. - -/* -Licensing (LICENSE) -------------------- - -This software is covered under the following copyright: -*/ -/* - * Copyright (c) 2003-2005 Tom Wu - * All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, - * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY - * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. - * - * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, - * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF - * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT - * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * In addition, the following condition applies: - * - * All redistributions must retain an intact copy of this copyright notice - * and disclaimer. - */ -/* -Address all questions regarding this license to: - - Tom Wu - tjw@cs.Stanford.EDU -*/ -var forge$o = forge$F; - -forge$o.jsbn = forge$o.jsbn || {}; - -// Bits per digit -var dbits; - -// (public) Constructor -function BigInteger$2(a,b,c) { - this.data = []; - if(a != null) - if("number" == typeof a) this.fromNumber(a,b,c); - else if(b == null && "string" != typeof a) this.fromString(a,256); - else this.fromString(a,b); -} -forge$o.jsbn.BigInteger = BigInteger$2; - -// return new, unset BigInteger -function nbi() { return new BigInteger$2(null); } - -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. - -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) -function am1(i,x,w,j,c,n) { - while(--n >= 0) { - var v = x*this.data[i++]+w.data[j]+c; - c = Math.floor(v/0x4000000); - w.data[j++] = v&0x3ffffff; - } - return c; -} -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) -function am2(i,x,w,j,c,n) { - var xl = x&0x7fff, xh = x>>15; - while(--n >= 0) { - var l = this.data[i]&0x7fff; - var h = this.data[i++]>>15; - var m = xh*l+h*xl; - l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff); - c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); - w.data[j++] = l&0x3fffffff; - } - return c; -} -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. -function am3(i,x,w,j,c,n) { - var xl = x&0x3fff, xh = x>>14; - while(--n >= 0) { - var l = this.data[i]&0x3fff; - var h = this.data[i++]>>14; - var m = xh*l+h*xl; - l = xl*l+((m&0x3fff)<<14)+w.data[j]+c; - c = (l>>28)+(m>>14)+xh*h; - w.data[j++] = l&0xfffffff; - } - return c; -} - -// node.js (no browser) -if(typeof(navigator) === 'undefined') -{ - BigInteger$2.prototype.am = am3; - dbits = 28; -} else if((navigator.appName == "Microsoft Internet Explorer")) { - BigInteger$2.prototype.am = am2; - dbits = 30; -} else if((navigator.appName != "Netscape")) { - BigInteger$2.prototype.am = am1; - dbits = 26; -} else { // Mozilla/Netscape seems to prefer am3 - BigInteger$2.prototype.am = am3; - dbits = 28; -} - -BigInteger$2.prototype.DB = dbits; -BigInteger$2.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i]; - r.t = this.t; - r.s = this.s; -} - -// (protected) set from integer value x, -DV <= x < DV -function bnpFromInt(x) { - this.t = 1; - this.s = (x<0)?-1:0; - if(x > 0) this.data[0] = x; - else if(x < -1) this.data[0] = x+this.DV; - else this.t = 0; -} - -// return bigint initialized to value -function nbv(i) { var r = nbi(); r.fromInt(i); return r; } - -// (protected) set from string and radix -function bnpFromString(s,b) { - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 256) k = 8; // byte array - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else { this.fromRadix(s,b); return; } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while(--i >= 0) { - var x = (k==8)?s[i]&0xff:intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-") mi = true; - continue; - } - mi = false; - if(sh == 0) - this.data[this.t++] = x; - else if(sh+k > this.DB) { - this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); - } else - this.data[this.t-1] |= x<= this.DB) sh -= this.DB; - } - if(k == 8 && (s[0]&0x80) != 0) { - this.s = -1; - if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t; -} - -// (public) return string representation in given radix -function bnToString(b) { - if(this.s < 0) return "-"+this.negate().toString(b); - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else return this.toRadix(b); - var km = (1< 0) { - if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); } - while(i >= 0) { - if(p < k) { - d = (this.data[i]&((1<>(p+=this.DB-k); - } else { - d = (this.data[i]>>(p-=k))&km; - if(p <= 0) { p += this.DB; --i; } - } - if(d > 0) m = true; - if(m) r += int2char(d); - } - } - return m?r:"0"; -} - -// (public) -this -function bnNegate() { var r = nbi(); BigInteger$2.ZERO.subTo(this,r); return r; } - -// (public) |this| -function bnAbs() { return (this.s<0)?this.negate():this; } - -// (public) return + if this > a, - if this < a, 0 if equal -function bnCompareTo(a) { - var r = this.s-a.s; - if(r != 0) return r; - var i = this.t; - r = i-a.t; - if(r != 0) return (this.s<0)?-r:r; - while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r; - return 0; -} - -// returns bit length of the integer x -function nbits(x) { - var r = 1, t; - if((t=x>>>16) != 0) { x = t; r += 16; } - if((t=x>>8) != 0) { x = t; r += 8; } - if((t=x>>4) != 0) { x = t; r += 4; } - if((t=x>>2) != 0) { x = t; r += 2; } - if((t=x>>1) != 0) { x = t; r += 1; } - return r; -} - -// (public) return the number of bits in "this" -function bnBitLength() { - if(this.t <= 0) return 0; - return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM)); -} - -// (protected) r = this << n*DB -function bnpDLShiftTo(n,r) { - var i; - for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i]; - for(i = n-1; i >= 0; --i) r.data[i] = 0; - r.t = this.t+n; - r.s = this.s; -} - -// (protected) r = this >> n*DB -function bnpDRShiftTo(n,r) { - for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i]; - r.t = Math.max(this.t-n,0); - r.s = this.s; -} - -// (protected) r = this << n -function bnpLShiftTo(n,r) { - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<= 0; --i) { - r.data[i+ds+1] = (this.data[i]>>cbs)|c; - c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0; - r.data[ds] = c; - r.t = this.t+ds+1; - r.s = this.s; - r.clamp(); -} - -// (protected) r = this >> n -function bnpRShiftTo(n,r) { - r.s = this.s; - var ds = Math.floor(n/this.DB); - if(ds >= this.t) { r.t = 0; return; } - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<>bs; - for(var i = ds+1; i < this.t; ++i) { - r.data[i-ds-1] |= (this.data[i]&bm)<>bs; - } - if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB; - } - if(a.t < this.t) { - c -= a.s; - while(i < this.t) { - c += this.data[i]; - r.data[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while(i < a.t) { - c -= a.data[i]; - r.data[i++] = c&this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = (c<0)?-1:0; - if(c < -1) r.data[i++] = this.DV+c; - else if(c > 0) r.data[i++] = c; - r.t = i; - r.clamp(); -} - -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. -function bnpMultiplyTo(a,r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i+y.t; - while(--i >= 0) r.data[i] = 0; - for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t); - r.s = 0; - r.clamp(); - if(this.s != a.s) BigInteger$2.ZERO.subTo(r,r); -} - -// (protected) r = this^2, r != this (HAC 14.16) -function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2*x.t; - while(--i >= 0) r.data[i] = 0; - for(i = 0; i < x.t-1; ++i) { - var c = x.am(i,x.data[i],r,2*i,0,1); - if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { - r.data[i+x.t] -= x.DV; - r.data[i+x.t+1] = 1; - } - } - if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1); - r.s = 0; - r.clamp(); -} - -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. -function bnpDivRemTo(m,q,r) { - var pm = m.abs(); - if(pm.t <= 0) return; - var pt = this.abs(); - if(pt.t < pm.t) { - if(q != null) q.fromInt(0); - if(r != null) this.copyTo(r); - return; - } - if(r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus - if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } - var ys = y.t; - var y0 = y.data[ys-1]; - if(y0 == 0) return; - var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0); - var d1 = this.FV/yt, d2 = (1<= 0) { - r.data[r.t++] = 1; - r.subTo(t,r); - } - BigInteger$2.ONE.dlShiftTo(ys,t); - t.subTo(y,y); // "negative" y so we can replace sub with am later - while(y.t < ys) y.data[y.t++] = 0; - while(--j >= 0) { - // Estimate quotient digit - var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2); - if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out - y.dlShiftTo(j,t); - r.subTo(t,r); - while(r.data[i] < --qd) r.subTo(t,r); - } - } - if(q != null) { - r.drShiftTo(ys,q); - if(ts != ms) BigInteger$2.ZERO.subTo(q,q); - } - r.t = ys; - r.clamp(); - if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder - if(ts < 0) BigInteger$2.ZERO.subTo(r,r); -} - -// (public) this mod a -function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a,null,r); - if(this.s < 0 && r.compareTo(BigInteger$2.ZERO) > 0) a.subTo(r,r); - return r; -} - -// Modular reduction using "classic" algorithm -function Classic(m) { this.m = m; } -function cConvert(x) { - if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; -} -function cRevert(x) { return x; } -function cReduce(x) { x.divRemTo(this.m,null,x); } -function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } -function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - -Classic.prototype.convert = cConvert; -Classic.prototype.revert = cRevert; -Classic.prototype.reduce = cReduce; -Classic.prototype.mulTo = cMulTo; -Classic.prototype.sqrTo = cSqrTo; - -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. -function bnpInvDigit() { - if(this.t < 1) return 0; - var x = this.data[0]; - if((x&1) == 0) return 0; - var y = x&3; // y == 1/x mod 2^2 - y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 - y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 - y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y>0)?this.DV-y:-y; -} - -// Montgomery reduction -function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp&0x7fff; - this.mph = this.mp>>15; - this.um = (1<<(m.DB-15))-1; - this.mt2 = 2*m.t; -} - -// xR mod m -function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t,r); - r.divRemTo(this.m,null,r); - if(x.s < 0 && r.compareTo(BigInteger$2.ZERO) > 0) this.m.subTo(r,r); - return r; -} - -// x/R mod m -function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; -} - -// x = x/R mod m (HAC 14.32) -function montReduce(x) { - while(x.t <= this.mt2) // pad x so am has enough room later - x.data[x.t++] = 0; - for(var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x.data[i]*mp mod DV - var j = x.data[i]&0x7fff; - var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM; - // use am to combine the multiply-shift-add into one call - j = i+this.m.t; - x.data[j] += this.m.am(0,u0,x,i,0,this.m.t); - // propagate carry - while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; } - } - x.clamp(); - x.drShiftTo(this.m.t,x); - if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); -} - -// r = "x^2/R mod m"; x != r -function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - -// r = "xy/R mod m"; x,y != r -function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - -Montgomery.prototype.convert = montConvert; -Montgomery.prototype.revert = montRevert; -Montgomery.prototype.reduce = montReduce; -Montgomery.prototype.mulTo = montMulTo; -Montgomery.prototype.sqrTo = montSqrTo; - -// (protected) true iff this is even -function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; } - -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) -function bnpExp(e,z) { - if(e > 0xffffffff || e < 1) return BigInteger$2.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; - g.copyTo(r); - while(--i >= 0) { - z.sqrTo(r,r2); - if((e&(1< 0) z.mulTo(r2,g,r); - else { var t = r; r = r2; r2 = t; } - } - return z.revert(r); -} - -// (public) this^e % m, 0 <= e < 2^32 -function bnModPowInt(e,m) { - var z; - if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); - return this.exp(e,z); -} - -// protected -BigInteger$2.prototype.copyTo = bnpCopyTo; -BigInteger$2.prototype.fromInt = bnpFromInt; -BigInteger$2.prototype.fromString = bnpFromString; -BigInteger$2.prototype.clamp = bnpClamp; -BigInteger$2.prototype.dlShiftTo = bnpDLShiftTo; -BigInteger$2.prototype.drShiftTo = bnpDRShiftTo; -BigInteger$2.prototype.lShiftTo = bnpLShiftTo; -BigInteger$2.prototype.rShiftTo = bnpRShiftTo; -BigInteger$2.prototype.subTo = bnpSubTo; -BigInteger$2.prototype.multiplyTo = bnpMultiplyTo; -BigInteger$2.prototype.squareTo = bnpSquareTo; -BigInteger$2.prototype.divRemTo = bnpDivRemTo; -BigInteger$2.prototype.invDigit = bnpInvDigit; -BigInteger$2.prototype.isEven = bnpIsEven; -BigInteger$2.prototype.exp = bnpExp; - -// public -BigInteger$2.prototype.toString = bnToString; -BigInteger$2.prototype.negate = bnNegate; -BigInteger$2.prototype.abs = bnAbs; -BigInteger$2.prototype.compareTo = bnCompareTo; -BigInteger$2.prototype.bitLength = bnBitLength; -BigInteger$2.prototype.mod = bnMod; -BigInteger$2.prototype.modPowInt = bnModPowInt; - -// "constants" -BigInteger$2.ZERO = nbv(0); -BigInteger$2.ONE = nbv(1); - -// jsbn2 lib - -//Copyright (c) 2005-2009 Tom Wu -//All Rights Reserved. -//See "LICENSE" for details (See jsbn.js for LICENSE). - -//Extended JavaScript BN functions, required for RSA private ops. - -//Version 1.1: new BigInteger("0", 10) returns "proper" zero - -//(public) -function bnClone() { var r = nbi(); this.copyTo(r); return r; } - -//(public) return value as integer -function bnIntValue() { -if(this.s < 0) { - if(this.t == 1) return this.data[0]-this.DV; - else if(this.t == 0) return -1; -} else if(this.t == 1) return this.data[0]; -else if(this.t == 0) return 0; -// assumes 16 < DB < 32 -return ((this.data[1]&((1<<(32-this.DB))-1))<>24; } - -//(public) return value as short (assumes DB>=16) -function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; } - -//(protected) return x s.t. r^x < DV -function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } - -//(public) 0 if this == 0, 1 if this > 0 -function bnSigNum() { -if(this.s < 0) return -1; -else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0; -else return 1; -} - -//(protected) convert to radix string -function bnpToRadix(b) { -if(b == null) b = 10; -if(this.signum() == 0 || b < 2 || b > 36) return "0"; -var cs = this.chunkSize(b); -var a = Math.pow(b,cs); -var d = nbv(a), y = nbi(), z = nbi(), r = ""; -this.divRemTo(d,y,z); -while(y.signum() > 0) { - r = (a+z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d,y,z); -} -return z.intValue().toString(b) + r; -} - -//(protected) convert from radix string -function bnpFromRadix(s,b) { -this.fromInt(0); -if(b == null) b = 10; -var cs = this.chunkSize(b); -var d = Math.pow(b,cs), mi = false, j = 0, w = 0; -for(var i = 0; i < s.length; ++i) { - var x = intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b*w+x; - if(++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w,0); - j = 0; - w = 0; - } -} -if(j > 0) { - this.dMultiply(Math.pow(b,j)); - this.dAddOffset(w,0); -} -if(mi) BigInteger$2.ZERO.subTo(this,this); -} - -//(protected) alternate constructor -function bnpFromNumber(a,b,c) { -if("number" == typeof b) { - // new BigInteger(int,int,RNG) - if(a < 2) this.fromInt(1); - else { - this.fromNumber(a,c); - if(!this.testBit(a-1)) // force MSB set - this.bitwiseTo(BigInteger$2.ONE.shiftLeft(a-1),op_or,this); - if(this.isEven()) this.dAddOffset(1,0); // force odd - while(!this.isProbablePrime(b)) { - this.dAddOffset(2,0); - if(this.bitLength() > a) this.subTo(BigInteger$2.ONE.shiftLeft(a-1),this); - } - } -} else { - // new BigInteger(int,RNG) - var x = new Array(), t = a&7; - x.length = (a>>3)+1; - b.nextBytes(x); - if(t > 0) x[0] &= ((1< 0) { - if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p) - r[k++] = d|(this.s<<(this.DB-p)); - while(i >= 0) { - if(p < 8) { - d = (this.data[i]&((1<>(p+=this.DB-8); - } else { - d = (this.data[i]>>(p-=8))&0xff; - if(p <= 0) { p += this.DB; --i; } - } - if((d&0x80) != 0) d |= -256; - if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; - if(k > 0 || d != this.s) r[k++] = d; - } -} -return r; -} - -function bnEquals(a) { return(this.compareTo(a)==0); } -function bnMin(a) { return (this.compareTo(a)<0)?this:a; } -function bnMax(a) { return (this.compareTo(a)>0)?this:a; } - -//(protected) r = this op a (bitwise) -function bnpBitwiseTo(a,op,r) { -var i, f, m = Math.min(a.t,this.t); -for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]); -if(a.t < this.t) { - f = a.s&this.DM; - for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f); - r.t = this.t; -} else { - f = this.s&this.DM; - for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]); - r.t = a.t; -} -r.s = op(this.s,a.s); -r.clamp(); -} - -//(public) this & a -function op_and(x,y) { return x&y; } -function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } - -//(public) this | a -function op_or(x,y) { return x|y; } -function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } - -//(public) this ^ a -function op_xor(x,y) { return x^y; } -function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } - -//(public) this & ~a -function op_andnot(x,y) { return x&~y; } -function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } - -//(public) ~this -function bnNot() { -var r = nbi(); -for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i]; -r.t = this.t; -r.s = ~this.s; -return r; -} - -//(public) this << n -function bnShiftLeft(n) { -var r = nbi(); -if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); -return r; -} - -//(public) this >> n -function bnShiftRight(n) { -var r = nbi(); -if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); -return r; -} - -//return index of lowest 1-bit in x, x < 2^31 -function lbit(x) { -if(x == 0) return -1; -var r = 0; -if((x&0xffff) == 0) { x >>= 16; r += 16; } -if((x&0xff) == 0) { x >>= 8; r += 8; } -if((x&0xf) == 0) { x >>= 4; r += 4; } -if((x&3) == 0) { x >>= 2; r += 2; } -if((x&1) == 0) ++r; -return r; -} - -//(public) returns index of lowest 1-bit (or -1 if none) -function bnGetLowestSetBit() { -for(var i = 0; i < this.t; ++i) - if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]); -if(this.s < 0) return this.t*this.DB; -return -1; -} - -//return number of 1 bits in x -function cbit(x) { -var r = 0; -while(x != 0) { x &= x-1; ++r; } -return r; -} - -//(public) return number of set bits -function bnBitCount() { -var r = 0, x = this.s&this.DM; -for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x); -return r; -} - -//(public) true iff nth bit is set -function bnTestBit(n) { -var j = Math.floor(n/this.DB); -if(j >= this.t) return(this.s!=0); -return((this.data[j]&(1<<(n%this.DB)))!=0); -} - -//(protected) this op (1<>= this.DB; -} -if(a.t < this.t) { - c += a.s; - while(i < this.t) { - c += this.data[i]; - r.data[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; -} else { - c += this.s; - while(i < a.t) { - c += a.data[i]; - r.data[i++] = c&this.DM; - c >>= this.DB; - } - c += a.s; -} -r.s = (c<0)?-1:0; -if(c > 0) r.data[i++] = c; -else if(c < -1) r.data[i++] = this.DV+c; -r.t = i; -r.clamp(); -} - -//(public) this + a -function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } - -//(public) this - a -function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } - -//(public) this * a -function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } - -//(public) this / a -function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } - -//(public) this % a -function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } - -//(public) [this/a,this%a] -function bnDivideAndRemainder(a) { -var q = nbi(), r = nbi(); -this.divRemTo(a,q,r); -return new Array(q,r); -} - -//(protected) this *= n, this >= 0, 1 < n < DV -function bnpDMultiply(n) { -this.data[this.t] = this.am(0,n-1,this,0,0,this.t); -++this.t; -this.clamp(); -} - -//(protected) this += n << w words, this >= 0 -function bnpDAddOffset(n,w) { -if(n == 0) return; -while(this.t <= w) this.data[this.t++] = 0; -this.data[w] += n; -while(this.data[w] >= this.DV) { - this.data[w] -= this.DV; - if(++w >= this.t) this.data[this.t++] = 0; - ++this.data[w]; -} -} - -//A "null" reducer -function NullExp() {} -function nNop(x) { return x; } -function nMulTo(x,y,r) { x.multiplyTo(y,r); } -function nSqrTo(x,r) { x.squareTo(r); } - -NullExp.prototype.convert = nNop; -NullExp.prototype.revert = nNop; -NullExp.prototype.mulTo = nMulTo; -NullExp.prototype.sqrTo = nSqrTo; - -//(public) this^e -function bnPow(e) { return this.exp(e,new NullExp()); } - -//(protected) r = lower n words of "this * a", a.t <= n -//"this" should be the larger one if appropriate. -function bnpMultiplyLowerTo(a,n,r) { -var i = Math.min(this.t+a.t,n); -r.s = 0; // assumes a,this >= 0 -r.t = i; -while(i > 0) r.data[--i] = 0; -var j; -for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t); -for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i); -r.clamp(); -} - -//(protected) r = "this * a" without lower n words, n > 0 -//"this" should be the larger one if appropriate. -function bnpMultiplyUpperTo(a,n,r) { ---n; -var i = r.t = this.t+a.t-n; -r.s = 0; // assumes a,this >= 0 -while(--i >= 0) r.data[i] = 0; -for(i = Math.max(n-this.t,0); i < a.t; ++i) - r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n); -r.clamp(); -r.drShiftTo(1,r); -} - -//Barrett modular reduction -function Barrett(m) { -// setup Barrett -this.r2 = nbi(); -this.q3 = nbi(); -BigInteger$2.ONE.dlShiftTo(2*m.t,this.r2); -this.mu = this.r2.divide(m); -this.m = m; -} - -function barrettConvert(x) { -if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); -else if(x.compareTo(this.m) < 0) return x; -else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } -} - -function barrettRevert(x) { return x; } - -//x = x mod m (HAC 14.42) -function barrettReduce(x) { -x.drShiftTo(this.m.t-1,this.r2); -if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } -this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); -this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); -while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); -x.subTo(this.r2,x); -while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); -} - -//r = x^2 mod m; x != r -function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - -//r = x*y mod m; x,y != r -function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - -Barrett.prototype.convert = barrettConvert; -Barrett.prototype.revert = barrettRevert; -Barrett.prototype.reduce = barrettReduce; -Barrett.prototype.mulTo = barrettMulTo; -Barrett.prototype.sqrTo = barrettSqrTo; - -//(public) this^e % m (HAC 14.85) -function bnModPow(e,m) { -var i = e.bitLength(), k, r = nbv(1), z; -if(i <= 0) return r; -else if(i < 18) k = 1; -else if(i < 48) k = 3; -else if(i < 144) k = 4; -else if(i < 768) k = 5; -else k = 6; -if(i < 8) - z = new Classic(m); -else if(m.isEven()) - z = new Barrett(m); -else - z = new Montgomery(m); - -// precomputation -var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { - var g2 = nbi(); - z.sqrTo(g[1],g2); - while(n <= km) { - g[n] = nbi(); - z.mulTo(g2,g[n-2],g[n]); - n += 2; - } -} - -var j = e.t-1, w, is1 = true, r2 = nbi(), t; -i = nbits(e.data[j])-1; -while(j >= 0) { - if(i >= k1) w = (e.data[j]>>(i-k1))&km; - else { - w = (e.data[j]&((1<<(i+1))-1))<<(k1-i); - if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1); - } - - n = k; - while((w&1) == 0) { w >>= 1; --n; } - if((i -= n) < 0) { i += this.DB; --j; } - if(is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; - } else { - while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } - if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } - z.mulTo(r2,g[w],r); - } - - while(j >= 0 && (e.data[j]&(1< 0) { - x.rShiftTo(g,x); - y.rShiftTo(g,y); -} -while(x.signum() > 0) { - if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); - if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); - if(x.compareTo(y) >= 0) { - x.subTo(y,x); - x.rShiftTo(1,x); - } else { - y.subTo(x,y); - y.rShiftTo(1,y); - } -} -if(g > 0) y.lShiftTo(g,y); -return y; -} - -//(protected) this % n, n < 2^26 -function bnpModInt(n) { -if(n <= 0) return 0; -var d = this.DV%n, r = (this.s<0)?n-1:0; -if(this.t > 0) - if(d == 0) r = this.data[0]%n; - else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n; -return r; -} - -//(public) 1/this % m (HAC 14.61) -function bnModInverse(m) { -var ac = m.isEven(); -if((this.isEven() && ac) || m.signum() == 0) return BigInteger$2.ZERO; -var u = m.clone(), v = this.clone(); -var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); -while(u.signum() != 0) { - while(u.isEven()) { - u.rShiftTo(1,u); - if(ac) { - if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } - a.rShiftTo(1,a); - } else if(!b.isEven()) b.subTo(m,b); - b.rShiftTo(1,b); - } - while(v.isEven()) { - v.rShiftTo(1,v); - if(ac) { - if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } - c.rShiftTo(1,c); - } else if(!d.isEven()) d.subTo(m,d); - d.rShiftTo(1,d); - } - if(u.compareTo(v) >= 0) { - u.subTo(v,u); - if(ac) a.subTo(c,a); - b.subTo(d,b); - } else { - v.subTo(u,v); - if(ac) c.subTo(a,c); - d.subTo(b,d); - } -} -if(v.compareTo(BigInteger$2.ONE) != 0) return BigInteger$2.ZERO; -if(d.compareTo(m) >= 0) return d.subtract(m); -if(d.signum() < 0) d.addTo(m,d); else return d; -if(d.signum() < 0) return d.add(m); else return d; -} - -var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; -var lplim = (1<<26)/lowprimes[lowprimes.length-1]; - -//(public) test primality with certainty >= 1-.5^t -function bnIsProbablePrime(t) { -var i, x = this.abs(); -if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) { - for(i = 0; i < lowprimes.length; ++i) - if(x.data[0] == lowprimes[i]) return true; - return false; -} -if(x.isEven()) return false; -i = 1; -while(i < lowprimes.length) { - var m = lowprimes[i], j = i+1; - while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while(i < j) if(m%lowprimes[i++] == 0) return false; -} -return x.millerRabin(t); -} - -//(protected) true if probably prime (HAC 4.24, Miller-Rabin) -function bnpMillerRabin(t) { -var n1 = this.subtract(BigInteger$2.ONE); -var k = n1.getLowestSetBit(); -if(k <= 0) return false; -var r = n1.shiftRight(k); -var prng = bnGetPrng(); -var a; -for(var i = 0; i < t; ++i) { - // select witness 'a' at random from between 1 and n1 - do { - a = new BigInteger$2(this.bitLength(), prng); - } - while(a.compareTo(BigInteger$2.ONE) <= 0 || a.compareTo(n1) >= 0); - var y = a.modPow(r,this); - if(y.compareTo(BigInteger$2.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while(j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2,this); - if(y.compareTo(BigInteger$2.ONE) == 0) return false; - } - if(y.compareTo(n1) != 0) return false; - } -} -return true; -} - -// get pseudo random number generator -function bnGetPrng() { - // create prng with api that matches BigInteger secure random - return { - // x is an array to fill with bytes - nextBytes: function(x) { - for(var i = 0; i < x.length; ++i) { - x[i] = Math.floor(Math.random() * 0x0100); - } - } - }; -} - -//protected -BigInteger$2.prototype.chunkSize = bnpChunkSize; -BigInteger$2.prototype.toRadix = bnpToRadix; -BigInteger$2.prototype.fromRadix = bnpFromRadix; -BigInteger$2.prototype.fromNumber = bnpFromNumber; -BigInteger$2.prototype.bitwiseTo = bnpBitwiseTo; -BigInteger$2.prototype.changeBit = bnpChangeBit; -BigInteger$2.prototype.addTo = bnpAddTo; -BigInteger$2.prototype.dMultiply = bnpDMultiply; -BigInteger$2.prototype.dAddOffset = bnpDAddOffset; -BigInteger$2.prototype.multiplyLowerTo = bnpMultiplyLowerTo; -BigInteger$2.prototype.multiplyUpperTo = bnpMultiplyUpperTo; -BigInteger$2.prototype.modInt = bnpModInt; -BigInteger$2.prototype.millerRabin = bnpMillerRabin; - -//public -BigInteger$2.prototype.clone = bnClone; -BigInteger$2.prototype.intValue = bnIntValue; -BigInteger$2.prototype.byteValue = bnByteValue; -BigInteger$2.prototype.shortValue = bnShortValue; -BigInteger$2.prototype.signum = bnSigNum; -BigInteger$2.prototype.toByteArray = bnToByteArray; -BigInteger$2.prototype.equals = bnEquals; -BigInteger$2.prototype.min = bnMin; -BigInteger$2.prototype.max = bnMax; -BigInteger$2.prototype.and = bnAnd; -BigInteger$2.prototype.or = bnOr; -BigInteger$2.prototype.xor = bnXor; -BigInteger$2.prototype.andNot = bnAndNot; -BigInteger$2.prototype.not = bnNot; -BigInteger$2.prototype.shiftLeft = bnShiftLeft; -BigInteger$2.prototype.shiftRight = bnShiftRight; -BigInteger$2.prototype.getLowestSetBit = bnGetLowestSetBit; -BigInteger$2.prototype.bitCount = bnBitCount; -BigInteger$2.prototype.testBit = bnTestBit; -BigInteger$2.prototype.setBit = bnSetBit; -BigInteger$2.prototype.clearBit = bnClearBit; -BigInteger$2.prototype.flipBit = bnFlipBit; -BigInteger$2.prototype.add = bnAdd; -BigInteger$2.prototype.subtract = bnSubtract; -BigInteger$2.prototype.multiply = bnMultiply; -BigInteger$2.prototype.divide = bnDivide; -BigInteger$2.prototype.remainder = bnRemainder; -BigInteger$2.prototype.divideAndRemainder = bnDivideAndRemainder; -BigInteger$2.prototype.modPow = bnModPow; -BigInteger$2.prototype.modInverse = bnModInverse; -BigInteger$2.prototype.pow = bnPow; -BigInteger$2.prototype.gcd = bnGCD; -BigInteger$2.prototype.isProbablePrime = bnIsProbablePrime; - -/** - * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. - * - * @author Dave Longley - * - * Copyright (c) 2010-2015 Digital Bazaar, Inc. - */ - -var forge$n = forge$F; - - - -var sha1 = forge$n.sha1 = forge$n.sha1 || {}; -forge$n.md.sha1 = forge$n.md.algorithms.sha1 = sha1; - -/** - * Creates a SHA-1 message digest object. - * - * @return a message digest object. - */ -sha1.create = function() { - // do initialization as necessary - if(!_initialized$1) { - _init$1(); - } - - // SHA-1 state contains five 32-bit integers - var _state = null; - - // input buffer - var _input = forge$n.util.createBuffer(); - - // used for word storage - var _w = new Array(80); - - // message digest object - var md = { - algorithm: 'sha1', - blockLength: 64, - digestLength: 20, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - - /** - * Starts the digest. - * - * @return this digest object. - */ - md.start = function() { - // up to 56-bit message length for convenience - md.messageLength = 0; - - // full message length (set md.messageLength64 for backwards-compatibility) - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for(var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge$n.util.createBuffer(); - _state = { - h0: 0x67452301, - h1: 0xEFCDAB89, - h2: 0x98BADCFE, - h3: 0x10325476, - h4: 0xC3D2E1F0 - }; - return md; - }; - // start digest automatically for first time - md.start(); - - /** - * Updates the digest with the given message input. The given input can - * treated as raw input (no encoding will be applied) or an encoding of - * 'utf8' maybe given to encode the input using UTF-8. - * - * @param msg the message input to update with. - * @param encoding the encoding to use (default: 'raw', other: 'utf8'). - * - * @return this digest object. - */ - md.update = function(msg, encoding) { - if(encoding === 'utf8') { - msg = forge$n.util.encodeUtf8(msg); - } - - // update message length - var len = msg.length; - md.messageLength += len; - len = [(len / 0x100000000) >>> 0, len >>> 0]; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = ((len[1] / 0x100000000) >>> 0); - } - - // add bytes to input buffer - _input.putBytes(msg); - - // process bytes - _update$1(_state, _w, _input); - - // compact input buffer every 2K or if empty - if(_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - - return md; - }; - - /** - * Produces the digest. - * - * @return a byte buffer containing the digest value. - */ - md.digest = function() { - /* Note: Here we copy the remaining bytes in the input buffer and - add the appropriate SHA-1 padding. Then we do the final update - on a copy of the state so that if the user wants to get - intermediate digests they can do so. */ - - /* Determine the number of bytes that must be added to the message - to ensure its length is congruent to 448 mod 512. In other words, - the data to be digested must be a multiple of 512 bits (or 128 bytes). - This data includes the message, some padding, and the length of the - message. Since the length of the message will be encoded as 8 bytes (64 - bits), that means that the last segment of the data must have 56 bytes - (448 bits) of message and padding. Therefore, the length of the message - plus the padding must be congruent to 448 mod 512 because - 512 - 128 = 448. - - In order to fill up the message length it must be filled with - padding that begins with 1 bit followed by all 0 bits. Padding - must *always* be present, so if the message length is already - congruent to 448 mod 512, then 512 padding bits must be added. */ - - var finalBlock = forge$n.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - - // compute remaining size to be digested (include message length size) - var remaining = ( - md.fullMessageLength[md.fullMessageLength.length - 1] + - md.messageLengthSize); - - // add padding for overflow blockSize - overflow - // _padding starts with 1 byte with first bit is set (byte value 128), then - // there may be up to (blockSize - 1) other pad bytes - var overflow = remaining & (md.blockLength - 1); - finalBlock.putBytes(_padding$1.substr(0, md.blockLength - overflow)); - - // serialize message length in bits in big-endian order; since length - // is stored in bytes we multiply by 8 and add carry from next int - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = (next / 0x100000000) >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4 - }; - _update$1(s2, _w, finalBlock); - var rval = forge$n.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - return rval; - }; - - return md; -}; - -// sha-1 padding bytes not initialized yet -var _padding$1 = null; -var _initialized$1 = false; - -/** - * Initializes the constant tables. - */ -function _init$1() { - // create padding - _padding$1 = String.fromCharCode(128); - _padding$1 += forge$n.util.fillString(String.fromCharCode(0x00), 64); - - // now initialized - _initialized$1 = true; -} - -/** - * Updates a SHA-1 state with the given byte buffer. - * - * @param s the SHA-1 state to update. - * @param w the array to use to store words. - * @param bytes the byte buffer to update with. - */ -function _update$1(s, w, bytes) { - // consume 512 bit (64 byte) chunks - var t, a, b, c, d, e, f, i; - var len = bytes.length(); - while(len >= 64) { - // the w array will be populated with sixteen 32-bit big-endian words - // and then extended into 80 32-bit words according to SHA-1 algorithm - // and for 32-79 using Max Locktyukhin's optimization - - // initialize hash value for this chunk - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - - // round 1 - for(i = 0; i < 16; ++i) { - t = bytes.getInt32(); - w[i] = t; - f = d ^ (b & (c ^ d)); - t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - for(; i < 20; ++i) { - t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); - t = (t << 1) | (t >>> 31); - w[i] = t; - f = d ^ (b & (c ^ d)); - t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - // round 2 - for(; i < 32; ++i) { - t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); - t = (t << 1) | (t >>> 31); - w[i] = t; - f = b ^ c ^ d; - t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - for(; i < 40; ++i) { - t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); - t = (t << 2) | (t >>> 30); - w[i] = t; - f = b ^ c ^ d; - t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - // round 3 - for(; i < 60; ++i) { - t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); - t = (t << 2) | (t >>> 30); - w[i] = t; - f = (b & c) | (d & (b ^ c)); - t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - // round 4 - for(; i < 80; ++i) { - t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); - t = (t << 2) | (t >>> 30); - w[i] = t; - f = b ^ c ^ d; - t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; - e = d; - d = c; - // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug - c = ((b << 30) | (b >>> 2)) >>> 0; - b = a; - a = t; - } - - // update hash state - s.h0 = (s.h0 + a) | 0; - s.h1 = (s.h1 + b) | 0; - s.h2 = (s.h2 + c) | 0; - s.h3 = (s.h3 + d) | 0; - s.h4 = (s.h4 + e) | 0; - - len -= 64; - } -} - -/** - * Partial implementation of PKCS#1 v2.2: RSA-OEAP - * - * Modified but based on the following MIT and BSD licensed code: - * - * https://github.com/kjur/jsjws/blob/master/rsa.js: - * - * The 'jsjws'(JSON Web Signature JavaScript Library) License - * - * Copyright (c) 2012 Kenji Urushima - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain: - * - * RSAES-OAEP.js - * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $ - * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002) - * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003. - * Contact: ellis@nukinetics.com - * Distributed under the BSD License. - * - * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125 - * - * @author Evan Jones (http://evanjones.ca/) - * @author Dave Longley - * - * Copyright (c) 2013-2014 Digital Bazaar, Inc. - */ - -var forge$m = forge$F; - - - - -// shortcut for PKCS#1 API -var pkcs1 = forge$m.pkcs1 = forge$m.pkcs1 || {}; - -/** - * Encode the given RSAES-OAEP message (M) using key, with optional label (L) - * and seed. - * - * This method does not perform RSA encryption, it only encodes the message - * using RSAES-OAEP. - * - * @param key the RSA key to use. - * @param message the message to encode. - * @param options the options to use: - * label an optional label to use. - * seed the seed to use. - * md the message digest object to use, undefined for SHA-1. - * mgf1 optional mgf1 parameters: - * md the message digest object to use for MGF1. - * - * @return the encoded message bytes. - */ -pkcs1.encode_rsa_oaep = function(key, message, options) { - // parse arguments - var label; - var seed; - var md; - var mgf1Md; - // legacy args (label, seed, md) - if(typeof options === 'string') { - label = options; - seed = arguments[3] || undefined; - md = arguments[4] || undefined; - } else if(options) { - label = options.label || undefined; - seed = options.seed || undefined; - md = options.md || undefined; - if(options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - - // default OAEP to SHA-1 message digest - if(!md) { - md = forge$m.md.sha1.create(); - } else { - md.start(); - } - - // default MGF-1 to same as OAEP - if(!mgf1Md) { - mgf1Md = md; - } - - // compute length in bytes and check output - var keyLength = Math.ceil(key.n.bitLength() / 8); - var maxLength = keyLength - 2 * md.digestLength - 2; - if(message.length > maxLength) { - var error = new Error('RSAES-OAEP input message length is too long.'); - error.length = message.length; - error.maxLength = maxLength; - throw error; - } - - if(!label) { - label = ''; - } - md.update(label, 'raw'); - var lHash = md.digest(); - - var PS = ''; - var PS_length = maxLength - message.length; - for(var i = 0; i < PS_length; i++) { - PS += '\x00'; - } - - var DB = lHash.getBytes() + PS + '\x01' + message; - - if(!seed) { - seed = forge$m.random.getBytes(md.digestLength); - } else if(seed.length !== md.digestLength) { - var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' + - 'match the digest length.'); - error.seedLength = seed.length; - error.digestLength = md.digestLength; - throw error; - } - - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var maskedDB = forge$m.util.xorBytes(DB, dbMask, DB.length); - - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var maskedSeed = forge$m.util.xorBytes(seed, seedMask, seed.length); - - // return encoded message - return '\x00' + maskedSeed + maskedDB; -}; - -/** - * Decode the given RSAES-OAEP encoded message (EM) using key, with optional - * label (L). - * - * This method does not perform RSA decryption, it only decodes the message - * using RSAES-OAEP. - * - * @param key the RSA key to use. - * @param em the encoded message to decode. - * @param options the options to use: - * label an optional label to use. - * md the message digest object to use for OAEP, undefined for SHA-1. - * mgf1 optional mgf1 parameters: - * md the message digest object to use for MGF1. - * - * @return the decoded message bytes. - */ -pkcs1.decode_rsa_oaep = function(key, em, options) { - // parse args - var label; - var md; - var mgf1Md; - // legacy args - if(typeof options === 'string') { - label = options; - md = arguments[3] || undefined; - } else if(options) { - label = options.label || undefined; - md = options.md || undefined; - if(options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - - // compute length in bytes - var keyLength = Math.ceil(key.n.bitLength() / 8); - - if(em.length !== keyLength) { - var error = new Error('RSAES-OAEP encoded message length is invalid.'); - error.length = em.length; - error.expectedLength = keyLength; - throw error; - } - - // default OAEP to SHA-1 message digest - if(md === undefined) { - md = forge$m.md.sha1.create(); - } else { - md.start(); - } - - // default MGF-1 to same as OAEP - if(!mgf1Md) { - mgf1Md = md; - } - - if(keyLength < 2 * md.digestLength + 2) { - throw new Error('RSAES-OAEP key is too short for the hash function.'); - } - - if(!label) { - label = ''; - } - md.update(label, 'raw'); - var lHash = md.digest().getBytes(); - - // split the message into its parts - var y = em.charAt(0); - var maskedSeed = em.substring(1, md.digestLength + 1); - var maskedDB = em.substring(1 + md.digestLength); - - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var seed = forge$m.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); - - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var db = forge$m.util.xorBytes(maskedDB, dbMask, maskedDB.length); - - var lHashPrime = db.substring(0, md.digestLength); - - // constant time check that all values match what is expected - var error = (y !== '\x00'); - - // constant time check lHash vs lHashPrime - for(var i = 0; i < md.digestLength; ++i) { - error |= (lHash.charAt(i) !== lHashPrime.charAt(i)); - } - - // "constant time" find the 0x1 byte separating the padding (zeros) from the - // message - // TODO: It must be possible to do this in a better/smarter way? - var in_ps = 1; - var index = md.digestLength; - for(var j = md.digestLength; j < db.length; j++) { - var code = db.charCodeAt(j); - - var is_0 = (code & 0x1) ^ 0x1; - - // non-zero if not 0 or 1 in the ps section - var error_mask = in_ps ? 0xfffe : 0x0000; - error |= (code & error_mask); - - // latch in_ps to zero after we find 0x1 - in_ps = in_ps & is_0; - index += in_ps; - } - - if(error || db.charCodeAt(index) !== 0x1) { - throw new Error('Invalid RSAES-OAEP padding.'); - } - - return db.substring(index + 1); -}; - -function rsa_mgf1(seed, maskLength, hash) { - // default to SHA-1 message digest - if(!hash) { - hash = forge$m.md.sha1.create(); - } - var t = ''; - var count = Math.ceil(maskLength / hash.digestLength); - for(var i = 0; i < count; ++i) { - var c = String.fromCharCode( - (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF); - hash.start(); - hash.update(seed + c); - t += hash.digest().getBytes(); - } - return t.substring(0, maskLength); -} - -/** - * Prime number generation API. - * - * @author Dave Longley - * - * Copyright (c) 2014 Digital Bazaar, Inc. - */ - -var forge$l = forge$F; - - - - -(function() { - -// forge.prime already defined -if(forge$l.prime) { - return; -} - -/* PRIME API */ -var prime = forge$l.prime = forge$l.prime || {}; - -var BigInteger = forge$l.jsbn.BigInteger; - -// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 -var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; -var THIRTY = new BigInteger(null); -THIRTY.fromInt(30); -var op_or = function(x, y) {return x|y;}; - -/** - * Generates a random probable prime with the given number of bits. - * - * Alternative algorithms can be specified by name as a string or as an - * object with custom options like so: - * - * { - * name: 'PRIMEINC', - * options: { - * maxBlockTime: , - * millerRabinTests: , - * workerScript: , - * workers: . - * workLoad: the size of the work load, ie: number of possible prime - * numbers for each web worker to check per work assignment, - * (default: 100). - * } - * } - * - * @param bits the number of bits for the prime number. - * @param options the options to use. - * [algorithm] the algorithm to use (default: 'PRIMEINC'). - * [prng] a custom crypto-secure pseudo-random number generator to use, - * that must define "getBytesSync". - * - * @return callback(err, num) called once the operation completes. - */ -prime.generateProbablePrime = function(bits, options, callback) { - if(typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - // default to PRIMEINC algorithm - var algorithm = options.algorithm || 'PRIMEINC'; - if(typeof algorithm === 'string') { - algorithm = {name: algorithm}; - } - algorithm.options = algorithm.options || {}; - - // create prng with api that matches BigInteger secure random - var prng = options.prng || forge$l.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for(var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } - } - }; - - if(algorithm.name === 'PRIMEINC') { - return primeincFindPrime(bits, rng, algorithm.options, callback); - } - - throw new Error('Invalid prime generation algorithm: ' + algorithm.name); -}; - -function primeincFindPrime(bits, rng, options, callback) { - if('workers' in options) { - return primeincFindPrimeWithWorkers(bits, rng, options, callback); - } - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); -} - -function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { - // initialize random number - var num = generateRandom(bits, rng); - - /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The - number we are given is always aligned at 30k + 1. Each time the number is - determined not to be prime we add to get to the next 'i', eg: if the number - was at 30k + 1 we add 6. */ - var deltaIdx = 0; - - // get required number of MR tests - var mrTests = getMillerRabinTests(num.bitLength()); - if('millerRabinTests' in options) { - mrTests = options.millerRabinTests; - } - - // find prime nearest to 'num' for maxBlockTime ms - // 10 ms gives 5ms of leeway for other calculations before dropping - // below 60fps (1000/60 == 16.67), but in reality, the number will - // likely be higher due to an 'atomic' big int modPow - var maxBlockTime = 10; - if('maxBlockTime' in options) { - maxBlockTime = options.maxBlockTime; - } - - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); -} - -function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { - var start = +new Date(); - do { - // overflow, regenerate random number - if(num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - // do primality test - if(num.isProbablePrime(mrTests)) { - return callback(null, num); - } - // get next potential prime - num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime)); - - // keep trying later - forge$l.util.setImmediate(function() { - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); - }); -} - -// NOTE: This algorithm is indeterminate in nature because workers -// run in parallel looking at different segments of numbers. Even if this -// algorithm is run twice with the same input from a predictable RNG, it -// may produce different outputs. -function primeincFindPrimeWithWorkers(bits, rng, options, callback) { - // web workers unavailable - if(typeof Worker === 'undefined') { - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); - } - - // initialize random number - var num = generateRandom(bits, rng); - - // use web workers to generate keys - var numWorkers = options.workers; - var workLoad = options.workLoad || 100; - var range = workLoad * 30 / 8; - var workerScript = options.workerScript || 'forge/prime.worker.js'; - if(numWorkers === -1) { - return forge$l.util.estimateCores(function(err, cores) { - if(err) { - // default to 2 - cores = 2; - } - numWorkers = cores - 1; - generate(); - }); - } - generate(); - - function generate() { - // require at least 1 worker - numWorkers = Math.max(1, numWorkers); - - // TODO: consider optimizing by starting workers outside getPrime() ... - // note that in order to clean up they will have to be made internally - // asynchronous which may actually be slower - - // start workers immediately - var workers = []; - for(var i = 0; i < numWorkers; ++i) { - // FIXME: fix path or use blob URLs - workers[i] = new Worker(workerScript); - } - - // listen for requests from workers and assign ranges to find prime - for(var i = 0; i < numWorkers; ++i) { - workers[i].addEventListener('message', workerMessage); - } - - /* Note: The distribution of random numbers is unknown. Therefore, each - web worker is continuously allocated a range of numbers to check for a - random number until one is found. - - Every 30 numbers will be checked just 8 times, because prime numbers - have the form: - - 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this) - - Therefore, if we want a web worker to run N checks before asking for - a new range of numbers, each range must contain N*30/8 numbers. - - For 100 checks (workLoad), this is a range of 375. */ - - var found = false; - function workerMessage(e) { - // ignore message, prime already found - if(found) { - return; - } - var data = e.data; - if(data.found) { - // terminate all workers - for(var i = 0; i < workers.length; ++i) { - workers[i].terminate(); - } - found = true; - return callback(null, new BigInteger(data.prime, 16)); - } - - // overflow, regenerate random number - if(num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - - // assign new range to check - var hex = num.toString(16); - - // start prime search - e.target.postMessage({ - hex: hex, - workLoad: workLoad - }); - - num.dAddOffset(range, 0); - } - } -} - -/** - * Generates a random number using the given number of bits and RNG. - * - * @param bits the number of bits for the number. - * @param rng the random number generator to use. - * - * @return the random number. - */ -function generateRandom(bits, rng) { - var num = new BigInteger(bits, rng); - // force MSB set - var bits1 = bits - 1; - if(!num.testBit(bits1)) { - num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); - } - // align number on 30k+1 boundary - num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); - return num; -} - -/** - * Returns the required number of Miller-Rabin tests to generate a - * prime with an error probability of (1/2)^80. - * - * See Handbook of Applied Cryptography Chapter 4, Table 4.4. - * - * @param bits the bit size. - * - * @return the required number of iterations. - */ -function getMillerRabinTests(bits) { - if(bits <= 100) return 27; - if(bits <= 150) return 18; - if(bits <= 200) return 15; - if(bits <= 250) return 12; - if(bits <= 300) return 9; - if(bits <= 350) return 8; - if(bits <= 400) return 7; - if(bits <= 500) return 6; - if(bits <= 600) return 5; - if(bits <= 800) return 4; - if(bits <= 1250) return 3; - return 2; -} - -})(); - -/** - * Javascript implementation of basic RSA algorithms. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - * - * The only algorithm currently supported for PKI is RSA. - * - * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo - * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier - * and a subjectPublicKey of type bit string. - * - * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters - * for the algorithm, if any. In the case of RSA, there aren't any. - * - * SubjectPublicKeyInfo ::= SEQUENCE { - * algorithm AlgorithmIdentifier, - * subjectPublicKey BIT STRING - * } - * - * AlgorithmIdentifer ::= SEQUENCE { - * algorithm OBJECT IDENTIFIER, - * parameters ANY DEFINED BY algorithm OPTIONAL - * } - * - * For an RSA public key, the subjectPublicKey is: - * - * RSAPublicKey ::= SEQUENCE { - * modulus INTEGER, -- n - * publicExponent INTEGER -- e - * } - * - * PrivateKeyInfo ::= SEQUENCE { - * version Version, - * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, - * privateKey PrivateKey, - * attributes [0] IMPLICIT Attributes OPTIONAL - * } - * - * Version ::= INTEGER - * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier - * PrivateKey ::= OCTET STRING - * Attributes ::= SET OF Attribute - * - * An RSA private key as the following structure: - * - * RSAPrivateKey ::= SEQUENCE { - * version Version, - * modulus INTEGER, -- n - * publicExponent INTEGER, -- e - * privateExponent INTEGER, -- d - * prime1 INTEGER, -- p - * prime2 INTEGER, -- q - * exponent1 INTEGER, -- d mod (p-1) - * exponent2 INTEGER, -- d mod (q-1) - * coefficient INTEGER -- (inverse of q) mod p - * } - * - * Version ::= INTEGER - * - * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1 - */ - -var forge$k = forge$F; - - - - - - - - -if(typeof BigInteger$1 === 'undefined') { - var BigInteger$1 = forge$k.jsbn.BigInteger; -} - -var _crypto = forge$k.util.isNodejs ? require$$1__default : null; - -// shortcut for asn.1 API -var asn1$7 = forge$k.asn1; - -// shortcut for util API -var util = forge$k.util; - -/* - * RSA encryption and decryption, see RFC 2313. - */ -forge$k.pki = forge$k.pki || {}; -forge$k.pki.rsa = forge$k.rsa = forge$k.rsa || {}; -var pki$4 = forge$k.pki; - -// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 -var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; - -// validator for a PrivateKeyInfo structure -var privateKeyValidator$1 = { - // PrivateKeyInfo - name: 'PrivateKeyInfo', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: 'PrivateKeyInfo.version', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyVersion' - }, { - // privateKeyAlgorithm - name: 'PrivateKeyInfo.privateKeyAlgorithm', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.OID, - constructed: false, - capture: 'privateKeyOid' - }] - }, { - // PrivateKey - name: 'PrivateKeyInfo', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.OCTETSTRING, - constructed: false, - capture: 'privateKey' - }] -}; - -// validator for an RSA private key -var rsaPrivateKeyValidator = { - // RSAPrivateKey - name: 'RSAPrivateKey', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: 'RSAPrivateKey.version', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyVersion' - }, { - // modulus (n) - name: 'RSAPrivateKey.modulus', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyModulus' - }, { - // publicExponent (e) - name: 'RSAPrivateKey.publicExponent', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyPublicExponent' - }, { - // privateExponent (d) - name: 'RSAPrivateKey.privateExponent', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyPrivateExponent' - }, { - // prime1 (p) - name: 'RSAPrivateKey.prime1', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyPrime1' - }, { - // prime2 (q) - name: 'RSAPrivateKey.prime2', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyPrime2' - }, { - // exponent1 (d mod (p-1)) - name: 'RSAPrivateKey.exponent1', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyExponent1' - }, { - // exponent2 (d mod (q-1)) - name: 'RSAPrivateKey.exponent2', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyExponent2' - }, { - // coefficient ((inverse of q) mod p) - name: 'RSAPrivateKey.coefficient', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'privateKeyCoefficient' - }] -}; - -// validator for an RSA public key -var rsaPublicKeyValidator = { - // RSAPublicKey - name: 'RSAPublicKey', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.SEQUENCE, - constructed: true, - value: [{ - // modulus (n) - name: 'RSAPublicKey.modulus', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'publicKeyModulus' - }, { - // publicExponent (e) - name: 'RSAPublicKey.exponent', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.INTEGER, - constructed: false, - capture: 'publicKeyExponent' - }] -}; - -// validator for an SubjectPublicKeyInfo structure -// Note: Currently only works with an RSA public key -var publicKeyValidator$2 = forge$k.pki.rsa.publicKeyValidator = { - name: 'SubjectPublicKeyInfo', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.SEQUENCE, - constructed: true, - captureAsn1: 'subjectPublicKeyInfo', - value: [{ - name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.OID, - constructed: false, - capture: 'publicKeyOid' - }] - }, { - // subjectPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', - tagClass: asn1$7.Class.UNIVERSAL, - type: asn1$7.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'rsaPublicKey' - }] - }] -}; - -/** - * Wrap digest in DigestInfo object. - * - * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447. - * - * DigestInfo ::= SEQUENCE { - * digestAlgorithm DigestAlgorithmIdentifier, - * digest Digest - * } - * - * DigestAlgorithmIdentifier ::= AlgorithmIdentifier - * Digest ::= OCTET STRING - * - * @param md the message digest object with the hash to sign. - * - * @return the encoded message (ready for RSA encrytion) - */ -var emsaPkcs1v15encode = function(md) { - // get the oid for the algorithm - var oid; - if(md.algorithm in pki$4.oids) { - oid = pki$4.oids[md.algorithm]; - } else { - var error = new Error('Unknown message digest algorithm.'); - error.algorithm = md.algorithm; - throw error; - } - var oidBytes = asn1$7.oidToDer(oid).getBytes(); - - // create the digest info - var digestInfo = asn1$7.create( - asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, []); - var digestAlgorithm = asn1$7.create( - asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, []); - digestAlgorithm.value.push(asn1$7.create( - asn1$7.Class.UNIVERSAL, asn1$7.Type.OID, false, oidBytes)); - digestAlgorithm.value.push(asn1$7.create( - asn1$7.Class.UNIVERSAL, asn1$7.Type.NULL, false, '')); - var digest = asn1$7.create( - asn1$7.Class.UNIVERSAL, asn1$7.Type.OCTETSTRING, - false, md.digest().getBytes()); - digestInfo.value.push(digestAlgorithm); - digestInfo.value.push(digest); - - // encode digest info - return asn1$7.toDer(digestInfo).getBytes(); -}; - -/** - * Performs x^c mod n (RSA encryption or decryption operation). - * - * @param x the number to raise and mod. - * @param key the key to use. - * @param pub true if the key is public, false if private. - * - * @return the result of x^c mod n. - */ -var _modPow = function(x, key, pub) { - if(pub) { - return x.modPow(key.e, key.n); - } - - if(!key.p || !key.q) { - // allow calculation without CRT params (slow) - return x.modPow(key.d, key.n); - } - - // pre-compute dP, dQ, and qInv if necessary - if(!key.dP) { - key.dP = key.d.mod(key.p.subtract(BigInteger$1.ONE)); - } - if(!key.dQ) { - key.dQ = key.d.mod(key.q.subtract(BigInteger$1.ONE)); - } - if(!key.qInv) { - key.qInv = key.q.modInverse(key.p); - } - - /* Chinese remainder theorem (CRT) states: - - Suppose n1, n2, ..., nk are positive integers which are pairwise - coprime (n1 and n2 have no common factors other than 1). For any - integers x1, x2, ..., xk there exists an integer x solving the - system of simultaneous congruences (where ~= means modularly - congruent so a ~= b mod n means a mod n = b mod n): - - x ~= x1 mod n1 - x ~= x2 mod n2 - ... - x ~= xk mod nk - - This system of congruences has a single simultaneous solution x - between 0 and n - 1. Furthermore, each xk solution and x itself - is congruent modulo the product n = n1*n2*...*nk. - So x1 mod n = x2 mod n = xk mod n = x mod n. - - The single simultaneous solution x can be solved with the following - equation: - - x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni. - - Where x is less than n, xi = x mod ni. - - For RSA we are only concerned with k = 2. The modulus n = pq, where - p and q are coprime. The RSA decryption algorithm is: - - y = x^d mod n - - Given the above: - - x1 = x^d mod p - r1 = n/p = q - s1 = q^-1 mod p - x2 = x^d mod q - r2 = n/q = p - s2 = p^-1 mod q - - So y = (x1r1s1 + x2r2s2) mod n - = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n - - According to Fermat's Little Theorem, if the modulus P is prime, - for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P. - Since A is not divisible by P it follows that if: - N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore: - - A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort - to calculate). In order to calculate x^d mod p more quickly the - exponent d mod (p - 1) is stored in the RSA private key (the same - is done for x^d mod q). These values are referred to as dP and dQ - respectively. Therefore we now have: - - y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n - - Since we'll be reducing x^dP by modulo p (same for q) we can also - reduce x by p (and q respectively) before hand. Therefore, let - - xp = ((x mod p)^dP mod p), and - xq = ((x mod q)^dQ mod q), yielding: - - y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n - - This can be further reduced to a simple algorithm that only - requires 1 inverse (the q inverse is used) to be used and stored. - The algorithm is called Garner's algorithm. If qInv is the - inverse of q, we simply calculate: - - y = (qInv*(xp - xq) mod p) * q + xq - - However, there are two further complications. First, we need to - ensure that xp > xq to prevent signed BigIntegers from being used - so we add p until this is true (since we will be mod'ing with - p anyway). Then, there is a known timing attack on algorithms - using the CRT. To mitigate this risk, "cryptographic blinding" - should be used. This requires simply generating a random number r - between 0 and n-1 and its inverse and multiplying x by r^e before - calculating y and then multiplying y by r^-1 afterwards. Note that - r must be coprime with n (gcd(r, n) === 1) in order to have an - inverse. - */ - - // cryptographic blinding - var r; - do { - r = new BigInteger$1( - forge$k.util.bytesToHex(forge$k.random.getBytes(key.n.bitLength() / 8)), - 16); - } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger$1.ONE)); - x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); - - // calculate xp and xq - var xp = x.mod(key.p).modPow(key.dP, key.p); - var xq = x.mod(key.q).modPow(key.dQ, key.q); - - // xp must be larger than xq to avoid signed bit usage - while(xp.compareTo(xq) < 0) { - xp = xp.add(key.p); - } - - // do last step - var y = xp.subtract(xq) - .multiply(key.qInv).mod(key.p) - .multiply(key.q).add(xq); - - // remove effect of random for cryptographic blinding - y = y.multiply(r.modInverse(key.n)).mod(key.n); - - return y; -}; - -/** - * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or - * 'encrypt' on a public key object instead. - * - * Performs RSA encryption. - * - * The parameter bt controls whether to put padding bytes before the - * message passed in. Set bt to either true or false to disable padding - * completely (in order to handle e.g. EMSA-PSS encoding seperately before), - * signaling whether the encryption operation is a public key operation - * (i.e. encrypting data) or not, i.e. private key operation (data signing). - * - * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01 - * (for signing) or 0x02 (for encryption). The key operation mode (private - * or public) is derived from this flag in that case). - * - * @param m the message to encrypt as a byte string. - * @param key the RSA key to use. - * @param bt for PKCS#1 v1.5 padding, the block type to use - * (0x01 for private key, 0x02 for public), - * to disable padding: true = public key, false = private key. - * - * @return the encrypted bytes as a string. - */ -pki$4.rsa.encrypt = function(m, key, bt) { - var pub = bt; - var eb; - - // get the length of the modulus in bytes - var k = Math.ceil(key.n.bitLength() / 8); - - if(bt !== false && bt !== true) { - // legacy, default to PKCS#1 v1.5 padding - pub = (bt === 0x02); - eb = _encodePkcs1_v1_5(m, key, bt); - } else { - eb = forge$k.util.createBuffer(); - eb.putBytes(m); - } - - // load encryption block as big integer 'x' - // FIXME: hex conversion inefficient, get BigInteger w/byte strings - var x = new BigInteger$1(eb.toHex(), 16); - - // do RSA encryption - var y = _modPow(x, key, pub); - - // convert y into the encrypted data byte string, if y is shorter in - // bytes than k, then prepend zero bytes to fill up ed - // FIXME: hex conversion inefficient, get BigInteger w/byte strings - var yhex = y.toString(16); - var ed = forge$k.util.createBuffer(); - var zeros = k - Math.ceil(yhex.length / 2); - while(zeros > 0) { - ed.putByte(0x00); - --zeros; - } - ed.putBytes(forge$k.util.hexToBytes(yhex)); - return ed.getBytes(); -}; - -/** - * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or - * 'verify' on a public key object instead. - * - * Performs RSA decryption. - * - * The parameter ml controls whether to apply PKCS#1 v1.5 padding - * or not. Set ml = false to disable padding removal completely - * (in order to handle e.g. EMSA-PSS later on) and simply pass back - * the RSA encryption block. - * - * @param ed the encrypted data to decrypt in as a byte string. - * @param key the RSA key to use. - * @param pub true for a public key operation, false for private. - * @param ml the message length, if known, false to disable padding. - * - * @return the decrypted message as a byte string. - */ -pki$4.rsa.decrypt = function(ed, key, pub, ml) { - // get the length of the modulus in bytes - var k = Math.ceil(key.n.bitLength() / 8); - - // error if the length of the encrypted data ED is not k - if(ed.length !== k) { - var error = new Error('Encrypted message length is invalid.'); - error.length = ed.length; - error.expected = k; - throw error; - } - - // convert encrypted data into a big integer - // FIXME: hex conversion inefficient, get BigInteger w/byte strings - var y = new BigInteger$1(forge$k.util.createBuffer(ed).toHex(), 16); - - // y must be less than the modulus or it wasn't the result of - // a previous mod operation (encryption) using that modulus - if(y.compareTo(key.n) >= 0) { - throw new Error('Encrypted message is invalid.'); - } - - // do RSA decryption - var x = _modPow(y, key, pub); - - // create the encryption block, if x is shorter in bytes than k, then - // prepend zero bytes to fill up eb - // FIXME: hex conversion inefficient, get BigInteger w/byte strings - var xhex = x.toString(16); - var eb = forge$k.util.createBuffer(); - var zeros = k - Math.ceil(xhex.length / 2); - while(zeros > 0) { - eb.putByte(0x00); - --zeros; - } - eb.putBytes(forge$k.util.hexToBytes(xhex)); - - if(ml !== false) { - // legacy, default to PKCS#1 v1.5 padding - return _decodePkcs1_v1_5(eb.getBytes(), key, pub); - } - - // return message - return eb.getBytes(); -}; - -/** - * Creates an RSA key-pair generation state object. It is used to allow - * key-generation to be performed in steps. It also allows for a UI to - * display progress updates. - * - * @param bits the size for the private key in bits, defaults to 2048. - * @param e the public exponent to use, defaults to 65537 (0x10001). - * @param [options] the options to use. - * prng a custom crypto-secure pseudo-random number generator to use, - * that must define "getBytesSync". - * algorithm the algorithm to use (default: 'PRIMEINC'). - * - * @return the state object to use to generate the key-pair. - */ -pki$4.rsa.createKeyPairGenerationState = function(bits, e, options) { - // TODO: migrate step-based prime generation code to forge.prime - - // set default bits - if(typeof(bits) === 'string') { - bits = parseInt(bits, 10); - } - bits = bits || 2048; - - // create prng with api that matches BigInteger secure random - options = options || {}; - var prng = options.prng || forge$k.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for(var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } - } - }; - - var algorithm = options.algorithm || 'PRIMEINC'; - - // create PRIMEINC algorithm state - var rval; - if(algorithm === 'PRIMEINC') { - rval = { - algorithm: algorithm, - state: 0, - bits: bits, - rng: rng, - eInt: e || 65537, - e: new BigInteger$1(null), - p: null, - q: null, - qBits: bits >> 1, - pBits: bits - (bits >> 1), - pqState: 0, - num: null, - keys: null - }; - rval.e.fromInt(rval.eInt); - } else { - throw new Error('Invalid key generation algorithm: ' + algorithm); - } - - return rval; -}; - -/** - * Attempts to runs the key-generation algorithm for at most n seconds - * (approximately) using the given state. When key-generation has completed, - * the keys will be stored in state.keys. - * - * To use this function to update a UI while generating a key or to prevent - * causing browser lockups/warnings, set "n" to a value other than 0. A - * simple pattern for generating a key and showing a progress indicator is: - * - * var state = pki.rsa.createKeyPairGenerationState(2048); - * var step = function() { - * // step key-generation, run algorithm for 100 ms, repeat - * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) { - * setTimeout(step, 1); - * } else { - * // key-generation complete - * // TODO: turn off progress indicator here - * // TODO: use the generated key-pair in "state.keys" - * } - * }; - * // TODO: turn on progress indicator here - * setTimeout(step, 0); - * - * @param state the state to use. - * @param n the maximum number of milliseconds to run the algorithm for, 0 - * to run the algorithm to completion. - * - * @return true if the key-generation completed, false if not. - */ -pki$4.rsa.stepKeyPairGenerationState = function(state, n) { - // set default algorithm if not set - if(!('algorithm' in state)) { - state.algorithm = 'PRIMEINC'; - } - - // TODO: migrate step-based prime generation code to forge.prime - // TODO: abstract as PRIMEINC algorithm - - // do key generation (based on Tom Wu's rsa.js, see jsbn.js license) - // with some minor optimizations and designed to run in steps - - // local state vars - var THIRTY = new BigInteger$1(null); - THIRTY.fromInt(30); - var deltaIdx = 0; - var op_or = function(x, y) {return x | y;}; - - // keep stepping until time limit is reached or done - var t1 = +new Date(); - var t2; - var total = 0; - while(state.keys === null && (n <= 0 || total < n)) { - // generate p or q - if(state.state === 0) { - /* Note: All primes are of the form: - - 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i - - When we generate a random number, we always align it at 30k + 1. Each - time the number is determined not to be prime we add to get to the - next 'i', eg: if the number was at 30k + 1 we add 6. */ - var bits = (state.p === null) ? state.pBits : state.qBits; - var bits1 = bits - 1; - - // get a random number - if(state.pqState === 0) { - state.num = new BigInteger$1(bits, state.rng); - // force MSB set - if(!state.num.testBit(bits1)) { - state.num.bitwiseTo( - BigInteger$1.ONE.shiftLeft(bits1), op_or, state.num); - } - // align number on 30k+1 boundary - state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); - deltaIdx = 0; - - ++state.pqState; - } else if(state.pqState === 1) { - // try to make the number a prime - if(state.num.bitLength() > bits) { - // overflow, try again - state.pqState = 0; - // do primality test - } else if(state.num.isProbablePrime( - _getMillerRabinTests(state.num.bitLength()))) { - ++state.pqState; - } else { - // get next potential prime - state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } - } else if(state.pqState === 2) { - // ensure number is coprime with e - state.pqState = - (state.num.subtract(BigInteger$1.ONE).gcd(state.e) - .compareTo(BigInteger$1.ONE) === 0) ? 3 : 0; - } else if(state.pqState === 3) { - // store p or q - state.pqState = 0; - if(state.p === null) { - state.p = state.num; - } else { - state.q = state.num; - } - - // advance state if both p and q are ready - if(state.p !== null && state.q !== null) { - ++state.state; - } - state.num = null; - } - } else if(state.state === 1) { - // ensure p is larger than q (swap them if not) - if(state.p.compareTo(state.q) < 0) { - state.num = state.p; - state.p = state.q; - state.q = state.num; - } - ++state.state; - } else if(state.state === 2) { - // compute phi: (p - 1)(q - 1) (Euler's totient function) - state.p1 = state.p.subtract(BigInteger$1.ONE); - state.q1 = state.q.subtract(BigInteger$1.ONE); - state.phi = state.p1.multiply(state.q1); - ++state.state; - } else if(state.state === 3) { - // ensure e and phi are coprime - if(state.phi.gcd(state.e).compareTo(BigInteger$1.ONE) === 0) { - // phi and e are coprime, advance - ++state.state; - } else { - // phi and e aren't coprime, so generate a new p and q - state.p = null; - state.q = null; - state.state = 0; - } - } else if(state.state === 4) { - // create n, ensure n is has the right number of bits - state.n = state.p.multiply(state.q); - - // ensure n is right number of bits - if(state.n.bitLength() === state.bits) { - // success, advance - ++state.state; - } else { - // failed, get new q - state.q = null; - state.state = 0; - } - } else if(state.state === 5) { - // set keys - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki$4.rsa.setPrivateKey( - state.n, state.e, d, state.p, state.q, - d.mod(state.p1), d.mod(state.q1), - state.q.modInverse(state.p)), - publicKey: pki$4.rsa.setPublicKey(state.n, state.e) - }; - } - - // update timing - t2 = +new Date(); - total += t2 - t1; - t1 = t2; - } - - return state.keys !== null; -}; - -/** - * Generates an RSA public-private key pair in a single call. - * - * To generate a key-pair in steps (to allow for progress updates and to - * prevent blocking or warnings in slow browsers) then use the key-pair - * generation state functions. - * - * To generate a key-pair asynchronously (either through web-workers, if - * available, or by breaking up the work on the main thread), pass a - * callback function. - * - * @param [bits] the size for the private key in bits, defaults to 2048. - * @param [e] the public exponent to use, defaults to 65537. - * @param [options] options for key-pair generation, if given then 'bits' - * and 'e' must *not* be given: - * bits the size for the private key in bits, (default: 2048). - * e the public exponent to use, (default: 65537 (0x10001)). - * workerScript the worker script URL. - * workers the number of web workers (if supported) to use, - * (default: 2). - * workLoad the size of the work load, ie: number of possible prime - * numbers for each web worker to check per work assignment, - * (default: 100). - * prng a custom crypto-secure pseudo-random number generator to use, - * that must define "getBytesSync". Disables use of native APIs. - * algorithm the algorithm to use (default: 'PRIMEINC'). - * @param [callback(err, keypair)] called once the operation completes. - * - * @return an object with privateKey and publicKey properties. - */ -pki$4.rsa.generateKeyPair = function(bits, e, options, callback) { - // (bits), (options), (callback) - if(arguments.length === 1) { - if(typeof bits === 'object') { - options = bits; - bits = undefined; - } else if(typeof bits === 'function') { - callback = bits; - bits = undefined; - } - } else if(arguments.length === 2) { - // (bits, e), (bits, options), (bits, callback), (options, callback) - if(typeof bits === 'number') { - if(typeof e === 'function') { - callback = e; - e = undefined; - } else if(typeof e !== 'number') { - options = e; - e = undefined; - } - } else { - options = bits; - callback = e; - bits = undefined; - e = undefined; - } - } else if(arguments.length === 3) { - // (bits, e, options), (bits, e, callback), (bits, options, callback) - if(typeof e === 'number') { - if(typeof options === 'function') { - callback = options; - options = undefined; - } - } else { - callback = options; - options = e; - e = undefined; - } - } - options = options || {}; - if(bits === undefined) { - bits = options.bits || 2048; - } - if(e === undefined) { - e = options.e || 0x10001; - } - - // use native code if permitted, available, and parameters are acceptable - if(!options.prng && - bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) { - if(callback) { - // try native async - if(_detectNodeCrypto('generateKeyPair')) { - return _crypto.generateKeyPair('rsa', { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: 'spki', - format: 'pem' - }, - privateKeyEncoding: { - type: 'pkcs8', - format: 'pem' - } - }, function(err, pub, priv) { - if(err) { - return callback(err); - } - callback(null, { - privateKey: pki$4.privateKeyFromPem(priv), - publicKey: pki$4.publicKeyFromPem(pub) - }); - }); - } - if(_detectSubtleCrypto('generateKey') && - _detectSubtleCrypto('exportKey')) { - // use standard native generateKey - return util.globalScope.crypto.subtle.generateKey({ - name: 'RSASSA-PKCS1-v1_5', - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: {name: 'SHA-256'} - }, true /* key can be exported*/, ['sign', 'verify']) - .then(function(pair) { - return util.globalScope.crypto.subtle.exportKey( - 'pkcs8', pair.privateKey); - // avoiding catch(function(err) {...}) to support IE <= 8 - }).then(undefined, function(err) { - callback(err); - }).then(function(pkcs8) { - if(pkcs8) { - var privateKey = pki$4.privateKeyFromAsn1( - asn1$7.fromDer(forge$k.util.createBuffer(pkcs8))); - callback(null, { - privateKey: privateKey, - publicKey: pki$4.setRsaPublicKey(privateKey.n, privateKey.e) - }); - } - }); - } - if(_detectSubtleMsCrypto('generateKey') && - _detectSubtleMsCrypto('exportKey')) { - var genOp = util.globalScope.msCrypto.subtle.generateKey({ - name: 'RSASSA-PKCS1-v1_5', - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: {name: 'SHA-256'} - }, true /* key can be exported*/, ['sign', 'verify']); - genOp.oncomplete = function(e) { - var pair = e.target.result; - var exportOp = util.globalScope.msCrypto.subtle.exportKey( - 'pkcs8', pair.privateKey); - exportOp.oncomplete = function(e) { - var pkcs8 = e.target.result; - var privateKey = pki$4.privateKeyFromAsn1( - asn1$7.fromDer(forge$k.util.createBuffer(pkcs8))); - callback(null, { - privateKey: privateKey, - publicKey: pki$4.setRsaPublicKey(privateKey.n, privateKey.e) - }); - }; - exportOp.onerror = function(err) { - callback(err); - }; - }; - genOp.onerror = function(err) { - callback(err); - }; - return; - } - } else { - // try native sync - if(_detectNodeCrypto('generateKeyPairSync')) { - var keypair = _crypto.generateKeyPairSync('rsa', { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: 'spki', - format: 'pem' - }, - privateKeyEncoding: { - type: 'pkcs8', - format: 'pem' - } - }); - return { - privateKey: pki$4.privateKeyFromPem(keypair.privateKey), - publicKey: pki$4.publicKeyFromPem(keypair.publicKey) - }; - } - } - } - - // use JavaScript implementation - var state = pki$4.rsa.createKeyPairGenerationState(bits, e, options); - if(!callback) { - pki$4.rsa.stepKeyPairGenerationState(state, 0); - return state.keys; - } - _generateKeyPair(state, options, callback); -}; - -/** - * Sets an RSA public key from BigIntegers modulus and exponent. - * - * @param n the modulus. - * @param e the exponent. - * - * @return the public key. - */ -pki$4.setRsaPublicKey = pki$4.rsa.setPublicKey = function(n, e) { - var key = { - n: n, - e: e - }; - - /** - * Encrypts the given data with this public key. Newer applications - * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for - * legacy applications. - * - * @param data the byte string to encrypt. - * @param scheme the encryption scheme to use: - * 'RSAES-PKCS1-V1_5' (default), - * 'RSA-OAEP', - * 'RAW', 'NONE', or null to perform raw RSA encryption, - * an object with an 'encode' property set to a function - * with the signature 'function(data, key)' that returns - * a binary-encoded string representing the encoded data. - * @param schemeOptions any scheme-specific options. - * - * @return the encrypted byte string. - */ - key.encrypt = function(data, scheme, schemeOptions) { - if(typeof scheme === 'string') { - scheme = scheme.toUpperCase(); - } else if(scheme === undefined) { - scheme = 'RSAES-PKCS1-V1_5'; - } - - if(scheme === 'RSAES-PKCS1-V1_5') { - scheme = { - encode: function(m, key, pub) { - return _encodePkcs1_v1_5(m, key, 0x02).getBytes(); - } - }; - } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { - scheme = { - encode: function(m, key) { - return forge$k.pkcs1.encode_rsa_oaep(key, m, schemeOptions); - } - }; - } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { - scheme = {encode: function(e) {return e;}}; - } else if(typeof scheme === 'string') { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - - // do scheme-based encoding then rsa encryption - var e = scheme.encode(data, key, true); - return pki$4.rsa.encrypt(e, key, true); - }; - - /** - * Verifies the given signature against the given digest. - * - * PKCS#1 supports multiple (currently two) signature schemes: - * RSASSA-PKCS1-V1_5 and RSASSA-PSS. - * - * By default this implementation uses the "old scheme", i.e. - * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the - * signature is an OCTET STRING that holds a DigestInfo. - * - * DigestInfo ::= SEQUENCE { - * digestAlgorithm DigestAlgorithmIdentifier, - * digest Digest - * } - * DigestAlgorithmIdentifier ::= AlgorithmIdentifier - * Digest ::= OCTET STRING - * - * To perform PSS signature verification, provide an instance - * of Forge PSS object as the scheme parameter. - * - * @param digest the message digest hash to compare against the signature, - * as a binary-encoded string. - * @param signature the signature to verify, as a binary-encoded string. - * @param scheme signature verification scheme to use: - * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, - * a Forge PSS object for RSASSA-PSS, - * 'NONE' or null for none, DigestInfo will not be expected, but - * PKCS#1 v1.5 padding will still be used. - * - * @return true if the signature was verified, false if not. - */ - key.verify = function(digest, signature, scheme) { - if(typeof scheme === 'string') { - scheme = scheme.toUpperCase(); - } else if(scheme === undefined) { - scheme = 'RSASSA-PKCS1-V1_5'; - } - - if(scheme === 'RSASSA-PKCS1-V1_5') { - scheme = { - verify: function(digest, d) { - // remove padding - d = _decodePkcs1_v1_5(d, key, true); - // d is ASN.1 BER-encoded DigestInfo - var obj = asn1$7.fromDer(d); - // compare the given digest to the decrypted one - return digest === obj.value[1].value; - } - }; - } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { - scheme = { - verify: function(digest, d) { - // remove padding - d = _decodePkcs1_v1_5(d, key, true); - return digest === d; - } - }; - } - - // do rsa decryption w/o any decoding, then verify -- which does decoding - var d = pki$4.rsa.decrypt(signature, key, true, false); - return scheme.verify(digest, d, key.n.bitLength()); - }; - - return key; -}; - -/** - * Sets an RSA private key from BigIntegers modulus, exponent, primes, - * prime exponents, and modular multiplicative inverse. - * - * @param n the modulus. - * @param e the public exponent. - * @param d the private exponent ((inverse of e) mod n). - * @param p the first prime. - * @param q the second prime. - * @param dP exponent1 (d mod (p-1)). - * @param dQ exponent2 (d mod (q-1)). - * @param qInv ((inverse of q) mod p) - * - * @return the private key. - */ -pki$4.setRsaPrivateKey = pki$4.rsa.setPrivateKey = function( - n, e, d, p, q, dP, dQ, qInv) { - var key = { - n: n, - e: e, - d: d, - p: p, - q: q, - dP: dP, - dQ: dQ, - qInv: qInv - }; - - /** - * Decrypts the given data with this private key. The decryption scheme - * must match the one used to encrypt the data. - * - * @param data the byte string to decrypt. - * @param scheme the decryption scheme to use: - * 'RSAES-PKCS1-V1_5' (default), - * 'RSA-OAEP', - * 'RAW', 'NONE', or null to perform raw RSA decryption. - * @param schemeOptions any scheme-specific options. - * - * @return the decrypted byte string. - */ - key.decrypt = function(data, scheme, schemeOptions) { - if(typeof scheme === 'string') { - scheme = scheme.toUpperCase(); - } else if(scheme === undefined) { - scheme = 'RSAES-PKCS1-V1_5'; - } - - // do rsa decryption w/o any decoding - var d = pki$4.rsa.decrypt(data, key, false, false); - - if(scheme === 'RSAES-PKCS1-V1_5') { - scheme = {decode: _decodePkcs1_v1_5}; - } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { - scheme = { - decode: function(d, key) { - return forge$k.pkcs1.decode_rsa_oaep(key, d, schemeOptions); - } - }; - } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { - scheme = {decode: function(d) {return d;}}; - } else { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - - // decode according to scheme - return scheme.decode(d, key, false); - }; - - /** - * Signs the given digest, producing a signature. - * - * PKCS#1 supports multiple (currently two) signature schemes: - * RSASSA-PKCS1-V1_5 and RSASSA-PSS. - * - * By default this implementation uses the "old scheme", i.e. - * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide - * an instance of Forge PSS object as the scheme parameter. - * - * @param md the message digest object with the hash to sign. - * @param scheme the signature scheme to use: - * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, - * a Forge PSS object for RSASSA-PSS, - * 'NONE' or null for none, DigestInfo will not be used but - * PKCS#1 v1.5 padding will still be used. - * - * @return the signature as a byte string. - */ - key.sign = function(md, scheme) { - /* Note: The internal implementation of RSA operations is being - transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy - code like the use of an encoding block identifier 'bt' will eventually - be removed. */ - - // private key operation - var bt = false; - - if(typeof scheme === 'string') { - scheme = scheme.toUpperCase(); - } - - if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') { - scheme = {encode: emsaPkcs1v15encode}; - bt = 0x01; - } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { - scheme = {encode: function() {return md;}}; - bt = 0x01; - } - - // encode and then encrypt - var d = scheme.encode(md, key.n.bitLength()); - return pki$4.rsa.encrypt(d, key, bt); - }; - - return key; -}; - -/** - * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object. - * - * @param rsaKey the ASN.1 RSAPrivateKey. - * - * @return the ASN.1 PrivateKeyInfo. - */ -pki$4.wrapRsaPrivateKey = function(rsaKey) { - // PrivateKeyInfo - return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ - // version (0) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - asn1$7.integerToDer(0).getBytes()), - // privateKeyAlgorithm - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ - asn1$7.create( - asn1$7.Class.UNIVERSAL, asn1$7.Type.OID, false, - asn1$7.oidToDer(pki$4.oids.rsaEncryption).getBytes()), - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.NULL, false, '') - ]), - // PrivateKey - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.OCTETSTRING, false, - asn1$7.toDer(rsaKey).getBytes()) - ]); -}; - -/** - * Converts a private key from an ASN.1 object. - * - * @param obj the ASN.1 representation of a PrivateKeyInfo containing an - * RSAPrivateKey or an RSAPrivateKey. - * - * @return the private key. - */ -pki$4.privateKeyFromAsn1 = function(obj) { - // get PrivateKeyInfo - var capture = {}; - var errors = []; - if(asn1$7.validate(obj, privateKeyValidator$1, capture, errors)) { - obj = asn1$7.fromDer(forge$k.util.createBuffer(capture.privateKey)); - } - - // get RSAPrivateKey - capture = {}; - errors = []; - if(!asn1$7.validate(obj, rsaPrivateKeyValidator, capture, errors)) { - var error = new Error('Cannot read private key. ' + - 'ASN.1 object does not contain an RSAPrivateKey.'); - error.errors = errors; - throw error; - } - - // Note: Version is currently ignored. - // capture.privateKeyVersion - // FIXME: inefficient, get a BigInteger that uses byte strings - var n, e, d, p, q, dP, dQ, qInv; - n = forge$k.util.createBuffer(capture.privateKeyModulus).toHex(); - e = forge$k.util.createBuffer(capture.privateKeyPublicExponent).toHex(); - d = forge$k.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); - p = forge$k.util.createBuffer(capture.privateKeyPrime1).toHex(); - q = forge$k.util.createBuffer(capture.privateKeyPrime2).toHex(); - dP = forge$k.util.createBuffer(capture.privateKeyExponent1).toHex(); - dQ = forge$k.util.createBuffer(capture.privateKeyExponent2).toHex(); - qInv = forge$k.util.createBuffer(capture.privateKeyCoefficient).toHex(); - - // set private key - return pki$4.setRsaPrivateKey( - new BigInteger$1(n, 16), - new BigInteger$1(e, 16), - new BigInteger$1(d, 16), - new BigInteger$1(p, 16), - new BigInteger$1(q, 16), - new BigInteger$1(dP, 16), - new BigInteger$1(dQ, 16), - new BigInteger$1(qInv, 16)); -}; - -/** - * Converts a private key to an ASN.1 RSAPrivateKey. - * - * @param key the private key. - * - * @return the ASN.1 representation of an RSAPrivateKey. - */ -pki$4.privateKeyToAsn1 = pki$4.privateKeyToRSAPrivateKey = function(key) { - // RSAPrivateKey - return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ - // version (0 = only 2 primes, 1 multiple primes) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - asn1$7.integerToDer(0).getBytes()), - // modulus (n) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.n)), - // publicExponent (e) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.e)), - // privateExponent (d) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.d)), - // privateKeyPrime1 (p) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.p)), - // privateKeyPrime2 (q) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.q)), - // privateKeyExponent1 (dP) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.dP)), - // privateKeyExponent2 (dQ) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.dQ)), - // coefficient (qInv) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.qInv)) - ]); -}; - -/** - * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey. - * - * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey. - * - * @return the public key. - */ -pki$4.publicKeyFromAsn1 = function(obj) { - // get SubjectPublicKeyInfo - var capture = {}; - var errors = []; - if(asn1$7.validate(obj, publicKeyValidator$2, capture, errors)) { - // get oid - var oid = asn1$7.derToOid(capture.publicKeyOid); - if(oid !== pki$4.oids.rsaEncryption) { - var error = new Error('Cannot read public key. Unknown OID.'); - error.oid = oid; - throw error; - } - obj = capture.rsaPublicKey; - } - - // get RSA params - errors = []; - if(!asn1$7.validate(obj, rsaPublicKeyValidator, capture, errors)) { - var error = new Error('Cannot read public key. ' + - 'ASN.1 object does not contain an RSAPublicKey.'); - error.errors = errors; - throw error; - } - - // FIXME: inefficient, get a BigInteger that uses byte strings - var n = forge$k.util.createBuffer(capture.publicKeyModulus).toHex(); - var e = forge$k.util.createBuffer(capture.publicKeyExponent).toHex(); - - // set public key - return pki$4.setRsaPublicKey( - new BigInteger$1(n, 16), - new BigInteger$1(e, 16)); -}; - -/** - * Converts a public key to an ASN.1 SubjectPublicKeyInfo. - * - * @param key the public key. - * - * @return the asn1 representation of a SubjectPublicKeyInfo. - */ -pki$4.publicKeyToAsn1 = pki$4.publicKeyToSubjectPublicKeyInfo = function(key) { - // SubjectPublicKeyInfo - return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ - // AlgorithmIdentifier - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ - // algorithm - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.OID, false, - asn1$7.oidToDer(pki$4.oids.rsaEncryption).getBytes()), - // parameters (null) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.NULL, false, '') - ]), - // subjectPublicKey - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.BITSTRING, false, [ - pki$4.publicKeyToRSAPublicKey(key) - ]) - ]); -}; - -/** - * Converts a public key to an ASN.1 RSAPublicKey. - * - * @param key the public key. - * - * @return the asn1 representation of a RSAPublicKey. - */ -pki$4.publicKeyToRSAPublicKey = function(key) { - // RSAPublicKey - return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [ - // modulus (n) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.n)), - // publicExponent (e) - asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false, - _bnToBytes(key.e)) - ]); -}; - -/** - * Encodes a message using PKCS#1 v1.5 padding. - * - * @param m the message to encode. - * @param key the RSA key to use. - * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02 - * (for encryption). - * - * @return the padded byte buffer. - */ -function _encodePkcs1_v1_5(m, key, bt) { - var eb = forge$k.util.createBuffer(); - - // get the length of the modulus in bytes - var k = Math.ceil(key.n.bitLength() / 8); - - /* use PKCS#1 v1.5 padding */ - if(m.length > (k - 11)) { - var error = new Error('Message is too long for PKCS#1 v1.5 padding.'); - error.length = m.length; - error.max = k - 11; - throw error; - } - - /* A block type BT, a padding string PS, and the data D shall be - formatted into an octet string EB, the encryption block: - - EB = 00 || BT || PS || 00 || D - - The block type BT shall be a single octet indicating the structure of - the encryption block. For this version of the document it shall have - value 00, 01, or 02. For a private-key operation, the block type - shall be 00 or 01. For a public-key operation, it shall be 02. - - The padding string PS shall consist of k-3-||D|| octets. For block - type 00, the octets shall have value 00; for block type 01, they - shall have value FF; and for block type 02, they shall be - pseudorandomly generated and nonzero. This makes the length of the - encryption block EB equal to k. */ - - // build the encryption block - eb.putByte(0x00); - eb.putByte(bt); - - // create the padding - var padNum = k - 3 - m.length; - var padByte; - // private key op - if(bt === 0x00 || bt === 0x01) { - padByte = (bt === 0x00) ? 0x00 : 0xFF; - for(var i = 0; i < padNum; ++i) { - eb.putByte(padByte); - } - } else { - // public key op - // pad with random non-zero values - while(padNum > 0) { - var numZeros = 0; - var padBytes = forge$k.random.getBytes(padNum); - for(var i = 0; i < padNum; ++i) { - padByte = padBytes.charCodeAt(i); - if(padByte === 0) { - ++numZeros; - } else { - eb.putByte(padByte); - } - } - padNum = numZeros; - } - } - - // zero followed by message - eb.putByte(0x00); - eb.putBytes(m); - - return eb; -} - -/** - * Decodes a message using PKCS#1 v1.5 padding. - * - * @param em the message to decode. - * @param key the RSA key to use. - * @param pub true if the key is a public key, false if it is private. - * @param ml the message length, if specified. - * - * @return the decoded bytes. - */ -function _decodePkcs1_v1_5(em, key, pub, ml) { - // get the length of the modulus in bytes - var k = Math.ceil(key.n.bitLength() / 8); - - /* It is an error if any of the following conditions occurs: - - 1. The encryption block EB cannot be parsed unambiguously. - 2. The padding string PS consists of fewer than eight octets - or is inconsisent with the block type BT. - 3. The decryption process is a public-key operation and the block - type BT is not 00 or 01, or the decryption process is a - private-key operation and the block type is not 02. - */ - - // parse the encryption block - var eb = forge$k.util.createBuffer(em); - var first = eb.getByte(); - var bt = eb.getByte(); - if(first !== 0x00 || - (pub && bt !== 0x00 && bt !== 0x01) || - (!pub && bt != 0x02) || - (pub && bt === 0x00 && typeof(ml) === 'undefined')) { - throw new Error('Encryption block is invalid.'); - } - - var padNum = 0; - if(bt === 0x00) { - // check all padding bytes for 0x00 - padNum = k - 3 - ml; - for(var i = 0; i < padNum; ++i) { - if(eb.getByte() !== 0x00) { - throw new Error('Encryption block is invalid.'); - } - } - } else if(bt === 0x01) { - // find the first byte that isn't 0xFF, should be after all padding - padNum = 0; - while(eb.length() > 1) { - if(eb.getByte() !== 0xFF) { - --eb.read; - break; - } - ++padNum; - } - } else if(bt === 0x02) { - // look for 0x00 byte - padNum = 0; - while(eb.length() > 1) { - if(eb.getByte() === 0x00) { - --eb.read; - break; - } - ++padNum; - } - } - - // zero must be 0x00 and padNum must be (k - 3 - message length) - var zero = eb.getByte(); - if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) { - throw new Error('Encryption block is invalid.'); - } - - return eb.getBytes(); -} - -/** - * Runs the key-generation algorithm asynchronously, either in the background - * via Web Workers, or using the main thread and setImmediate. - * - * @param state the key-pair generation state. - * @param [options] options for key-pair generation: - * workerScript the worker script URL. - * workers the number of web workers (if supported) to use, - * (default: 2, -1 to use estimated cores minus one). - * workLoad the size of the work load, ie: number of possible prime - * numbers for each web worker to check per work assignment, - * (default: 100). - * @param callback(err, keypair) called once the operation completes. - */ -function _generateKeyPair(state, options, callback) { - if(typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - var opts = { - algorithm: { - name: options.algorithm || 'PRIMEINC', - options: { - workers: options.workers || 2, - workLoad: options.workLoad || 100, - workerScript: options.workerScript - } - } - }; - if('prng' in options) { - opts.prng = options.prng; - } - - generate(); - - function generate() { - // find p and then q (done in series to simplify) - getPrime(state.pBits, function(err, num) { - if(err) { - return callback(err); - } - state.p = num; - if(state.q !== null) { - return finish(err, state.q); - } - getPrime(state.qBits, finish); - }); - } - - function getPrime(bits, callback) { - forge$k.prime.generateProbablePrime(bits, opts, callback); - } - - function finish(err, num) { - if(err) { - return callback(err); - } - - // set q - state.q = num; - - // ensure p is larger than q (swap them if not) - if(state.p.compareTo(state.q) < 0) { - var tmp = state.p; - state.p = state.q; - state.q = tmp; - } - - // ensure p is coprime with e - if(state.p.subtract(BigInteger$1.ONE).gcd(state.e) - .compareTo(BigInteger$1.ONE) !== 0) { - state.p = null; - generate(); - return; - } - - // ensure q is coprime with e - if(state.q.subtract(BigInteger$1.ONE).gcd(state.e) - .compareTo(BigInteger$1.ONE) !== 0) { - state.q = null; - getPrime(state.qBits, finish); - return; - } - - // compute phi: (p - 1)(q - 1) (Euler's totient function) - state.p1 = state.p.subtract(BigInteger$1.ONE); - state.q1 = state.q.subtract(BigInteger$1.ONE); - state.phi = state.p1.multiply(state.q1); - - // ensure e and phi are coprime - if(state.phi.gcd(state.e).compareTo(BigInteger$1.ONE) !== 0) { - // phi and e aren't coprime, so generate a new p and q - state.p = state.q = null; - generate(); - return; - } - - // create n, ensure n is has the right number of bits - state.n = state.p.multiply(state.q); - if(state.n.bitLength() !== state.bits) { - // failed, get new q - state.q = null; - getPrime(state.qBits, finish); - return; - } - - // set keys - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki$4.rsa.setPrivateKey( - state.n, state.e, d, state.p, state.q, - d.mod(state.p1), d.mod(state.q1), - state.q.modInverse(state.p)), - publicKey: pki$4.rsa.setPublicKey(state.n, state.e) - }; - - callback(null, state.keys); - } -} - -/** - * Converts a positive BigInteger into 2's-complement big-endian bytes. - * - * @param b the big integer to convert. - * - * @return the bytes. - */ -function _bnToBytes(b) { - // prepend 0x00 if first byte >= 0x80 - var hex = b.toString(16); - if(hex[0] >= '8') { - hex = '00' + hex; - } - var bytes = forge$k.util.hexToBytes(hex); - - // ensure integer is minimally-encoded - if(bytes.length > 1 && - // leading 0x00 for positive integer - ((bytes.charCodeAt(0) === 0 && - (bytes.charCodeAt(1) & 0x80) === 0) || - // leading 0xFF for negative integer - (bytes.charCodeAt(0) === 0xFF && - (bytes.charCodeAt(1) & 0x80) === 0x80))) { - return bytes.substr(1); - } - return bytes; -} - -/** - * Returns the required number of Miller-Rabin tests to generate a - * prime with an error probability of (1/2)^80. - * - * See Handbook of Applied Cryptography Chapter 4, Table 4.4. - * - * @param bits the bit size. - * - * @return the required number of iterations. - */ -function _getMillerRabinTests(bits) { - if(bits <= 100) return 27; - if(bits <= 150) return 18; - if(bits <= 200) return 15; - if(bits <= 250) return 12; - if(bits <= 300) return 9; - if(bits <= 350) return 8; - if(bits <= 400) return 7; - if(bits <= 500) return 6; - if(bits <= 600) return 5; - if(bits <= 800) return 4; - if(bits <= 1250) return 3; - return 2; -} - -/** - * Performs feature detection on the Node crypto interface. - * - * @param fn the feature (function) to detect. - * - * @return true if detected, false if not. - */ -function _detectNodeCrypto(fn) { - return forge$k.util.isNodejs && typeof _crypto[fn] === 'function'; -} - -/** - * Performs feature detection on the SubtleCrypto interface. - * - * @param fn the feature (function) to detect. - * - * @return true if detected, false if not. - */ -function _detectSubtleCrypto(fn) { - return (typeof util.globalScope !== 'undefined' && - typeof util.globalScope.crypto === 'object' && - typeof util.globalScope.crypto.subtle === 'object' && - typeof util.globalScope.crypto.subtle[fn] === 'function'); -} - -/** - * Performs feature detection on the deprecated Microsoft Internet Explorer - * outdated SubtleCrypto interface. This function should only be used after - * checking for the modern, standard SubtleCrypto interface. - * - * @param fn the feature (function) to detect. - * - * @return true if detected, false if not. - */ -function _detectSubtleMsCrypto(fn) { - return (typeof util.globalScope !== 'undefined' && - typeof util.globalScope.msCrypto === 'object' && - typeof util.globalScope.msCrypto.subtle === 'object' && - typeof util.globalScope.msCrypto.subtle[fn] === 'function'); -} - -function _intToUint8Array(x) { - var bytes = forge$k.util.hexToBytes(x.toString(16)); - var buffer = new Uint8Array(bytes.length); - for(var i = 0; i < bytes.length; ++i) { - buffer[i] = bytes.charCodeAt(i); - } - return buffer; -} - -/** - * Password-based encryption functions. - * - * @author Dave Longley - * @author Stefan Siegl - * - * Copyright (c) 2010-2013 Digital Bazaar, Inc. - * Copyright (c) 2012 Stefan Siegl - * - * An EncryptedPrivateKeyInfo: - * - * EncryptedPrivateKeyInfo ::= SEQUENCE { - * encryptionAlgorithm EncryptionAlgorithmIdentifier, - * encryptedData EncryptedData } - * - * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier - * - * EncryptedData ::= OCTET STRING - */ - -var forge$j = forge$F; - -// shortcut for asn.1 API -var asn1$6 = forge$j.asn1; - -/* Password-based encryption implementation. */ -var pki$3 = forge$j.pki = forge$j.pki || {}; -pki$3.pbe = forge$j.pbe = forge$j.pbe || {}; -var oids$1 = pki$3.oids; - -// validator for an EncryptedPrivateKeyInfo structure -// Note: Currently only works w/algorithm params -var encryptedPrivateKeyValidator = { - name: 'EncryptedPrivateKeyInfo', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.OID, - constructed: false, - capture: 'encryptionOid' - }, { - name: 'AlgorithmIdentifier.parameters', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.SEQUENCE, - constructed: true, - captureAsn1: 'encryptionParams' - }] - }, { - // encryptedData - name: 'EncryptedPrivateKeyInfo.encryptedData', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.OCTETSTRING, - constructed: false, - capture: 'encryptedData' - }] -}; - -// validator for a PBES2Algorithms structure -// Note: Currently only works w/PBKDF2 + AES encryption schemes -var PBES2AlgorithmsValidator = { - name: 'PBES2Algorithms', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PBES2Algorithms.keyDerivationFunc', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PBES2Algorithms.keyDerivationFunc.oid', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.OID, - constructed: false, - capture: 'kdfOid' - }, { - name: 'PBES2Algorithms.params', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PBES2Algorithms.params.salt', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.OCTETSTRING, - constructed: false, - capture: 'kdfSalt' - }, { - name: 'PBES2Algorithms.params.iterationCount', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.INTEGER, - constructed: false, - capture: 'kdfIterationCount' - }, { - name: 'PBES2Algorithms.params.keyLength', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.INTEGER, - constructed: false, - optional: true, - capture: 'keyLength' - }, { - // prf - name: 'PBES2Algorithms.params.prf', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: 'PBES2Algorithms.params.prf.algorithm', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.OID, - constructed: false, - capture: 'prfOid' - }] - }] - }] - }, { - name: 'PBES2Algorithms.encryptionScheme', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PBES2Algorithms.encryptionScheme.oid', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.OID, - constructed: false, - capture: 'encOid' - }, { - name: 'PBES2Algorithms.encryptionScheme.iv', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.OCTETSTRING, - constructed: false, - capture: 'encIv' - }] - }] -}; - -var pkcs12PbeParamsValidator = { - name: 'pkcs-12PbeParams', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'pkcs-12PbeParams.salt', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.OCTETSTRING, - constructed: false, - capture: 'salt' - }, { - name: 'pkcs-12PbeParams.iterations', - tagClass: asn1$6.Class.UNIVERSAL, - type: asn1$6.Type.INTEGER, - constructed: false, - capture: 'iterations' - }] -}; - -/** - * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo. - * - * PBES2Algorithms ALGORITHM-IDENTIFIER ::= - * { {PBES2-params IDENTIFIED BY id-PBES2}, ...} - * - * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} - * - * PBES2-params ::= SEQUENCE { - * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}}, - * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} - * } - * - * PBES2-KDFs ALGORITHM-IDENTIFIER ::= - * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... } - * - * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... } - * - * PBKDF2-params ::= SEQUENCE { - * salt CHOICE { - * specified OCTET STRING, - * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}} - * }, - * iterationCount INTEGER (1..MAX), - * keyLength INTEGER (1..MAX) OPTIONAL, - * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 - * } - * - * @param obj the ASN.1 PrivateKeyInfo object. - * @param password the password to encrypt with. - * @param options: - * algorithm the encryption algorithm to use - * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. - * count the iteration count to use. - * saltSize the salt size to use. - * prfAlgorithm the PRF message digest algorithm to use - * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512') - * - * @return the ASN.1 EncryptedPrivateKeyInfo. - */ -pki$3.encryptPrivateKeyInfo = function(obj, password, options) { - // set default options - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || 'aes128'; - options.prfAlgorithm = options.prfAlgorithm || 'sha1'; - - // generate PBE params - var salt = forge$j.random.getBytesSync(options.saltSize); - var count = options.count; - var countBytes = asn1$6.integerToDer(count); - var dkLen; - var encryptionAlgorithm; - var encryptedData; - if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') { - // do PBES2 - var ivLen, encOid, cipherFn; - switch(options.algorithm) { - case 'aes128': - dkLen = 16; - ivLen = 16; - encOid = oids$1['aes128-CBC']; - cipherFn = forge$j.aes.createEncryptionCipher; - break; - case 'aes192': - dkLen = 24; - ivLen = 16; - encOid = oids$1['aes192-CBC']; - cipherFn = forge$j.aes.createEncryptionCipher; - break; - case 'aes256': - dkLen = 32; - ivLen = 16; - encOid = oids$1['aes256-CBC']; - cipherFn = forge$j.aes.createEncryptionCipher; - break; - case 'des': - dkLen = 8; - ivLen = 8; - encOid = oids$1['desCBC']; - cipherFn = forge$j.des.createEncryptionCipher; - break; - default: - var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); - error.algorithm = options.algorithm; - throw error; - } - - // get PRF message digest - var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase(); - var md = prfAlgorithmToMessageDigest(prfAlgorithm); - - // encrypt private key using pbe SHA-1 and AES/DES - var dk = forge$j.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = forge$j.random.getBytesSync(ivLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1$6.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - - // get PBKDF2-params - var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); - - encryptionAlgorithm = asn1$6.create( - asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, - asn1$6.oidToDer(oids$1['pkcs5PBES2']).getBytes()), - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ - // keyDerivationFunc - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, - asn1$6.oidToDer(oids$1['pkcs5PBKDF2']).getBytes()), - // PBKDF2-params - params - ]), - // encryptionScheme - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, - asn1$6.oidToDer(encOid).getBytes()), - // iv - asn1$6.create( - asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, iv) - ]) - ]) - ]); - } else if(options.algorithm === '3des') { - // Do PKCS12 PBE - dkLen = 24; - - var saltBytes = new forge$j.util.ByteBuffer(salt); - var dk = pki$3.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); - var iv = pki$3.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); - var cipher = forge$j.des.createEncryptionCipher(dk); - cipher.start(iv); - cipher.update(asn1$6.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - - encryptionAlgorithm = asn1$6.create( - asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, - asn1$6.oidToDer(oids$1['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()), - // pkcs-12PbeParams - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ - // salt - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, salt), - // iteration count - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.INTEGER, false, - countBytes.getBytes()) - ]) - ]); - } else { - var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); - error.algorithm = options.algorithm; - throw error; - } - - // EncryptedPrivateKeyInfo - var rval = asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ - // encryptionAlgorithm - encryptionAlgorithm, - // encryptedData - asn1$6.create( - asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, encryptedData) - ]); - return rval; -}; - -/** - * Decrypts a ASN.1 PrivateKeyInfo object. - * - * @param obj the ASN.1 EncryptedPrivateKeyInfo object. - * @param password the password to decrypt with. - * - * @return the ASN.1 PrivateKeyInfo on success, null on failure. - */ -pki$3.decryptPrivateKeyInfo = function(obj, password) { - var rval = null; - - // get PBE params - var capture = {}; - var errors = []; - if(!asn1$6.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { - var error = new Error('Cannot read encrypted private key. ' + - 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); - error.errors = errors; - throw error; - } - - // get cipher - var oid = asn1$6.derToOid(capture.encryptionOid); - var cipher = pki$3.pbe.getCipher(oid, capture.encryptionParams, password); - - // get encrypted data - var encrypted = forge$j.util.createBuffer(capture.encryptedData); - - cipher.update(encrypted); - if(cipher.finish()) { - rval = asn1$6.fromDer(cipher.output); - } - - return rval; -}; - -/** - * Converts a EncryptedPrivateKeyInfo to PEM format. - * - * @param epki the EncryptedPrivateKeyInfo. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted encrypted private key. - */ -pki$3.encryptedPrivateKeyToPem = function(epki, maxline) { - // convert to DER, then PEM-encode - var msg = { - type: 'ENCRYPTED PRIVATE KEY', - body: asn1$6.toDer(epki).getBytes() - }; - return forge$j.pem.encode(msg, {maxline: maxline}); -}; - -/** - * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption - * is not performed. - * - * @param pem the EncryptedPrivateKeyInfo in PEM-format. - * - * @return the ASN.1 EncryptedPrivateKeyInfo. - */ -pki$3.encryptedPrivateKeyFromPem = function(pem) { - var msg = forge$j.pem.decode(pem)[0]; - - if(msg.type !== 'ENCRYPTED PRIVATE KEY') { - var error = new Error('Could not convert encrypted private key from PEM; ' + - 'PEM header type is "ENCRYPTED PRIVATE KEY".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert encrypted private key from PEM; ' + - 'PEM is encrypted.'); - } - - // convert DER to ASN.1 object - return asn1$6.fromDer(msg.body); -}; - -/** - * Encrypts an RSA private key. By default, the key will be wrapped in - * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo. - * This is the standard, preferred way to encrypt a private key. - * - * To produce a non-standard PEM-encrypted private key that uses encapsulated - * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL - * private key encryption), set the 'legacy' option to true. Note: Using this - * option will cause the iteration count to be forced to 1. - * - * Note: The 'des' algorithm is supported, but it is not considered to be - * secure because it only uses a single 56-bit key. If possible, it is highly - * recommended that a different algorithm be used. - * - * @param rsaKey the RSA key to encrypt. - * @param password the password to use. - * @param options: - * algorithm: the encryption algorithm to use - * ('aes128', 'aes192', 'aes256', '3des', 'des'). - * count: the iteration count to use. - * saltSize: the salt size to use. - * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated - * headers (DEK-Info) private key. - * - * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo. - */ -pki$3.encryptRsaPrivateKey = function(rsaKey, password, options) { - // standard PKCS#8 - options = options || {}; - if(!options.legacy) { - // encrypt PrivateKeyInfo - var rval = pki$3.wrapRsaPrivateKey(pki$3.privateKeyToAsn1(rsaKey)); - rval = pki$3.encryptPrivateKeyInfo(rval, password, options); - return pki$3.encryptedPrivateKeyToPem(rval); - } - - // legacy non-PKCS#8 - var algorithm; - var iv; - var dkLen; - var cipherFn; - switch(options.algorithm) { - case 'aes128': - algorithm = 'AES-128-CBC'; - dkLen = 16; - iv = forge$j.random.getBytesSync(16); - cipherFn = forge$j.aes.createEncryptionCipher; - break; - case 'aes192': - algorithm = 'AES-192-CBC'; - dkLen = 24; - iv = forge$j.random.getBytesSync(16); - cipherFn = forge$j.aes.createEncryptionCipher; - break; - case 'aes256': - algorithm = 'AES-256-CBC'; - dkLen = 32; - iv = forge$j.random.getBytesSync(16); - cipherFn = forge$j.aes.createEncryptionCipher; - break; - case '3des': - algorithm = 'DES-EDE3-CBC'; - dkLen = 24; - iv = forge$j.random.getBytesSync(8); - cipherFn = forge$j.des.createEncryptionCipher; - break; - case 'des': - algorithm = 'DES-CBC'; - dkLen = 8; - iv = forge$j.random.getBytesSync(8); - cipherFn = forge$j.des.createEncryptionCipher; - break; - default: - var error = new Error('Could not encrypt RSA private key; unsupported ' + - 'encryption algorithm "' + options.algorithm + '".'); - error.algorithm = options.algorithm; - throw error; - } - - // encrypt private key using OpenSSL legacy key derivation - var dk = forge$j.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1$6.toDer(pki$3.privateKeyToAsn1(rsaKey))); - cipher.finish(); - - var msg = { - type: 'RSA PRIVATE KEY', - procType: { - version: '4', - type: 'ENCRYPTED' - }, - dekInfo: { - algorithm: algorithm, - parameters: forge$j.util.bytesToHex(iv).toUpperCase() - }, - body: cipher.output.getBytes() - }; - return forge$j.pem.encode(msg); -}; - -/** - * Decrypts an RSA private key. - * - * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt. - * @param password the password to use. - * - * @return the RSA key on success, null on failure. - */ -pki$3.decryptRsaPrivateKey = function(pem, password) { - var rval = null; - - var msg = forge$j.pem.decode(pem)[0]; - - if(msg.type !== 'ENCRYPTED PRIVATE KEY' && - msg.type !== 'PRIVATE KEY' && - msg.type !== 'RSA PRIVATE KEY') { - var error = new Error('Could not convert private key from PEM; PEM header type ' + - 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); - error.headerType = error; - throw error; - } - - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - var dkLen; - var cipherFn; - switch(msg.dekInfo.algorithm) { - case 'DES-CBC': - dkLen = 8; - cipherFn = forge$j.des.createDecryptionCipher; - break; - case 'DES-EDE3-CBC': - dkLen = 24; - cipherFn = forge$j.des.createDecryptionCipher; - break; - case 'AES-128-CBC': - dkLen = 16; - cipherFn = forge$j.aes.createDecryptionCipher; - break; - case 'AES-192-CBC': - dkLen = 24; - cipherFn = forge$j.aes.createDecryptionCipher; - break; - case 'AES-256-CBC': - dkLen = 32; - cipherFn = forge$j.aes.createDecryptionCipher; - break; - case 'RC2-40-CBC': - dkLen = 5; - cipherFn = function(key) { - return forge$j.rc2.createDecryptionCipher(key, 40); - }; - break; - case 'RC2-64-CBC': - dkLen = 8; - cipherFn = function(key) { - return forge$j.rc2.createDecryptionCipher(key, 64); - }; - break; - case 'RC2-128-CBC': - dkLen = 16; - cipherFn = function(key) { - return forge$j.rc2.createDecryptionCipher(key, 128); - }; - break; - default: - var error = new Error('Could not decrypt private key; unsupported ' + - 'encryption algorithm "' + msg.dekInfo.algorithm + '".'); - error.algorithm = msg.dekInfo.algorithm; - throw error; - } - - // use OpenSSL legacy key derivation - var iv = forge$j.util.hexToBytes(msg.dekInfo.parameters); - var dk = forge$j.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(forge$j.util.createBuffer(msg.body)); - if(cipher.finish()) { - rval = cipher.output.getBytes(); - } else { - return rval; - } - } else { - rval = msg.body; - } - - if(msg.type === 'ENCRYPTED PRIVATE KEY') { - rval = pki$3.decryptPrivateKeyInfo(asn1$6.fromDer(rval), password); - } else { - // decryption already performed above - rval = asn1$6.fromDer(rval); - } - - if(rval !== null) { - rval = pki$3.privateKeyFromAsn1(rval); - } - - return rval; -}; - -/** - * Derives a PKCS#12 key. - * - * @param password the password to derive the key material from, null or - * undefined for none. - * @param salt the salt, as a ByteBuffer, to use. - * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). - * @param iter the iteration count. - * @param n the number of bytes to derive from the password. - * @param md the message digest to use, defaults to SHA-1. - * - * @return a ByteBuffer with the bytes derived from the password. - */ -pki$3.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { - var j, l; - - if(typeof md === 'undefined' || md === null) { - if(!('sha1' in forge$j.md)) { - throw new Error('"sha1" hash algorithm unavailable.'); - } - md = forge$j.md.sha1.create(); - } - - var u = md.digestLength; - var v = md.blockLength; - var result = new forge$j.util.ByteBuffer(); - - /* Convert password to Unicode byte buffer + trailing 0-byte. */ - var passBuf = new forge$j.util.ByteBuffer(); - if(password !== null && password !== undefined) { - for(l = 0; l < password.length; l++) { - passBuf.putInt16(password.charCodeAt(l)); - } - passBuf.putInt16(0); - } - - /* Length of salt and password in BYTES. */ - var p = passBuf.length(); - var s = salt.length(); - - /* 1. Construct a string, D (the "diversifier"), by concatenating - v copies of ID. */ - var D = new forge$j.util.ByteBuffer(); - D.fillWithByte(id, v); - - /* 2. Concatenate copies of the salt together to create a string S of length - v * ceil(s / v) bytes (the final copy of the salt may be trunacted - to create S). - Note that if the salt is the empty string, then so is S. */ - var Slen = v * Math.ceil(s / v); - var S = new forge$j.util.ByteBuffer(); - for(l = 0; l < Slen; l++) { - S.putByte(salt.at(l % s)); - } - - /* 3. Concatenate copies of the password together to create a string P of - length v * ceil(p / v) bytes (the final copy of the password may be - truncated to create P). - Note that if the password is the empty string, then so is P. */ - var Plen = v * Math.ceil(p / v); - var P = new forge$j.util.ByteBuffer(); - for(l = 0; l < Plen; l++) { - P.putByte(passBuf.at(l % p)); - } - - /* 4. Set I=S||P to be the concatenation of S and P. */ - var I = S; - I.putBuffer(P); - - /* 5. Set c=ceil(n / u). */ - var c = Math.ceil(n / u); - - /* 6. For i=1, 2, ..., c, do the following: */ - for(var i = 1; i <= c; i++) { - /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */ - var buf = new forge$j.util.ByteBuffer(); - buf.putBytes(D.bytes()); - buf.putBytes(I.bytes()); - for(var round = 0; round < iter; round++) { - md.start(); - md.update(buf.getBytes()); - buf = md.digest(); - } - - /* b) Concatenate copies of Ai to create a string B of length v bytes (the - final copy of Ai may be truncated to create B). */ - var B = new forge$j.util.ByteBuffer(); - for(l = 0; l < v; l++) { - B.putByte(buf.at(l % u)); - } - - /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks, - where k=ceil(s / v) + ceil(p / v), modify I by setting - Ij=(Ij+B+1) mod 2v for each j. */ - var k = Math.ceil(s / v) + Math.ceil(p / v); - var Inew = new forge$j.util.ByteBuffer(); - for(j = 0; j < k; j++) { - var chunk = new forge$j.util.ByteBuffer(I.getBytes(v)); - var x = 0x1ff; - for(l = B.length() - 1; l >= 0; l--) { - x = x >> 8; - x += B.at(l) + chunk.at(l); - chunk.setAt(l, x & 0xff); - } - Inew.putBuffer(chunk); - } - I = Inew; - - /* Add Ai to A. */ - result.putBuffer(buf); - } - - result.truncate(result.length() - n); - return result; -}; - -/** - * Get new Forge cipher object instance. - * - * @param oid the OID (in string notation). - * @param params the ASN.1 params object. - * @param password the password to decrypt with. - * - * @return new cipher object instance. - */ -pki$3.pbe.getCipher = function(oid, params, password) { - switch(oid) { - case pki$3.oids['pkcs5PBES2']: - return pki$3.pbe.getCipherForPBES2(oid, params, password); - - case pki$3.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: - case pki$3.oids['pbewithSHAAnd40BitRC2-CBC']: - return pki$3.pbe.getCipherForPKCS12PBE(oid, params, password); - - default: - var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.'); - error.oid = oid; - error.supportedOids = [ - 'pkcs5PBES2', - 'pbeWithSHAAnd3-KeyTripleDES-CBC', - 'pbewithSHAAnd40BitRC2-CBC' - ]; - throw error; - } -}; - -/** - * Get new Forge cipher object instance according to PBES2 params block. - * - * The returned cipher instance is already started using the IV - * from PBES2 parameter block. - * - * @param oid the PKCS#5 PBKDF2 OID (in string notation). - * @param params the ASN.1 PBES2-params object. - * @param password the password to decrypt with. - * - * @return new cipher object instance. - */ -pki$3.pbe.getCipherForPBES2 = function(oid, params, password) { - // get PBE params - var capture = {}; - var errors = []; - if(!asn1$6.validate(params, PBES2AlgorithmsValidator, capture, errors)) { - var error = new Error('Cannot read password-based-encryption algorithm ' + - 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); - error.errors = errors; - throw error; - } - - // check oids - oid = asn1$6.derToOid(capture.kdfOid); - if(oid !== pki$3.oids['pkcs5PBKDF2']) { - var error = new Error('Cannot read encrypted private key. ' + - 'Unsupported key derivation function OID.'); - error.oid = oid; - error.supportedOids = ['pkcs5PBKDF2']; - throw error; - } - oid = asn1$6.derToOid(capture.encOid); - if(oid !== pki$3.oids['aes128-CBC'] && - oid !== pki$3.oids['aes192-CBC'] && - oid !== pki$3.oids['aes256-CBC'] && - oid !== pki$3.oids['des-EDE3-CBC'] && - oid !== pki$3.oids['desCBC']) { - var error = new Error('Cannot read encrypted private key. ' + - 'Unsupported encryption scheme OID.'); - error.oid = oid; - error.supportedOids = [ - 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC']; - throw error; - } - - // set PBE params - var salt = capture.kdfSalt; - var count = forge$j.util.createBuffer(capture.kdfIterationCount); - count = count.getInt(count.length() << 3); - var dkLen; - var cipherFn; - switch(pki$3.oids[oid]) { - case 'aes128-CBC': - dkLen = 16; - cipherFn = forge$j.aes.createDecryptionCipher; - break; - case 'aes192-CBC': - dkLen = 24; - cipherFn = forge$j.aes.createDecryptionCipher; - break; - case 'aes256-CBC': - dkLen = 32; - cipherFn = forge$j.aes.createDecryptionCipher; - break; - case 'des-EDE3-CBC': - dkLen = 24; - cipherFn = forge$j.des.createDecryptionCipher; - break; - case 'desCBC': - dkLen = 8; - cipherFn = forge$j.des.createDecryptionCipher; - break; - } - - // get PRF message digest - var md = prfOidToMessageDigest(capture.prfOid); - - // decrypt private key using pbe with chosen PRF and AES/DES - var dk = forge$j.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = capture.encIv; - var cipher = cipherFn(dk); - cipher.start(iv); - - return cipher; -}; - -/** - * Get new Forge cipher object instance for PKCS#12 PBE. - * - * The returned cipher instance is already started using the key & IV - * derived from the provided password and PKCS#12 PBE salt. - * - * @param oid The PKCS#12 PBE OID (in string notation). - * @param params The ASN.1 PKCS#12 PBE-params object. - * @param password The password to decrypt with. - * - * @return the new cipher object instance. - */ -pki$3.pbe.getCipherForPKCS12PBE = function(oid, params, password) { - // get PBE params - var capture = {}; - var errors = []; - if(!asn1$6.validate(params, pkcs12PbeParamsValidator, capture, errors)) { - var error = new Error('Cannot read password-based-encryption algorithm ' + - 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); - error.errors = errors; - throw error; - } - - var salt = forge$j.util.createBuffer(capture.salt); - var count = forge$j.util.createBuffer(capture.iterations); - count = count.getInt(count.length() << 3); - - var dkLen, dIvLen, cipherFn; - switch(oid) { - case pki$3.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: - dkLen = 24; - dIvLen = 8; - cipherFn = forge$j.des.startDecrypting; - break; - - case pki$3.oids['pbewithSHAAnd40BitRC2-CBC']: - dkLen = 5; - dIvLen = 8; - cipherFn = function(key, iv) { - var cipher = forge$j.rc2.createDecryptionCipher(key, 40); - cipher.start(iv, null); - return cipher; - }; - break; - - default: - var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.'); - error.oid = oid; - throw error; - } - - // get PRF message digest - var md = prfOidToMessageDigest(capture.prfOid); - var key = pki$3.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); - md.start(); - var iv = pki$3.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); - - return cipherFn(key, iv); -}; - -/** - * OpenSSL's legacy key derivation function. - * - * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html - * - * @param password the password to derive the key from. - * @param salt the salt to use, null for none. - * @param dkLen the number of bytes needed for the derived key. - * @param [options] the options to use: - * [md] an optional message digest object to use. - */ -pki$3.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { - if(typeof md === 'undefined' || md === null) { - if(!('md5' in forge$j.md)) { - throw new Error('"md5" hash algorithm unavailable.'); - } - md = forge$j.md.md5.create(); - } - if(salt === null) { - salt = ''; - } - var digests = [hash(md, password + salt)]; - for(var length = 16, i = 1; length < dkLen; ++i, length += 16) { - digests.push(hash(md, digests[i - 1] + password + salt)); - } - return digests.join('').substr(0, dkLen); -}; - -function hash(md, bytes) { - return md.start().update(bytes).digest().getBytes(); -} - -function prfOidToMessageDigest(prfOid) { - // get PRF algorithm, default to SHA-1 - var prfAlgorithm; - if(!prfOid) { - prfAlgorithm = 'hmacWithSHA1'; - } else { - prfAlgorithm = pki$3.oids[asn1$6.derToOid(prfOid)]; - if(!prfAlgorithm) { - var error = new Error('Unsupported PRF OID.'); - error.oid = prfOid; - error.supported = [ - 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', - 'hmacWithSHA512']; - throw error; - } - } - return prfAlgorithmToMessageDigest(prfAlgorithm); -} - -function prfAlgorithmToMessageDigest(prfAlgorithm) { - var factory = forge$j.md; - switch(prfAlgorithm) { - case 'hmacWithSHA224': - factory = forge$j.md.sha512; - case 'hmacWithSHA1': - case 'hmacWithSHA256': - case 'hmacWithSHA384': - case 'hmacWithSHA512': - prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); - break; - default: - var error = new Error('Unsupported PRF algorithm.'); - error.algorithm = prfAlgorithm; - error.supported = [ - 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', - 'hmacWithSHA512']; - throw error; - } - if(!factory || !(prfAlgorithm in factory)) { - throw new Error('Unknown hash algorithm: ' + prfAlgorithm); - } - return factory[prfAlgorithm].create(); -} - -function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { - var params = asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ - // salt - asn1$6.create( - asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, salt), - // iteration count - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.INTEGER, false, - countBytes.getBytes()) - ]); - // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm - if(prfAlgorithm !== 'hmacWithSHA1') { - params.value.push( - // key length - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.INTEGER, false, - forge$j.util.hexToBytes(dkLen.toString(16))), - // AlgorithmIdentifier - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [ - // algorithm - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false, - asn1$6.oidToDer(pki$3.oids[prfAlgorithm]).getBytes()), - // parameters (null) - asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.NULL, false, '') - ])); - } - return params; -} - -/** - * Javascript implementation of ASN.1 validators for PKCS#7 v1.5. - * - * @author Dave Longley - * @author Stefan Siegl - * - * Copyright (c) 2012-2015 Digital Bazaar, Inc. - * Copyright (c) 2012 Stefan Siegl - * - * The ASN.1 representation of PKCS#7 is as follows - * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt): - * - * A PKCS#7 message consists of a ContentInfo on root level, which may - * contain any number of further ContentInfo nested into it. - * - * ContentInfo ::= SEQUENCE { - * contentType ContentType, - * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL - * } - * - * ContentType ::= OBJECT IDENTIFIER - * - * EnvelopedData ::= SEQUENCE { - * version Version, - * recipientInfos RecipientInfos, - * encryptedContentInfo EncryptedContentInfo - * } - * - * EncryptedData ::= SEQUENCE { - * version Version, - * encryptedContentInfo EncryptedContentInfo - * } - * - * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2) - * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 } - * - * SignedData ::= SEQUENCE { - * version INTEGER, - * digestAlgorithms DigestAlgorithmIdentifiers, - * contentInfo ContentInfo, - * certificates [0] IMPLICIT Certificates OPTIONAL, - * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, - * signerInfos SignerInfos - * } - * - * SignerInfos ::= SET OF SignerInfo - * - * SignerInfo ::= SEQUENCE { - * version Version, - * issuerAndSerialNumber IssuerAndSerialNumber, - * digestAlgorithm DigestAlgorithmIdentifier, - * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, - * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, - * encryptedDigest EncryptedDigest, - * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL - * } - * - * EncryptedDigest ::= OCTET STRING - * - * Attributes ::= SET OF Attribute - * - * Attribute ::= SEQUENCE { - * attrType OBJECT IDENTIFIER, - * attrValues SET OF AttributeValue - * } - * - * AttributeValue ::= ANY - * - * Version ::= INTEGER - * - * RecipientInfos ::= SET OF RecipientInfo - * - * EncryptedContentInfo ::= SEQUENCE { - * contentType ContentType, - * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, - * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL - * } - * - * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier - * - * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters - * for the algorithm, if any. In the case of AES and DES3, there is only one, - * the IV. - * - * AlgorithmIdentifer ::= SEQUENCE { - * algorithm OBJECT IDENTIFIER, - * parameters ANY DEFINED BY algorithm OPTIONAL - * } - * - * EncryptedContent ::= OCTET STRING - * - * RecipientInfo ::= SEQUENCE { - * version Version, - * issuerAndSerialNumber IssuerAndSerialNumber, - * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier, - * encryptedKey EncryptedKey - * } - * - * IssuerAndSerialNumber ::= SEQUENCE { - * issuer Name, - * serialNumber CertificateSerialNumber - * } - * - * CertificateSerialNumber ::= INTEGER - * - * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier - * - * EncryptedKey ::= OCTET STRING - */ - -var forge$i = forge$F; - - - -// shortcut for ASN.1 API -var asn1$5 = forge$i.asn1; - -// shortcut for PKCS#7 API -var p7v = forge$i.pkcs7asn1 = forge$i.pkcs7asn1 || {}; -forge$i.pkcs7 = forge$i.pkcs7 || {}; -forge$i.pkcs7.asn1 = p7v; - -var contentInfoValidator$1 = { - name: 'ContentInfo', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'ContentInfo.ContentType', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.OID, - constructed: false, - capture: 'contentType' - }, { - name: 'ContentInfo.content', - tagClass: asn1$5.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - captureAsn1: 'content' - }] -}; -p7v.contentInfoValidator = contentInfoValidator$1; - -var encryptedContentInfoValidator = { - name: 'EncryptedContentInfo', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EncryptedContentInfo.contentType', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.OID, - constructed: false, - capture: 'contentType' - }, { - name: 'EncryptedContentInfo.contentEncryptionAlgorithm', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.OID, - constructed: false, - capture: 'encAlgorithm' - }, { - name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter', - tagClass: asn1$5.Class.UNIVERSAL, - captureAsn1: 'encParameter' - }] - }, { - name: 'EncryptedContentInfo.encryptedContent', - tagClass: asn1$5.Class.CONTEXT_SPECIFIC, - type: 0, - /* The PKCS#7 structure output by OpenSSL somewhat differs from what - * other implementations do generate. - * - * OpenSSL generates a structure like this: - * SEQUENCE { - * ... - * [0] - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * - * Whereas other implementations (and this PKCS#7 module) generate: - * SEQUENCE { - * ... - * [0] { - * OCTET STRING - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * } - * - * In order to support both, we just capture the context specific - * field here. The OCTET STRING bit is removed below. - */ - capture: 'encryptedContent', - captureAsn1: 'encryptedContentAsn1' - }] -}; - -p7v.envelopedDataValidator = { - name: 'EnvelopedData', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EnvelopedData.Version', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.INTEGER, - constructed: false, - capture: 'version' - }, { - name: 'EnvelopedData.RecipientInfos', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SET, - constructed: true, - captureAsn1: 'recipientInfos' - }].concat(encryptedContentInfoValidator) -}; - -p7v.encryptedDataValidator = { - name: 'EncryptedData', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'EncryptedData.Version', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.INTEGER, - constructed: false, - capture: 'version' - }].concat(encryptedContentInfoValidator) -}; - -var signerValidator = { - name: 'SignerInfo', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SignerInfo.version', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.INTEGER, - constructed: false - }, { - name: 'SignerInfo.issuerAndSerialNumber', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SignerInfo.issuerAndSerialNumber.issuer', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - captureAsn1: 'issuer' - }, { - name: 'SignerInfo.issuerAndSerialNumber.serialNumber', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.INTEGER, - constructed: false, - capture: 'serial' - }] - }, { - name: 'SignerInfo.digestAlgorithm', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SignerInfo.digestAlgorithm.algorithm', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.OID, - constructed: false, - capture: 'digestAlgorithm' - }, { - name: 'SignerInfo.digestAlgorithm.parameter', - tagClass: asn1$5.Class.UNIVERSAL, - constructed: false, - captureAsn1: 'digestParameter', - optional: true - }] - }, { - name: 'SignerInfo.authenticatedAttributes', - tagClass: asn1$5.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: 'authenticatedAttributes' - }, { - name: 'SignerInfo.digestEncryptionAlgorithm', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - capture: 'signatureAlgorithm' - }, { - name: 'SignerInfo.encryptedDigest', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.OCTETSTRING, - constructed: false, - capture: 'signature' - }, { - name: 'SignerInfo.unauthenticatedAttributes', - tagClass: asn1$5.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - capture: 'unauthenticatedAttributes' - }] -}; - -p7v.signedDataValidator = { - name: 'SignedData', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SignedData.Version', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.INTEGER, - constructed: false, - capture: 'version' - }, { - name: 'SignedData.DigestAlgorithms', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SET, - constructed: true, - captureAsn1: 'digestAlgorithms' - }, - contentInfoValidator$1, - { - name: 'SignedData.Certificates', - tagClass: asn1$5.Class.CONTEXT_SPECIFIC, - type: 0, - optional: true, - captureAsn1: 'certificates' - }, { - name: 'SignedData.CertificateRevocationLists', - tagClass: asn1$5.Class.CONTEXT_SPECIFIC, - type: 1, - optional: true, - captureAsn1: 'crls' - }, { - name: 'SignedData.SignerInfos', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SET, - capture: 'signerInfos', - optional: true, - value: [signerValidator] - }] -}; - -p7v.recipientInfoValidator = { - name: 'RecipientInfo', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'RecipientInfo.version', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.INTEGER, - constructed: false, - capture: 'version' - }, { - name: 'RecipientInfo.issuerAndSerial', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'RecipientInfo.issuerAndSerial.issuer', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - captureAsn1: 'issuer' - }, { - name: 'RecipientInfo.issuerAndSerial.serialNumber', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.INTEGER, - constructed: false, - capture: 'serial' - }] - }, { - name: 'RecipientInfo.keyEncryptionAlgorithm', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.OID, - constructed: false, - capture: 'encAlgorithm' - }, { - name: 'RecipientInfo.keyEncryptionAlgorithm.parameter', - tagClass: asn1$5.Class.UNIVERSAL, - constructed: false, - captureAsn1: 'encParameter' - }] - }, { - name: 'RecipientInfo.encryptedKey', - tagClass: asn1$5.Class.UNIVERSAL, - type: asn1$5.Type.OCTETSTRING, - constructed: false, - capture: 'encKey' - }] -}; - -/** - * Javascript implementation of mask generation function MGF1. - * - * @author Stefan Siegl - * @author Dave Longley - * - * Copyright (c) 2012 Stefan Siegl - * Copyright (c) 2014 Digital Bazaar, Inc. - */ - -var forge$h = forge$F; - - -forge$h.mgf = forge$h.mgf || {}; -var mgf1 = forge$h.mgf.mgf1 = forge$h.mgf1 = forge$h.mgf1 || {}; - -/** - * Creates a MGF1 mask generation function object. - * - * @param md the message digest API to use (eg: forge.md.sha1.create()). - * - * @return a mask generation function object. - */ -mgf1.create = function(md) { - var mgf = { - /** - * Generate mask of specified length. - * - * @param {String} seed The seed for mask generation. - * @param maskLen Number of bytes to generate. - * @return {String} The generated mask. - */ - generate: function(seed, maskLen) { - /* 2. Let T be the empty octet string. */ - var t = new forge$h.util.ByteBuffer(); - - /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */ - var len = Math.ceil(maskLen / md.digestLength); - for(var i = 0; i < len; i++) { - /* a. Convert counter to an octet string C of length 4 octets */ - var c = new forge$h.util.ByteBuffer(); - c.putInt32(i); - - /* b. Concatenate the hash of the seed mgfSeed and C to the octet - * string T: */ - md.start(); - md.update(seed + c.getBytes()); - t.putBuffer(md.digest()); - } - - /* Output the leading maskLen octets of T as the octet string mask. */ - t.truncate(t.length() - maskLen); - return t.getBytes(); - } - }; - - return mgf; -}; - -/** - * Node.js module for Forge mask generation functions. - * - * @author Stefan Siegl - * - * Copyright 2012 Stefan Siegl - */ - -var forge$g = forge$F; - - -forge$g.mgf = forge$g.mgf || {}; -forge$g.mgf.mgf1 = forge$g.mgf1; - -/** - * Javascript implementation of PKCS#1 PSS signature padding. - * - * @author Stefan Siegl - * - * Copyright (c) 2012 Stefan Siegl - */ - -var forge$f = forge$F; - - - -// shortcut for PSS API -var pss = forge$f.pss = forge$f.pss || {}; - -/** - * Creates a PSS signature scheme object. - * - * There are several ways to provide a salt for encoding: - * - * 1. Specify the saltLength only and the built-in PRNG will generate it. - * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that - * will be used. - * 3. Specify the salt itself as a forge.util.ByteBuffer. - * - * @param options the options to use: - * md the message digest object to use, a forge md instance. - * mgf the mask generation function to use, a forge mgf instance. - * [saltLength] the length of the salt in octets. - * [prng] the pseudo-random number generator to use to produce a salt. - * [salt] the salt to use when encoding. - * - * @return a signature scheme object. - */ -pss.create = function(options) { - // backwards compatibility w/legacy args: hash, mgf, sLen - if(arguments.length === 3) { - options = { - md: arguments[0], - mgf: arguments[1], - saltLength: arguments[2] - }; - } - - var hash = options.md; - var mgf = options.mgf; - var hLen = hash.digestLength; - - var salt_ = options.salt || null; - if(typeof salt_ === 'string') { - // assume binary-encoded string - salt_ = forge$f.util.createBuffer(salt_); - } - - var sLen; - if('saltLength' in options) { - sLen = options.saltLength; - } else if(salt_ !== null) { - sLen = salt_.length(); - } else { - throw new Error('Salt length not specified or specific salt not given.'); - } - - if(salt_ !== null && salt_.length() !== sLen) { - throw new Error('Given salt length does not match length of given salt.'); - } - - var prng = options.prng || forge$f.random; - - var pssobj = {}; - - /** - * Encodes a PSS signature. - * - * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1. - * - * @param md the message digest object with the hash to sign. - * @param modsBits the length of the RSA modulus in bits. - * - * @return the encoded message as a binary-encoded string of length - * ceil((modBits - 1) / 8). - */ - pssobj.encode = function(md, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - - /* 2. Let mHash = Hash(M), an octet string of length hLen. */ - var mHash = md.digest().getBytes(); - - /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */ - if(emLen < hLen + sLen + 2) { - throw new Error('Message is too long to encrypt.'); - } - - /* 4. Generate a random octet string salt of length sLen; if sLen = 0, - * then salt is the empty string. */ - var salt; - if(salt_ === null) { - salt = prng.getBytesSync(sLen); - } else { - salt = salt_.bytes(); - } - - /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */ - var m_ = new forge$f.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - - /* 6. Let H = Hash(M'), an octet string of length hLen. */ - hash.start(); - hash.update(m_.getBytes()); - var h = hash.digest().getBytes(); - - /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2 - * zero octets. The length of PS may be 0. */ - var ps = new forge$f.util.ByteBuffer(); - ps.fillWithByte(0, emLen - sLen - hLen - 2); - - /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length - * emLen - hLen - 1. */ - ps.putByte(0x01); - ps.putBytes(salt); - var db = ps.getBytes(); - - /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */ - var maskLen = emLen - hLen - 1; - var dbMask = mgf.generate(h, maskLen); - - /* 10. Let maskedDB = DB \xor dbMask. */ - var maskedDB = ''; - for(i = 0; i < maskLen; i++) { - maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } - - /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in - * maskedDB to zero. */ - var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; - maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + - maskedDB.substr(1); - - /* 12. Let EM = maskedDB || H || 0xbc. - * 13. Output EM. */ - return maskedDB + h + String.fromCharCode(0xbc); - }; - - /** - * Verifies a PSS signature. - * - * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2. - * - * @param mHash the message digest hash, as a binary-encoded string, to - * compare against the signature. - * @param em the encoded message, as a binary-encoded string - * (RSA decryption result). - * @param modsBits the length of the RSA modulus in bits. - * - * @return true if the signature was verified, false if not. - */ - pssobj.verify = function(mHash, em, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - - /* c. Convert the message representative m to an encoded message EM - * of length emLen = ceil((modBits - 1) / 8) octets, where modBits - * is the length in bits of the RSA modulus n */ - em = em.substr(-emLen); - - /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */ - if(emLen < hLen + sLen + 2) { - throw new Error('Inconsistent parameters to PSS signature verification.'); - } - - /* 4. If the rightmost octet of EM does not have hexadecimal value - * 0xbc, output "inconsistent" and stop. */ - if(em.charCodeAt(emLen - 1) !== 0xbc) { - throw new Error('Encoded message does not end in 0xBC.'); - } - - /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and - * let H be the next hLen octets. */ - var maskLen = emLen - hLen - 1; - var maskedDB = em.substr(0, maskLen); - var h = em.substr(maskLen, hLen); - - /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in - * maskedDB are not all equal to zero, output "inconsistent" and stop. */ - var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; - if((maskedDB.charCodeAt(0) & mask) !== 0) { - throw new Error('Bits beyond keysize not zero as expected.'); - } - - /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */ - var dbMask = mgf.generate(h, maskLen); - - /* 8. Let DB = maskedDB \xor dbMask. */ - var db = ''; - for(i = 0; i < maskLen; i++) { - db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } - - /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet - * in DB to zero. */ - db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); - - /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero - * or if the octet at position emLen - hLen - sLen - 1 (the leftmost - * position is "position 1") does not have hexadecimal value 0x01, - * output "inconsistent" and stop. */ - var checkLen = emLen - hLen - sLen - 2; - for(i = 0; i < checkLen; i++) { - if(db.charCodeAt(i) !== 0x00) { - throw new Error('Leftmost octets not zero as expected'); - } - } - - if(db.charCodeAt(checkLen) !== 0x01) { - throw new Error('Inconsistent PSS signature, 0x01 marker not found'); - } - - /* 11. Let salt be the last sLen octets of DB. */ - var salt = db.substr(-sLen); - - /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */ - var m_ = new forge$f.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - - /* 13. Let H' = Hash(M'), an octet string of length hLen. */ - hash.start(); - hash.update(m_.getBytes()); - var h_ = hash.digest().getBytes(); - - /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */ - return h === h_; - }; - - return pssobj; -}; - -/** - * Javascript implementation of X.509 and related components (such as - * Certification Signing Requests) of a Public Key Infrastructure. - * - * @author Dave Longley - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - * - * The ASN.1 representation of an X.509v3 certificate is as follows - * (see RFC 2459): - * - * Certificate ::= SEQUENCE { - * tbsCertificate TBSCertificate, - * signatureAlgorithm AlgorithmIdentifier, - * signatureValue BIT STRING - * } - * - * TBSCertificate ::= SEQUENCE { - * version [0] EXPLICIT Version DEFAULT v1, - * serialNumber CertificateSerialNumber, - * signature AlgorithmIdentifier, - * issuer Name, - * validity Validity, - * subject Name, - * subjectPublicKeyInfo SubjectPublicKeyInfo, - * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, - * -- If present, version shall be v2 or v3 - * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, - * -- If present, version shall be v2 or v3 - * extensions [3] EXPLICIT Extensions OPTIONAL - * -- If present, version shall be v3 - * } - * - * Version ::= INTEGER { v1(0), v2(1), v3(2) } - * - * CertificateSerialNumber ::= INTEGER - * - * Name ::= CHOICE { - * // only one possible choice for now - * RDNSequence - * } - * - * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName - * - * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue - * - * AttributeTypeAndValue ::= SEQUENCE { - * type AttributeType, - * value AttributeValue - * } - * AttributeType ::= OBJECT IDENTIFIER - * AttributeValue ::= ANY DEFINED BY AttributeType - * - * Validity ::= SEQUENCE { - * notBefore Time, - * notAfter Time - * } - * - * Time ::= CHOICE { - * utcTime UTCTime, - * generalTime GeneralizedTime - * } - * - * UniqueIdentifier ::= BIT STRING - * - * SubjectPublicKeyInfo ::= SEQUENCE { - * algorithm AlgorithmIdentifier, - * subjectPublicKey BIT STRING - * } - * - * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension - * - * Extension ::= SEQUENCE { - * extnID OBJECT IDENTIFIER, - * critical BOOLEAN DEFAULT FALSE, - * extnValue OCTET STRING - * } - * - * The only key algorithm currently supported for PKI is RSA. - * - * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055. - * - * PKCS#10 v1.7 describes certificate signing requests: - * - * CertificationRequestInfo: - * - * CertificationRequestInfo ::= SEQUENCE { - * version INTEGER { v1(0) } (v1,...), - * subject Name, - * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, - * attributes [0] Attributes{{ CRIAttributes }} - * } - * - * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }} - * - * CRIAttributes ATTRIBUTE ::= { - * ... -- add any locally defined attributes here -- } - * - * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { - * type ATTRIBUTE.&id({IOSet}), - * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type}) - * } - * - * CertificationRequest ::= SEQUENCE { - * certificationRequestInfo CertificationRequestInfo, - * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, - * signature BIT STRING - * } - */ - -var forge$e = forge$F; - - - - - - - - - - - -// shortcut for asn.1 API -var asn1$4 = forge$e.asn1; - -/* Public Key Infrastructure (PKI) implementation. */ -var pki$2 = forge$e.pki = forge$e.pki || {}; -var oids = pki$2.oids; - -// short name OID mappings -var _shortNames = {}; -_shortNames['CN'] = oids['commonName']; -_shortNames['commonName'] = 'CN'; -_shortNames['C'] = oids['countryName']; -_shortNames['countryName'] = 'C'; -_shortNames['L'] = oids['localityName']; -_shortNames['localityName'] = 'L'; -_shortNames['ST'] = oids['stateOrProvinceName']; -_shortNames['stateOrProvinceName'] = 'ST'; -_shortNames['O'] = oids['organizationName']; -_shortNames['organizationName'] = 'O'; -_shortNames['OU'] = oids['organizationalUnitName']; -_shortNames['organizationalUnitName'] = 'OU'; -_shortNames['E'] = oids['emailAddress']; -_shortNames['emailAddress'] = 'E'; - -// validator for an SubjectPublicKeyInfo structure -// Note: Currently only works with an RSA public key -var publicKeyValidator$1 = forge$e.pki.rsa.publicKeyValidator; - -// validator for an X.509v3 certificate -var x509CertificateValidator = { - name: 'Certificate', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'Certificate.TBSCertificate', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - captureAsn1: 'tbsCertificate', - value: [{ - name: 'Certificate.TBSCertificate.version', - tagClass: asn1$4.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - value: [{ - name: 'Certificate.TBSCertificate.version.integer', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.INTEGER, - constructed: false, - capture: 'certVersion' - }] - }, { - name: 'Certificate.TBSCertificate.serialNumber', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.INTEGER, - constructed: false, - capture: 'certSerialNumber' - }, { - name: 'Certificate.TBSCertificate.signature', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'Certificate.TBSCertificate.signature.algorithm', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.OID, - constructed: false, - capture: 'certinfoSignatureOid' - }, { - name: 'Certificate.TBSCertificate.signature.parameters', - tagClass: asn1$4.Class.UNIVERSAL, - optional: true, - captureAsn1: 'certinfoSignatureParams' - }] - }, { - name: 'Certificate.TBSCertificate.issuer', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - captureAsn1: 'certIssuer' - }, { - name: 'Certificate.TBSCertificate.validity', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - // Note: UTC and generalized times may both appear so the capture - // names are based on their detected order, the names used below - // are only for the common case, which validity time really means - // "notBefore" and which means "notAfter" will be determined by order - value: [{ - // notBefore (Time) (UTC time case) - name: 'Certificate.TBSCertificate.validity.notBefore (utc)', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.UTCTIME, - constructed: false, - optional: true, - capture: 'certValidity1UTCTime' - }, { - // notBefore (Time) (generalized time case) - name: 'Certificate.TBSCertificate.validity.notBefore (generalized)', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: 'certValidity2GeneralizedTime' - }, { - // notAfter (Time) (only UTC time is supported) - name: 'Certificate.TBSCertificate.validity.notAfter (utc)', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.UTCTIME, - constructed: false, - optional: true, - capture: 'certValidity3UTCTime' - }, { - // notAfter (Time) (only UTC time is supported) - name: 'Certificate.TBSCertificate.validity.notAfter (generalized)', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: 'certValidity4GeneralizedTime' - }] - }, { - // Name (subject) (RDNSequence) - name: 'Certificate.TBSCertificate.subject', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - captureAsn1: 'certSubject' - }, - // SubjectPublicKeyInfo - publicKeyValidator$1, - { - // issuerUniqueID (optional) - name: 'Certificate.TBSCertificate.issuerUniqueID', - tagClass: asn1$4.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - value: [{ - name: 'Certificate.TBSCertificate.issuerUniqueID.id', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: 'certIssuerUniqueId' - }] - }, { - // subjectUniqueID (optional) - name: 'Certificate.TBSCertificate.subjectUniqueID', - tagClass: asn1$4.Class.CONTEXT_SPECIFIC, - type: 2, - constructed: true, - optional: true, - value: [{ - name: 'Certificate.TBSCertificate.subjectUniqueID.id', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: 'certSubjectUniqueId' - }] - }, { - // Extensions (optional) - name: 'Certificate.TBSCertificate.extensions', - tagClass: asn1$4.Class.CONTEXT_SPECIFIC, - type: 3, - constructed: true, - captureAsn1: 'certExtensions', - optional: true - }] - }, { - // AlgorithmIdentifier (signature algorithm) - name: 'Certificate.signatureAlgorithm', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: 'Certificate.signatureAlgorithm.algorithm', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.OID, - constructed: false, - capture: 'certSignatureOid' - }, { - name: 'Certificate.TBSCertificate.signature.parameters', - tagClass: asn1$4.Class.UNIVERSAL, - optional: true, - captureAsn1: 'certSignatureParams' - }] - }, { - // SignatureValue - name: 'Certificate.signatureValue', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.BITSTRING, - constructed: false, - captureBitStringValue: 'certSignature' - }] -}; - -var rsassaPssParameterValidator = { - name: 'rsapss', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'rsapss.hashAlgorithm', - tagClass: asn1$4.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - value: [{ - name: 'rsapss.hashAlgorithm.AlgorithmIdentifier', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.OID, - constructed: false, - capture: 'hashOid' - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }, { - name: 'rsapss.maskGenAlgorithm', - tagClass: asn1$4.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - value: [{ - name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.OID, - constructed: false, - capture: 'maskGenOid' - }, { - name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.OID, - constructed: false, - capture: 'maskGenHashOid' - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }] - }, { - name: 'rsapss.saltLength', - tagClass: asn1$4.Class.CONTEXT_SPECIFIC, - type: 2, - optional: true, - value: [{ - name: 'rsapss.saltLength.saltLength', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Class.INTEGER, - constructed: false, - capture: 'saltLength' - }] - }, { - name: 'rsapss.trailerField', - tagClass: asn1$4.Class.CONTEXT_SPECIFIC, - type: 3, - optional: true, - value: [{ - name: 'rsapss.trailer.trailer', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Class.INTEGER, - constructed: false, - capture: 'trailer' - }] - }] -}; - -// validator for a CertificationRequestInfo structure -var certificationRequestInfoValidator = { - name: 'CertificationRequestInfo', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - captureAsn1: 'certificationRequestInfo', - value: [{ - name: 'CertificationRequestInfo.integer', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.INTEGER, - constructed: false, - capture: 'certificationRequestInfoVersion' - }, { - // Name (subject) (RDNSequence) - name: 'CertificationRequestInfo.subject', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - captureAsn1: 'certificationRequestInfoSubject' - }, - // SubjectPublicKeyInfo - publicKeyValidator$1, - { - name: 'CertificationRequestInfo.attributes', - tagClass: asn1$4.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: 'certificationRequestInfoAttributes', - value: [{ - name: 'CertificationRequestInfo.attributes', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'CertificationRequestInfo.attributes.type', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.OID, - constructed: false - }, { - name: 'CertificationRequestInfo.attributes.value', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SET, - constructed: true - }] - }] - }] -}; - -// validator for a CertificationRequest structure -var certificationRequestValidator = { - name: 'CertificationRequest', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - captureAsn1: 'csr', - value: [ - certificationRequestInfoValidator, { - // AlgorithmIdentifier (signature algorithm) - name: 'CertificationRequest.signatureAlgorithm', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: 'CertificationRequest.signatureAlgorithm.algorithm', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.OID, - constructed: false, - capture: 'csrSignatureOid' - }, { - name: 'CertificationRequest.signatureAlgorithm.parameters', - tagClass: asn1$4.Class.UNIVERSAL, - optional: true, - captureAsn1: 'csrSignatureParams' - }] - }, { - // signature - name: 'CertificationRequest.signature', - tagClass: asn1$4.Class.UNIVERSAL, - type: asn1$4.Type.BITSTRING, - constructed: false, - captureBitStringValue: 'csrSignature' - } - ] -}; - -/** - * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName - * sets into an array with objects that have type and value properties. - * - * @param rdn the RDNSequence to convert. - * @param md a message digest to append type and value to if provided. - */ -pki$2.RDNAttributesAsArray = function(rdn, md) { - var rval = []; - - // each value in 'rdn' in is a SET of RelativeDistinguishedName - var set, attr, obj; - for(var si = 0; si < rdn.value.length; ++si) { - // get the RelativeDistinguishedName set - set = rdn.value[si]; - - // each value in the SET is an AttributeTypeAndValue sequence - // containing first a type (an OID) and second a value (defined by - // the OID) - for(var i = 0; i < set.value.length; ++i) { - obj = {}; - attr = set.value[i]; - obj.type = asn1$4.derToOid(attr.value[0].value); - obj.value = attr.value[1].value; - obj.valueTagClass = attr.value[1].type; - // if the OID is known, get its name and short name - if(obj.type in oids) { - obj.name = oids[obj.type]; - if(obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - if(md) { - md.update(obj.type); - md.update(obj.value); - } - rval.push(obj); - } - } - - return rval; -}; - -/** - * Converts ASN.1 CRIAttributes into an array with objects that have type and - * value properties. - * - * @param attributes the CRIAttributes to convert. - */ -pki$2.CRIAttributesAsArray = function(attributes) { - var rval = []; - - // each value in 'attributes' in is a SEQUENCE with an OID and a SET - for(var si = 0; si < attributes.length; ++si) { - // get the attribute sequence - var seq = attributes[si]; - - // each value in the SEQUENCE containing first a type (an OID) and - // second a set of values (defined by the OID) - var type = asn1$4.derToOid(seq.value[0].value); - var values = seq.value[1].value; - for(var vi = 0; vi < values.length; ++vi) { - var obj = {}; - obj.type = type; - obj.value = values[vi].value; - obj.valueTagClass = values[vi].type; - // if the OID is known, get its name and short name - if(obj.type in oids) { - obj.name = oids[obj.type]; - if(obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - // parse extensions - if(obj.type === oids.extensionRequest) { - obj.extensions = []; - for(var ei = 0; ei < obj.value.length; ++ei) { - obj.extensions.push(pki$2.certificateExtensionFromAsn1(obj.value[ei])); - } - } - rval.push(obj); - } - } - - return rval; -}; - -/** - * Gets an issuer or subject attribute from its name, type, or short name. - * - * @param obj the issuer or subject object. - * @param options a short name string or an object with: - * shortName the short name for the attribute. - * name the name for the attribute. - * type the type for the attribute. - * - * @return the attribute. - */ -function _getAttribute(obj, options) { - if(typeof options === 'string') { - options = {shortName: options}; - } - - var rval = null; - var attr; - for(var i = 0; rval === null && i < obj.attributes.length; ++i) { - attr = obj.attributes[i]; - if(options.type && options.type === attr.type) { - rval = attr; - } else if(options.name && options.name === attr.name) { - rval = attr; - } else if(options.shortName && options.shortName === attr.shortName) { - rval = attr; - } - } - return rval; -} - -/** - * Converts signature parameters from ASN.1 structure. - * - * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had - * no parameters. - * - * RSASSA-PSS-params ::= SEQUENCE { - * hashAlgorithm [0] HashAlgorithm DEFAULT - * sha1Identifier, - * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT - * mgf1SHA1Identifier, - * saltLength [2] INTEGER DEFAULT 20, - * trailerField [3] INTEGER DEFAULT 1 - * } - * - * HashAlgorithm ::= AlgorithmIdentifier - * - * MaskGenAlgorithm ::= AlgorithmIdentifier - * - * AlgorithmIdentifer ::= SEQUENCE { - * algorithm OBJECT IDENTIFIER, - * parameters ANY DEFINED BY algorithm OPTIONAL - * } - * - * @param oid The OID specifying the signature algorithm - * @param obj The ASN.1 structure holding the parameters - * @param fillDefaults Whether to use return default values where omitted - * @return signature parameter object - */ -var _readSignatureParameters = function(oid, obj, fillDefaults) { - var params = {}; - - if(oid !== oids['RSASSA-PSS']) { - return params; - } - - if(fillDefaults) { - params = { - hash: { - algorithmOid: oids['sha1'] - }, - mgf: { - algorithmOid: oids['mgf1'], - hash: { - algorithmOid: oids['sha1'] - } - }, - saltLength: 20 - }; - } - - var capture = {}; - var errors = []; - if(!asn1$4.validate(obj, rsassaPssParameterValidator, capture, errors)) { - var error = new Error('Cannot read RSASSA-PSS parameter block.'); - error.errors = errors; - throw error; - } - - if(capture.hashOid !== undefined) { - params.hash = params.hash || {}; - params.hash.algorithmOid = asn1$4.derToOid(capture.hashOid); - } - - if(capture.maskGenOid !== undefined) { - params.mgf = params.mgf || {}; - params.mgf.algorithmOid = asn1$4.derToOid(capture.maskGenOid); - params.mgf.hash = params.mgf.hash || {}; - params.mgf.hash.algorithmOid = asn1$4.derToOid(capture.maskGenHashOid); - } - - if(capture.saltLength !== undefined) { - params.saltLength = capture.saltLength.charCodeAt(0); - } - - return params; -}; - -/** - * Converts an X.509 certificate from PEM format. - * - * Note: If the certificate is to be verified then compute hash should - * be set to true. This will scan the TBSCertificate part of the ASN.1 - * object while it is converted so it doesn't need to be converted back - * to ASN.1-DER-encoding later. - * - * @param pem the PEM-formatted certificate. - * @param computeHash true to compute the hash for verification. - * @param strict true to be strict when checking ASN.1 value lengths, false to - * allow truncated values (default: true). - * - * @return the certificate. - */ -pki$2.certificateFromPem = function(pem, computeHash, strict) { - var msg = forge$e.pem.decode(pem)[0]; - - if(msg.type !== 'CERTIFICATE' && - msg.type !== 'X509 CERTIFICATE' && - msg.type !== 'TRUSTED CERTIFICATE') { - var error = new Error( - 'Could not convert certificate from PEM; PEM header type ' + - 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error( - 'Could not convert certificate from PEM; PEM is encrypted.'); - } - - // convert DER to ASN.1 object - var obj = asn1$4.fromDer(msg.body, strict); - - return pki$2.certificateFromAsn1(obj, computeHash); -}; - -/** - * Converts an X.509 certificate to PEM format. - * - * @param cert the certificate. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted certificate. - */ -pki$2.certificateToPem = function(cert, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'CERTIFICATE', - body: asn1$4.toDer(pki$2.certificateToAsn1(cert)).getBytes() - }; - return forge$e.pem.encode(msg, {maxline: maxline}); -}; - -/** - * Converts an RSA public key from PEM format. - * - * @param pem the PEM-formatted public key. - * - * @return the public key. - */ -pki$2.publicKeyFromPem = function(pem) { - var msg = forge$e.pem.decode(pem)[0]; - - if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') { - var error = new Error('Could not convert public key from PEM; PEM header ' + - 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert public key from PEM; PEM is encrypted.'); - } - - // convert DER to ASN.1 object - var obj = asn1$4.fromDer(msg.body); - - return pki$2.publicKeyFromAsn1(obj); -}; - -/** - * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo). - * - * @param key the public key. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted public key. - */ -pki$2.publicKeyToPem = function(key, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'PUBLIC KEY', - body: asn1$4.toDer(pki$2.publicKeyToAsn1(key)).getBytes() - }; - return forge$e.pem.encode(msg, {maxline: maxline}); -}; - -/** - * Converts an RSA public key to PEM format (using an RSAPublicKey). - * - * @param key the public key. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted public key. - */ -pki$2.publicKeyToRSAPublicKeyPem = function(key, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'RSA PUBLIC KEY', - body: asn1$4.toDer(pki$2.publicKeyToRSAPublicKey(key)).getBytes() - }; - return forge$e.pem.encode(msg, {maxline: maxline}); -}; - -/** - * Gets a fingerprint for the given public key. - * - * @param options the options to use. - * [md] the message digest object to use (defaults to forge.md.sha1). - * [type] the type of fingerprint, such as 'RSAPublicKey', - * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey'). - * [encoding] an alternative output encoding, such as 'hex' - * (defaults to none, outputs a byte buffer). - * [delimiter] the delimiter to use between bytes for 'hex' encoded - * output, eg: ':' (defaults to none). - * - * @return the fingerprint as a byte buffer or other encoding based on options. - */ -pki$2.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge$e.md.sha1.create(); - var type = options.type || 'RSAPublicKey'; - - var bytes; - switch(type) { - case 'RSAPublicKey': - bytes = asn1$4.toDer(pki$2.publicKeyToRSAPublicKey(key)).getBytes(); - break; - case 'SubjectPublicKeyInfo': - bytes = asn1$4.toDer(pki$2.publicKeyToAsn1(key)).getBytes(); - break; - default: - throw new Error('Unknown fingerprint type "' + options.type + '".'); - } - - // hash public key bytes - md.start(); - md.update(bytes); - var digest = md.digest(); - if(options.encoding === 'hex') { - var hex = digest.toHex(); - if(options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if(options.encoding === 'binary') { - return digest.getBytes(); - } else if(options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); - } - return digest; -}; - -/** - * Converts a PKCS#10 certification request (CSR) from PEM format. - * - * Note: If the certification request is to be verified then compute hash - * should be set to true. This will scan the CertificationRequestInfo part of - * the ASN.1 object while it is converted so it doesn't need to be converted - * back to ASN.1-DER-encoding later. - * - * @param pem the PEM-formatted certificate. - * @param computeHash true to compute the hash for verification. - * @param strict true to be strict when checking ASN.1 value lengths, false to - * allow truncated values (default: true). - * - * @return the certification request (CSR). - */ -pki$2.certificationRequestFromPem = function(pem, computeHash, strict) { - var msg = forge$e.pem.decode(pem)[0]; - - if(msg.type !== 'CERTIFICATE REQUEST') { - var error = new Error('Could not convert certification request from PEM; ' + - 'PEM header type is not "CERTIFICATE REQUEST".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert certification request from PEM; ' + - 'PEM is encrypted.'); - } - - // convert DER to ASN.1 object - var obj = asn1$4.fromDer(msg.body, strict); - - return pki$2.certificationRequestFromAsn1(obj, computeHash); -}; - -/** - * Converts a PKCS#10 certification request (CSR) to PEM format. - * - * @param csr the certification request. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted certification request. - */ -pki$2.certificationRequestToPem = function(csr, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'CERTIFICATE REQUEST', - body: asn1$4.toDer(pki$2.certificationRequestToAsn1(csr)).getBytes() - }; - return forge$e.pem.encode(msg, {maxline: maxline}); -}; - -/** - * Creates an empty X.509v3 RSA certificate. - * - * @return the certificate. - */ -pki$2.createCertificate = function() { - var cert = {}; - cert.version = 0x02; - cert.serialNumber = '00'; - cert.signatureOid = null; - cert.signature = null; - cert.siginfo = {}; - cert.siginfo.algorithmOid = null; - cert.validity = {}; - cert.validity.notBefore = new Date(); - cert.validity.notAfter = new Date(); - - cert.issuer = {}; - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = []; - cert.issuer.hash = null; - - cert.subject = {}; - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = []; - cert.subject.hash = null; - - cert.extensions = []; - cert.publicKey = null; - cert.md = null; - - /** - * Sets the subject of this certificate. - * - * @param attrs the array of subject attributes to use. - * @param uniqueId an optional a unique ID to use. - */ - cert.setSubject = function(attrs, uniqueId) { - // set new attributes, clear hash - _fillMissingFields(attrs); - cert.subject.attributes = attrs; - delete cert.subject.uniqueId; - if(uniqueId) { - // TODO: support arbitrary bit length ids - cert.subject.uniqueId = uniqueId; - } - cert.subject.hash = null; - }; - - /** - * Sets the issuer of this certificate. - * - * @param attrs the array of issuer attributes to use. - * @param uniqueId an optional a unique ID to use. - */ - cert.setIssuer = function(attrs, uniqueId) { - // set new attributes, clear hash - _fillMissingFields(attrs); - cert.issuer.attributes = attrs; - delete cert.issuer.uniqueId; - if(uniqueId) { - // TODO: support arbitrary bit length ids - cert.issuer.uniqueId = uniqueId; - } - cert.issuer.hash = null; - }; - - /** - * Sets the extensions of this certificate. - * - * @param exts the array of extensions to use. - */ - cert.setExtensions = function(exts) { - for(var i = 0; i < exts.length; ++i) { - _fillMissingExtensionFields(exts[i], {cert: cert}); - } - // set new extensions - cert.extensions = exts; - }; - - /** - * Gets an extension by its name or id. - * - * @param options the name to use or an object with: - * name the name to use. - * id the id to use. - * - * @return the extension or null if not found. - */ - cert.getExtension = function(options) { - if(typeof options === 'string') { - options = {name: options}; - } - - var rval = null; - var ext; - for(var i = 0; rval === null && i < cert.extensions.length; ++i) { - ext = cert.extensions[i]; - if(options.id && ext.id === options.id) { - rval = ext; - } else if(options.name && ext.name === options.name) { - rval = ext; - } - } - return rval; - }; - - /** - * Signs this certificate using the given private key. - * - * @param key the private key to sign with. - * @param md the message digest object to use (defaults to forge.md.sha1). - */ - cert.sign = function(key, md) { - // TODO: get signature OID from private key - cert.md = md || forge$e.md.sha1.create(); - var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption']; - if(!algorithmOid) { - var error = new Error('Could not compute certificate digest. ' + - 'Unknown message digest algorithm OID.'); - error.algorithm = cert.md.algorithm; - throw error; - } - cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; - - // get TBSCertificate, convert to DER - cert.tbsCertificate = pki$2.getTBSCertificate(cert); - var bytes = asn1$4.toDer(cert.tbsCertificate); - - // digest and sign - cert.md.update(bytes.getBytes()); - cert.signature = key.sign(cert.md); - }; - - /** - * Attempts verify the signature on the passed certificate using this - * certificate's public key. - * - * @param child the certificate to verify. - * - * @return true if verified, false if not. - */ - cert.verify = function(child) { - var rval = false; - - if(!cert.issued(child)) { - var issuer = child.issuer; - var subject = cert.subject; - var error = new Error( - 'The parent certificate did not issue the given child ' + - 'certificate; the child certificate\'s issuer does not match the ' + - 'parent\'s subject.'); - error.expectedIssuer = issuer.attributes; - error.actualIssuer = subject.attributes; - throw error; - } - - var md = child.md; - if(md === null) { - // check signature OID for supported signature types - if(child.signatureOid in oids) { - var oid = oids[child.signatureOid]; - switch(oid) { - case 'sha1WithRSAEncryption': - md = forge$e.md.sha1.create(); - break; - case 'md5WithRSAEncryption': - md = forge$e.md.md5.create(); - break; - case 'sha256WithRSAEncryption': - md = forge$e.md.sha256.create(); - break; - case 'sha384WithRSAEncryption': - md = forge$e.md.sha384.create(); - break; - case 'sha512WithRSAEncryption': - md = forge$e.md.sha512.create(); - break; - case 'RSASSA-PSS': - md = forge$e.md.sha256.create(); - break; - } - } - if(md === null) { - var error = new Error('Could not compute certificate digest. ' + - 'Unknown signature OID.'); - error.signatureOid = child.signatureOid; - throw error; - } - - // produce DER formatted TBSCertificate and digest it - var tbsCertificate = child.tbsCertificate || pki$2.getTBSCertificate(child); - var bytes = asn1$4.toDer(tbsCertificate); - md.update(bytes.getBytes()); - } - - if(md !== null) { - var scheme; - - switch(child.signatureOid) { - case oids.sha1WithRSAEncryption: - scheme = undefined; /* use PKCS#1 v1.5 padding scheme */ - break; - case oids['RSASSA-PSS']: - var hash, mgf; - - /* initialize mgf */ - hash = oids[child.signatureParameters.mgf.hash.algorithmOid]; - if(hash === undefined || forge$e.md[hash] === undefined) { - var error = new Error('Unsupported MGF hash function.'); - error.oid = child.signatureParameters.mgf.hash.algorithmOid; - error.name = hash; - throw error; - } - - mgf = oids[child.signatureParameters.mgf.algorithmOid]; - if(mgf === undefined || forge$e.mgf[mgf] === undefined) { - var error = new Error('Unsupported MGF function.'); - error.oid = child.signatureParameters.mgf.algorithmOid; - error.name = mgf; - throw error; - } - - mgf = forge$e.mgf[mgf].create(forge$e.md[hash].create()); - - /* initialize hash function */ - hash = oids[child.signatureParameters.hash.algorithmOid]; - if(hash === undefined || forge$e.md[hash] === undefined) { - throw { - message: 'Unsupported RSASSA-PSS hash function.', - oid: child.signatureParameters.hash.algorithmOid, - name: hash - }; - } - - scheme = forge$e.pss.create(forge$e.md[hash].create(), mgf, - child.signatureParameters.saltLength); - break; - } - - // verify signature on cert using public key - rval = cert.publicKey.verify( - md.digest().getBytes(), child.signature, scheme); - } - - return rval; - }; - - /** - * Returns true if this certificate's issuer matches the passed - * certificate's subject. Note that no signature check is performed. - * - * @param parent the certificate to check. - * - * @return true if this certificate's issuer matches the passed certificate's - * subject. - */ - cert.isIssuer = function(parent) { - var rval = false; - - var i = cert.issuer; - var s = parent.subject; - - // compare hashes if present - if(i.hash && s.hash) { - rval = (i.hash === s.hash); - } else if(i.attributes.length === s.attributes.length) { - // all attributes are the same so issuer matches subject - rval = true; - var iattr, sattr; - for(var n = 0; rval && n < i.attributes.length; ++n) { - iattr = i.attributes[n]; - sattr = s.attributes[n]; - if(iattr.type !== sattr.type || iattr.value !== sattr.value) { - // attribute mismatch - rval = false; - } - } - } - - return rval; - }; - - /** - * Returns true if this certificate's subject matches the issuer of the - * given certificate). Note that not signature check is performed. - * - * @param child the certificate to check. - * - * @return true if this certificate's subject matches the passed - * certificate's issuer. - */ - cert.issued = function(child) { - return child.isIssuer(cert); - }; - - /** - * Generates the subjectKeyIdentifier for this certificate as byte buffer. - * - * @return the subjectKeyIdentifier for this certificate as byte buffer. - */ - cert.generateSubjectKeyIdentifier = function() { - /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either: - - (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the - value of the BIT STRING subjectPublicKey (excluding the tag, - length, and number of unused bits). - - (2) The keyIdentifier is composed of a four bit type field with - the value 0100 followed by the least significant 60 bits of the - SHA-1 hash of the value of the BIT STRING subjectPublicKey - (excluding the tag, length, and number of unused bit string bits). - */ - - // skipping the tag, length, and number of unused bits is the same - // as just using the RSAPublicKey (for RSA keys, which are the - // only ones supported) - return pki$2.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'}); - }; - - /** - * Verifies the subjectKeyIdentifier extension value for this certificate - * against its public key. If no extension is found, false will be - * returned. - * - * @return true if verified, false if not. - */ - cert.verifySubjectKeyIdentifier = function() { - var oid = oids['subjectKeyIdentifier']; - for(var i = 0; i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if(ext.id === oid) { - var ski = cert.generateSubjectKeyIdentifier().getBytes(); - return (forge$e.util.hexToBytes(ext.subjectKeyIdentifier) === ski); - } - } - return false; - }; - - return cert; -}; - -/** - * Converts an X.509v3 RSA certificate from an ASN.1 object. - * - * Note: If the certificate is to be verified then compute hash should - * be set to true. There is currently no implementation for converting - * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1 - * object needs to be scanned before the cert object is created. - * - * @param obj the asn1 representation of an X.509v3 RSA certificate. - * @param computeHash true to compute the hash for verification. - * - * @return the certificate. - */ -pki$2.certificateFromAsn1 = function(obj, computeHash) { - // validate certificate and capture data - var capture = {}; - var errors = []; - if(!asn1$4.validate(obj, x509CertificateValidator, capture, errors)) { - var error = new Error('Cannot read X.509 certificate. ' + - 'ASN.1 object is not an X509v3 Certificate.'); - error.errors = errors; - throw error; - } - - // get oid - var oid = asn1$4.derToOid(capture.publicKeyOid); - if(oid !== pki$2.oids.rsaEncryption) { - throw new Error('Cannot read public key. OID is not RSA.'); - } - - // create certificate - var cert = pki$2.createCertificate(); - cert.version = capture.certVersion ? - capture.certVersion.charCodeAt(0) : 0; - var serial = forge$e.util.createBuffer(capture.certSerialNumber); - cert.serialNumber = serial.toHex(); - cert.signatureOid = forge$e.asn1.derToOid(capture.certSignatureOid); - cert.signatureParameters = _readSignatureParameters( - cert.signatureOid, capture.certSignatureParams, true); - cert.siginfo.algorithmOid = forge$e.asn1.derToOid(capture.certinfoSignatureOid); - cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid, - capture.certinfoSignatureParams, false); - cert.signature = capture.certSignature; - - var validity = []; - if(capture.certValidity1UTCTime !== undefined) { - validity.push(asn1$4.utcTimeToDate(capture.certValidity1UTCTime)); - } - if(capture.certValidity2GeneralizedTime !== undefined) { - validity.push(asn1$4.generalizedTimeToDate( - capture.certValidity2GeneralizedTime)); - } - if(capture.certValidity3UTCTime !== undefined) { - validity.push(asn1$4.utcTimeToDate(capture.certValidity3UTCTime)); - } - if(capture.certValidity4GeneralizedTime !== undefined) { - validity.push(asn1$4.generalizedTimeToDate( - capture.certValidity4GeneralizedTime)); - } - if(validity.length > 2) { - throw new Error('Cannot read notBefore/notAfter validity times; more ' + - 'than two times were provided in the certificate.'); - } - if(validity.length < 2) { - throw new Error('Cannot read notBefore/notAfter validity times; they ' + - 'were not provided as either UTCTime or GeneralizedTime.'); - } - cert.validity.notBefore = validity[0]; - cert.validity.notAfter = validity[1]; - - // keep TBSCertificate to preserve signature when exporting - cert.tbsCertificate = capture.tbsCertificate; - - if(computeHash) { - // check signature OID for supported signature types - cert.md = null; - if(cert.signatureOid in oids) { - var oid = oids[cert.signatureOid]; - switch(oid) { - case 'sha1WithRSAEncryption': - cert.md = forge$e.md.sha1.create(); - break; - case 'md5WithRSAEncryption': - cert.md = forge$e.md.md5.create(); - break; - case 'sha256WithRSAEncryption': - cert.md = forge$e.md.sha256.create(); - break; - case 'sha384WithRSAEncryption': - cert.md = forge$e.md.sha384.create(); - break; - case 'sha512WithRSAEncryption': - cert.md = forge$e.md.sha512.create(); - break; - case 'RSASSA-PSS': - cert.md = forge$e.md.sha256.create(); - break; - } - } - if(cert.md === null) { - var error = new Error('Could not compute certificate digest. ' + - 'Unknown signature OID.'); - error.signatureOid = cert.signatureOid; - throw error; - } - - // produce DER formatted TBSCertificate and digest it - var bytes = asn1$4.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); - } - - // handle issuer, build issuer message digest - var imd = forge$e.md.sha1.create(); - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = pki$2.RDNAttributesAsArray(capture.certIssuer, imd); - if(capture.certIssuerUniqueId) { - cert.issuer.uniqueId = capture.certIssuerUniqueId; - } - cert.issuer.hash = imd.digest().toHex(); - - // handle subject, build subject message digest - var smd = forge$e.md.sha1.create(); - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = pki$2.RDNAttributesAsArray(capture.certSubject, smd); - if(capture.certSubjectUniqueId) { - cert.subject.uniqueId = capture.certSubjectUniqueId; - } - cert.subject.hash = smd.digest().toHex(); - - // handle extensions - if(capture.certExtensions) { - cert.extensions = pki$2.certificateExtensionsFromAsn1(capture.certExtensions); - } else { - cert.extensions = []; - } - - // convert RSA public key from ASN.1 - cert.publicKey = pki$2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - - return cert; -}; - -/** - * Converts an ASN.1 extensions object (with extension sequences as its - * values) into an array of extension objects with types and values. - * - * Supported extensions: - * - * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } - * KeyUsage ::= BIT STRING { - * digitalSignature (0), - * nonRepudiation (1), - * keyEncipherment (2), - * dataEncipherment (3), - * keyAgreement (4), - * keyCertSign (5), - * cRLSign (6), - * encipherOnly (7), - * decipherOnly (8) - * } - * - * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } - * BasicConstraints ::= SEQUENCE { - * cA BOOLEAN DEFAULT FALSE, - * pathLenConstraint INTEGER (0..MAX) OPTIONAL - * } - * - * subjectAltName EXTENSION ::= { - * SYNTAX GeneralNames - * IDENTIFIED BY id-ce-subjectAltName - * } - * - * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName - * - * GeneralName ::= CHOICE { - * otherName [0] INSTANCE OF OTHER-NAME, - * rfc822Name [1] IA5String, - * dNSName [2] IA5String, - * x400Address [3] ORAddress, - * directoryName [4] Name, - * ediPartyName [5] EDIPartyName, - * uniformResourceIdentifier [6] IA5String, - * IPAddress [7] OCTET STRING, - * registeredID [8] OBJECT IDENTIFIER - * } - * - * OTHER-NAME ::= TYPE-IDENTIFIER - * - * EDIPartyName ::= SEQUENCE { - * nameAssigner [0] DirectoryString {ub-name} OPTIONAL, - * partyName [1] DirectoryString {ub-name} - * } - * - * @param exts the extensions ASN.1 with extension sequences to parse. - * - * @return the array. - */ -pki$2.certificateExtensionsFromAsn1 = function(exts) { - var rval = []; - for(var i = 0; i < exts.value.length; ++i) { - // get extension sequence - var extseq = exts.value[i]; - for(var ei = 0; ei < extseq.value.length; ++ei) { - rval.push(pki$2.certificateExtensionFromAsn1(extseq.value[ei])); - } - } - - return rval; -}; - -/** - * Parses a single certificate extension from ASN.1. - * - * @param ext the extension in ASN.1 format. - * - * @return the parsed extension as an object. - */ -pki$2.certificateExtensionFromAsn1 = function(ext) { - // an extension has: - // [0] extnID OBJECT IDENTIFIER - // [1] critical BOOLEAN DEFAULT FALSE - // [2] extnValue OCTET STRING - var e = {}; - e.id = asn1$4.derToOid(ext.value[0].value); - e.critical = false; - if(ext.value[1].type === asn1$4.Type.BOOLEAN) { - e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00); - e.value = ext.value[2].value; - } else { - e.value = ext.value[1].value; - } - // if the oid is known, get its name - if(e.id in oids) { - e.name = oids[e.id]; - - // handle key usage - if(e.name === 'keyUsage') { - // get value as BIT STRING - var ev = asn1$4.fromDer(e.value); - var b2 = 0x00; - var b3 = 0x00; - if(ev.value.length > 1) { - // skip first byte, just indicates unused bits which - // will be padded with 0s anyway - // get bytes with flag bits - b2 = ev.value.charCodeAt(1); - b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; - } - // set flags - e.digitalSignature = (b2 & 0x80) === 0x80; - e.nonRepudiation = (b2 & 0x40) === 0x40; - e.keyEncipherment = (b2 & 0x20) === 0x20; - e.dataEncipherment = (b2 & 0x10) === 0x10; - e.keyAgreement = (b2 & 0x08) === 0x08; - e.keyCertSign = (b2 & 0x04) === 0x04; - e.cRLSign = (b2 & 0x02) === 0x02; - e.encipherOnly = (b2 & 0x01) === 0x01; - e.decipherOnly = (b3 & 0x80) === 0x80; - } else if(e.name === 'basicConstraints') { - // handle basic constraints - // get value as SEQUENCE - var ev = asn1$4.fromDer(e.value); - // get cA BOOLEAN flag (defaults to false) - if(ev.value.length > 0 && ev.value[0].type === asn1$4.Type.BOOLEAN) { - e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00); - } else { - e.cA = false; - } - // get path length constraint - var value = null; - if(ev.value.length > 0 && ev.value[0].type === asn1$4.Type.INTEGER) { - value = ev.value[0].value; - } else if(ev.value.length > 1) { - value = ev.value[1].value; - } - if(value !== null) { - e.pathLenConstraint = asn1$4.derToInteger(value); - } - } else if(e.name === 'extKeyUsage') { - // handle extKeyUsage - // value is a SEQUENCE of OIDs - var ev = asn1$4.fromDer(e.value); - for(var vi = 0; vi < ev.value.length; ++vi) { - var oid = asn1$4.derToOid(ev.value[vi].value); - if(oid in oids) { - e[oids[oid]] = true; - } else { - e[oid] = true; - } - } - } else if(e.name === 'nsCertType') { - // handle nsCertType - // get value as BIT STRING - var ev = asn1$4.fromDer(e.value); - var b2 = 0x00; - if(ev.value.length > 1) { - // skip first byte, just indicates unused bits which - // will be padded with 0s anyway - // get bytes with flag bits - b2 = ev.value.charCodeAt(1); - } - // set flags - e.client = (b2 & 0x80) === 0x80; - e.server = (b2 & 0x40) === 0x40; - e.email = (b2 & 0x20) === 0x20; - e.objsign = (b2 & 0x10) === 0x10; - e.reserved = (b2 & 0x08) === 0x08; - e.sslCA = (b2 & 0x04) === 0x04; - e.emailCA = (b2 & 0x02) === 0x02; - e.objCA = (b2 & 0x01) === 0x01; - } else if( - e.name === 'subjectAltName' || - e.name === 'issuerAltName') { - // handle subjectAltName/issuerAltName - e.altNames = []; - - // ev is a SYNTAX SEQUENCE - var gn; - var ev = asn1$4.fromDer(e.value); - for(var n = 0; n < ev.value.length; ++n) { - // get GeneralName - gn = ev.value[n]; - - var altName = { - type: gn.type, - value: gn.value - }; - e.altNames.push(altName); - - // Note: Support for types 1,2,6,7,8 - switch(gn.type) { - // rfc822Name - case 1: - // dNSName - case 2: - // uniformResourceIdentifier (URI) - case 6: - break; - // IPAddress - case 7: - // convert to IPv4/IPv6 string representation - altName.ip = forge$e.util.bytesToIP(gn.value); - break; - // registeredID - case 8: - altName.oid = asn1$4.derToOid(gn.value); - break; - // unsupported - } - } - } else if(e.name === 'subjectKeyIdentifier') { - // value is an OCTETSTRING w/the hash of the key-type specific - // public key structure (eg: RSAPublicKey) - var ev = asn1$4.fromDer(e.value); - e.subjectKeyIdentifier = forge$e.util.bytesToHex(ev.value); - } - } - return e; -}; - -/** - * Converts a PKCS#10 certification request (CSR) from an ASN.1 object. - * - * Note: If the certification request is to be verified then compute hash - * should be set to true. There is currently no implementation for converting - * a certificate back to ASN.1 so the CertificationRequestInfo part of the - * ASN.1 object needs to be scanned before the csr object is created. - * - * @param obj the asn1 representation of a PKCS#10 certification request (CSR). - * @param computeHash true to compute the hash for verification. - * - * @return the certification request (CSR). - */ -pki$2.certificationRequestFromAsn1 = function(obj, computeHash) { - // validate certification request and capture data - var capture = {}; - var errors = []; - if(!asn1$4.validate(obj, certificationRequestValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#10 certificate request. ' + - 'ASN.1 object is not a PKCS#10 CertificationRequest.'); - error.errors = errors; - throw error; - } - - // get oid - var oid = asn1$4.derToOid(capture.publicKeyOid); - if(oid !== pki$2.oids.rsaEncryption) { - throw new Error('Cannot read public key. OID is not RSA.'); - } - - // create certification request - var csr = pki$2.createCertificationRequest(); - csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; - csr.signatureOid = forge$e.asn1.derToOid(capture.csrSignatureOid); - csr.signatureParameters = _readSignatureParameters( - csr.signatureOid, capture.csrSignatureParams, true); - csr.siginfo.algorithmOid = forge$e.asn1.derToOid(capture.csrSignatureOid); - csr.siginfo.parameters = _readSignatureParameters( - csr.siginfo.algorithmOid, capture.csrSignatureParams, false); - csr.signature = capture.csrSignature; - - // keep CertificationRequestInfo to preserve signature when exporting - csr.certificationRequestInfo = capture.certificationRequestInfo; - - if(computeHash) { - // check signature OID for supported signature types - csr.md = null; - if(csr.signatureOid in oids) { - var oid = oids[csr.signatureOid]; - switch(oid) { - case 'sha1WithRSAEncryption': - csr.md = forge$e.md.sha1.create(); - break; - case 'md5WithRSAEncryption': - csr.md = forge$e.md.md5.create(); - break; - case 'sha256WithRSAEncryption': - csr.md = forge$e.md.sha256.create(); - break; - case 'sha384WithRSAEncryption': - csr.md = forge$e.md.sha384.create(); - break; - case 'sha512WithRSAEncryption': - csr.md = forge$e.md.sha512.create(); - break; - case 'RSASSA-PSS': - csr.md = forge$e.md.sha256.create(); - break; - } - } - if(csr.md === null) { - var error = new Error('Could not compute certification request digest. ' + - 'Unknown signature OID.'); - error.signatureOid = csr.signatureOid; - throw error; - } - - // produce DER formatted CertificationRequestInfo and digest it - var bytes = asn1$4.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); - } - - // handle subject, build subject message digest - var smd = forge$e.md.sha1.create(); - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = pki$2.RDNAttributesAsArray( - capture.certificationRequestInfoSubject, smd); - csr.subject.hash = smd.digest().toHex(); - - // convert RSA public key from ASN.1 - csr.publicKey = pki$2.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - - // convert attributes from ASN.1 - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.attributes = pki$2.CRIAttributesAsArray( - capture.certificationRequestInfoAttributes || []); - - return csr; -}; - -/** - * Creates an empty certification request (a CSR or certificate signing - * request). Once created, its public key and attributes can be set and then - * it can be signed. - * - * @return the empty certification request. - */ -pki$2.createCertificationRequest = function() { - var csr = {}; - csr.version = 0x00; - csr.signatureOid = null; - csr.signature = null; - csr.siginfo = {}; - csr.siginfo.algorithmOid = null; - - csr.subject = {}; - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = []; - csr.subject.hash = null; - - csr.publicKey = null; - csr.attributes = []; - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.md = null; - - /** - * Sets the subject of this certification request. - * - * @param attrs the array of subject attributes to use. - */ - csr.setSubject = function(attrs) { - // set new attributes - _fillMissingFields(attrs); - csr.subject.attributes = attrs; - csr.subject.hash = null; - }; - - /** - * Sets the attributes of this certification request. - * - * @param attrs the array of attributes to use. - */ - csr.setAttributes = function(attrs) { - // set new attributes - _fillMissingFields(attrs); - csr.attributes = attrs; - }; - - /** - * Signs this certification request using the given private key. - * - * @param key the private key to sign with. - * @param md the message digest object to use (defaults to forge.md.sha1). - */ - csr.sign = function(key, md) { - // TODO: get signature OID from private key - csr.md = md || forge$e.md.sha1.create(); - var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption']; - if(!algorithmOid) { - var error = new Error('Could not compute certification request digest. ' + - 'Unknown message digest algorithm OID.'); - error.algorithm = csr.md.algorithm; - throw error; - } - csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; - - // get CertificationRequestInfo, convert to DER - csr.certificationRequestInfo = pki$2.getCertificationRequestInfo(csr); - var bytes = asn1$4.toDer(csr.certificationRequestInfo); - - // digest and sign - csr.md.update(bytes.getBytes()); - csr.signature = key.sign(csr.md); - }; - - /** - * Attempts verify the signature on the passed certification request using - * its public key. - * - * A CSR that has been exported to a file in PEM format can be verified using - * OpenSSL using this command: - * - * openssl req -in -verify -noout -text - * - * @return true if verified, false if not. - */ - csr.verify = function() { - var rval = false; - - var md = csr.md; - if(md === null) { - // check signature OID for supported signature types - if(csr.signatureOid in oids) { - // TODO: create DRY `OID to md` function - var oid = oids[csr.signatureOid]; - switch(oid) { - case 'sha1WithRSAEncryption': - md = forge$e.md.sha1.create(); - break; - case 'md5WithRSAEncryption': - md = forge$e.md.md5.create(); - break; - case 'sha256WithRSAEncryption': - md = forge$e.md.sha256.create(); - break; - case 'sha384WithRSAEncryption': - md = forge$e.md.sha384.create(); - break; - case 'sha512WithRSAEncryption': - md = forge$e.md.sha512.create(); - break; - case 'RSASSA-PSS': - md = forge$e.md.sha256.create(); - break; - } - } - if(md === null) { - var error = new Error( - 'Could not compute certification request digest. ' + - 'Unknown signature OID.'); - error.signatureOid = csr.signatureOid; - throw error; - } - - // produce DER formatted CertificationRequestInfo and digest it - var cri = csr.certificationRequestInfo || - pki$2.getCertificationRequestInfo(csr); - var bytes = asn1$4.toDer(cri); - md.update(bytes.getBytes()); - } - - if(md !== null) { - var scheme; - - switch(csr.signatureOid) { - case oids.sha1WithRSAEncryption: - /* use PKCS#1 v1.5 padding scheme */ - break; - case oids['RSASSA-PSS']: - var hash, mgf; - - /* initialize mgf */ - hash = oids[csr.signatureParameters.mgf.hash.algorithmOid]; - if(hash === undefined || forge$e.md[hash] === undefined) { - var error = new Error('Unsupported MGF hash function.'); - error.oid = csr.signatureParameters.mgf.hash.algorithmOid; - error.name = hash; - throw error; - } - - mgf = oids[csr.signatureParameters.mgf.algorithmOid]; - if(mgf === undefined || forge$e.mgf[mgf] === undefined) { - var error = new Error('Unsupported MGF function.'); - error.oid = csr.signatureParameters.mgf.algorithmOid; - error.name = mgf; - throw error; - } - - mgf = forge$e.mgf[mgf].create(forge$e.md[hash].create()); - - /* initialize hash function */ - hash = oids[csr.signatureParameters.hash.algorithmOid]; - if(hash === undefined || forge$e.md[hash] === undefined) { - var error = new Error('Unsupported RSASSA-PSS hash function.'); - error.oid = csr.signatureParameters.hash.algorithmOid; - error.name = hash; - throw error; - } - - scheme = forge$e.pss.create(forge$e.md[hash].create(), mgf, - csr.signatureParameters.saltLength); - break; - } - - // verify signature on csr using its public key - rval = csr.publicKey.verify( - md.digest().getBytes(), csr.signature, scheme); - } - - return rval; - }; - - return csr; -}; - -/** - * Converts an X.509 subject or issuer to an ASN.1 RDNSequence. - * - * @param obj the subject or issuer (distinguished name). - * - * @return the ASN.1 RDNSequence. - */ -function _dnToAsn1(obj) { - // create an empty RDNSequence - var rval = asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); - - // iterate over attributes - var attr, set; - var attrs = obj.attributes; - for(var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - var value = attr.value; - - // reuse tag class for attribute value if available - var valueTagClass = asn1$4.Type.PRINTABLESTRING; - if('valueTagClass' in attr) { - valueTagClass = attr.valueTagClass; - - if(valueTagClass === asn1$4.Type.UTF8) { - value = forge$e.util.encodeUtf8(value); - } - // FIXME: handle more encodings - } - - // create a RelativeDistinguishedName set - // each value in the set is an AttributeTypeAndValue first - // containing the type (an OID) and second the value - set = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SET, true, [ - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - // AttributeType - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, - asn1$4.oidToDer(attr.type).getBytes()), - // AttributeValue - asn1$4.create(asn1$4.Class.UNIVERSAL, valueTagClass, false, value) - ]) - ]); - rval.value.push(set); - } - - return rval; -} - -/** - * Fills in missing fields in attributes. - * - * @param attrs the attributes to fill missing fields in. - */ -function _fillMissingFields(attrs) { - var attr; - for(var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - - // populate missing name - if(typeof attr.name === 'undefined') { - if(attr.type && attr.type in pki$2.oids) { - attr.name = pki$2.oids[attr.type]; - } else if(attr.shortName && attr.shortName in _shortNames) { - attr.name = pki$2.oids[_shortNames[attr.shortName]]; - } - } - - // populate missing type (OID) - if(typeof attr.type === 'undefined') { - if(attr.name && attr.name in pki$2.oids) { - attr.type = pki$2.oids[attr.name]; - } else { - var error = new Error('Attribute type not specified.'); - error.attribute = attr; - throw error; - } - } - - // populate missing shortname - if(typeof attr.shortName === 'undefined') { - if(attr.name && attr.name in _shortNames) { - attr.shortName = _shortNames[attr.name]; - } - } - - // convert extensions to value - if(attr.type === oids.extensionRequest) { - attr.valueConstructed = true; - attr.valueTagClass = asn1$4.Type.SEQUENCE; - if(!attr.value && attr.extensions) { - attr.value = []; - for(var ei = 0; ei < attr.extensions.length; ++ei) { - attr.value.push(pki$2.certificateExtensionToAsn1( - _fillMissingExtensionFields(attr.extensions[ei]))); - } - } - } - - if(typeof attr.value === 'undefined') { - var error = new Error('Attribute value not specified.'); - error.attribute = attr; - throw error; - } - } -} - -/** - * Fills in missing fields in certificate extensions. - * - * @param e the extension. - * @param [options] the options to use. - * [cert] the certificate the extensions are for. - * - * @return the extension. - */ -function _fillMissingExtensionFields(e, options) { - options = options || {}; - - // populate missing name - if(typeof e.name === 'undefined') { - if(e.id && e.id in pki$2.oids) { - e.name = pki$2.oids[e.id]; - } - } - - // populate missing id - if(typeof e.id === 'undefined') { - if(e.name && e.name in pki$2.oids) { - e.id = pki$2.oids[e.name]; - } else { - var error = new Error('Extension ID not specified.'); - error.extension = e; - throw error; - } - } - - if(typeof e.value !== 'undefined') { - return e; - } - - // handle missing value: - - // value is a BIT STRING - if(e.name === 'keyUsage') { - // build flags - var unused = 0; - var b2 = 0x00; - var b3 = 0x00; - if(e.digitalSignature) { - b2 |= 0x80; - unused = 7; - } - if(e.nonRepudiation) { - b2 |= 0x40; - unused = 6; - } - if(e.keyEncipherment) { - b2 |= 0x20; - unused = 5; - } - if(e.dataEncipherment) { - b2 |= 0x10; - unused = 4; - } - if(e.keyAgreement) { - b2 |= 0x08; - unused = 3; - } - if(e.keyCertSign) { - b2 |= 0x04; - unused = 2; - } - if(e.cRLSign) { - b2 |= 0x02; - unused = 1; - } - if(e.encipherOnly) { - b2 |= 0x01; - unused = 0; - } - if(e.decipherOnly) { - b3 |= 0x80; - unused = 7; - } - - // create bit string - var value = String.fromCharCode(unused); - if(b3 !== 0) { - value += String.fromCharCode(b2) + String.fromCharCode(b3); - } else if(b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, value); - } else if(e.name === 'basicConstraints') { - // basicConstraints is a SEQUENCE - e.value = asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); - // cA BOOLEAN flag defaults to false - if(e.cA) { - e.value.value.push(asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.BOOLEAN, false, - String.fromCharCode(0xFF))); - } - if('pathLenConstraint' in e) { - e.value.value.push(asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, - asn1$4.integerToDer(e.pathLenConstraint).getBytes())); - } - } else if(e.name === 'extKeyUsage') { - // extKeyUsage is a SEQUENCE of OIDs - e.value = asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); - var seq = e.value.value; - for(var key in e) { - if(e[key] !== true) { - continue; - } - // key is name in OID map - if(key in oids) { - seq.push(asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, - false, asn1$4.oidToDer(oids[key]).getBytes())); - } else if(key.indexOf('.') !== -1) { - // assume key is an OID - seq.push(asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, - false, asn1$4.oidToDer(key).getBytes())); - } - } - } else if(e.name === 'nsCertType') { - // nsCertType is a BIT STRING - // build flags - var unused = 0; - var b2 = 0x00; - - if(e.client) { - b2 |= 0x80; - unused = 7; - } - if(e.server) { - b2 |= 0x40; - unused = 6; - } - if(e.email) { - b2 |= 0x20; - unused = 5; - } - if(e.objsign) { - b2 |= 0x10; - unused = 4; - } - if(e.reserved) { - b2 |= 0x08; - unused = 3; - } - if(e.sslCA) { - b2 |= 0x04; - unused = 2; - } - if(e.emailCA) { - b2 |= 0x02; - unused = 1; - } - if(e.objCA) { - b2 |= 0x01; - unused = 0; - } - - // create bit string - var value = String.fromCharCode(unused); - if(b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, value); - } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') { - // SYNTAX SEQUENCE - e.value = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); - - var altName; - for(var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - // handle IP - if(altName.type === 7 && altName.ip) { - value = forge$e.util.bytesFromIP(altName.ip); - if(value === null) { - var error = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); - error.extension = e; - throw error; - } - } else if(altName.type === 8) { - // handle OID - if(altName.oid) { - value = asn1$4.oidToDer(asn1$4.oidToDer(altName.oid)); - } else { - // deprecated ... convert value to OID - value = asn1$4.oidToDer(value); - } - } - e.value.value.push(asn1$4.create( - asn1$4.Class.CONTEXT_SPECIFIC, altName.type, false, - value)); - } - } else if(e.name === 'nsComment' && options.cert) { - // sanity check value is ASCII (req'd) and not too big - if(!(/^[\x00-\x7F]*$/.test(e.comment)) || - (e.comment.length < 1) || (e.comment.length > 128)) { - throw new Error('Invalid "nsComment" content.'); - } - // IA5STRING opaque comment - e.value = asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.IA5STRING, false, e.comment); - } else if(e.name === 'subjectKeyIdentifier' && options.cert) { - var ski = options.cert.generateSubjectKeyIdentifier(); - e.subjectKeyIdentifier = ski.toHex(); - // OCTETSTRING w/digest - e.value = asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, ski.getBytes()); - } else if(e.name === 'authorityKeyIdentifier' && options.cert) { - // SYNTAX SEQUENCE - e.value = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); - var seq = e.value.value; - - if(e.keyIdentifier) { - var keyIdentifier = (e.keyIdentifier === true ? - options.cert.generateSubjectKeyIdentifier().getBytes() : - e.keyIdentifier); - seq.push( - asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier)); - } - - if(e.authorityCertIssuer) { - var authorityCertIssuer = [ - asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 4, true, [ - _dnToAsn1(e.authorityCertIssuer === true ? - options.cert.issuer : e.authorityCertIssuer) - ]) - ]; - seq.push( - asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer)); - } - - if(e.serialNumber) { - var serialNumber = forge$e.util.hexToBytes(e.serialNumber === true ? - options.cert.serialNumber : e.serialNumber); - seq.push( - asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 2, false, serialNumber)); - } - } else if(e.name === 'cRLDistributionPoints') { - e.value = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); - var seq = e.value.value; - - // Create sub SEQUENCE of DistributionPointName - var subSeq = asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); - - // Create fullName CHOICE - var fullNameGeneralNames = asn1$4.create( - asn1$4.Class.CONTEXT_SPECIFIC, 0, true, []); - var altName; - for(var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - // handle IP - if(altName.type === 7 && altName.ip) { - value = forge$e.util.bytesFromIP(altName.ip); - if(value === null) { - var error = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); - error.extension = e; - throw error; - } - } else if(altName.type === 8) { - // handle OID - if(altName.oid) { - value = asn1$4.oidToDer(asn1$4.oidToDer(altName.oid)); - } else { - // deprecated ... convert value to OID - value = asn1$4.oidToDer(value); - } - } - fullNameGeneralNames.value.push(asn1$4.create( - asn1$4.Class.CONTEXT_SPECIFIC, altName.type, false, - value)); - } - - // Add to the parent SEQUENCE - subSeq.value.push(asn1$4.create( - asn1$4.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames])); - seq.push(subSeq); - } - - // ensure value has been defined by now - if(typeof e.value === 'undefined') { - var error = new Error('Extension value not specified.'); - error.extension = e; - throw error; - } - - return e; -} - -/** - * Convert signature parameters object to ASN.1 - * - * @param {String} oid Signature algorithm OID - * @param params The signature parametrs object - * @return ASN.1 object representing signature parameters - */ -function _signatureParametersToAsn1(oid, params) { - switch(oid) { - case oids['RSASSA-PSS']: - var parts = []; - - if(params.hash.algorithmOid !== undefined) { - parts.push(asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, - asn1$4.oidToDer(params.hash.algorithmOid).getBytes()), - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, '') - ]) - ])); - } - - if(params.mgf.algorithmOid !== undefined) { - parts.push(asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, - asn1$4.oidToDer(params.mgf.algorithmOid).getBytes()), - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, - asn1$4.oidToDer(params.mgf.hash.algorithmOid).getBytes()), - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, '') - ]) - ]) - ])); - } - - if(params.saltLength !== undefined) { - parts.push(asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, - asn1$4.integerToDer(params.saltLength).getBytes()) - ])); - } - - return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, parts); - - default: - return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, ''); - } -} - -/** - * Converts a certification request's attributes to an ASN.1 set of - * CRIAttributes. - * - * @param csr certification request. - * - * @return the ASN.1 set of CRIAttributes. - */ -function _CRIAttributesToAsn1(csr) { - // create an empty context-specific container - var rval = asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, true, []); - - // no attributes, return empty container - if(csr.attributes.length === 0) { - return rval; - } - - // each attribute has a sequence with a type and a set of values - var attrs = csr.attributes; - for(var i = 0; i < attrs.length; ++i) { - var attr = attrs[i]; - var value = attr.value; - - // reuse tag class for attribute value if available - var valueTagClass = asn1$4.Type.UTF8; - if('valueTagClass' in attr) { - valueTagClass = attr.valueTagClass; - } - if(valueTagClass === asn1$4.Type.UTF8) { - value = forge$e.util.encodeUtf8(value); - } - var valueConstructed = false; - if('valueConstructed' in attr) { - valueConstructed = attr.valueConstructed; - } - // FIXME: handle more encodings - - // create a RelativeDistinguishedName set - // each value in the set is an AttributeTypeAndValue first - // containing the type (an OID) and second the value - var seq = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - // AttributeType - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, - asn1$4.oidToDer(attr.type).getBytes()), - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SET, true, [ - // AttributeValue - asn1$4.create( - asn1$4.Class.UNIVERSAL, valueTagClass, valueConstructed, value) - ]) - ]); - rval.value.push(seq); - } - - return rval; -} - -var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); -var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); - -/** - * Converts a Date object to ASN.1 - * Handles the different format before and after 1st January 2050 - * - * @param date date object. - * - * @return the ASN.1 object representing the date. - */ -function _dateToAsn1(date) { - if(date >= jan_1_1950 && date < jan_1_2050) { - return asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.UTCTIME, false, - asn1$4.dateToUtcTime(date)); - } else { - return asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.GENERALIZEDTIME, false, - asn1$4.dateToGeneralizedTime(date)); - } -} - -/** - * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate. - * - * @param cert the certificate. - * - * @return the asn1 TBSCertificate. - */ -pki$2.getTBSCertificate = function(cert) { - // TBSCertificate - var notBefore = _dateToAsn1(cert.validity.notBefore); - var notAfter = _dateToAsn1(cert.validity.notAfter); - var tbs = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - // version - asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, true, [ - // integer - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, - asn1$4.integerToDer(cert.version).getBytes()) - ]), - // serialNumber - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, - forge$e.util.hexToBytes(cert.serialNumber)), - // signature - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - // algorithm - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, - asn1$4.oidToDer(cert.siginfo.algorithmOid).getBytes()), - // parameters - _signatureParametersToAsn1( - cert.siginfo.algorithmOid, cert.siginfo.parameters) - ]), - // issuer - _dnToAsn1(cert.issuer), - // validity - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - notBefore, - notAfter - ]), - // subject - _dnToAsn1(cert.subject), - // SubjectPublicKeyInfo - pki$2.publicKeyToAsn1(cert.publicKey) - ]); - - if(cert.issuer.uniqueId) { - // issuerUniqueID (optional) - tbs.value.push( - asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0x00) + - cert.issuer.uniqueId - ) - ]) - ); - } - if(cert.subject.uniqueId) { - // subjectUniqueID (optional) - tbs.value.push( - asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0x00) + - cert.subject.uniqueId - ) - ]) - ); - } - - if(cert.extensions.length > 0) { - // extensions (optional) - tbs.value.push(pki$2.certificateExtensionsToAsn1(cert.extensions)); - } - - return tbs; -}; - -/** - * Gets the ASN.1 CertificationRequestInfo part of a - * PKCS#10 CertificationRequest. - * - * @param csr the certification request. - * - * @return the asn1 CertificationRequestInfo. - */ -pki$2.getCertificationRequestInfo = function(csr) { - // CertificationRequestInfo - var cri = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - // version - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false, - asn1$4.integerToDer(csr.version).getBytes()), - // subject - _dnToAsn1(csr.subject), - // SubjectPublicKeyInfo - pki$2.publicKeyToAsn1(csr.publicKey), - // attributes - _CRIAttributesToAsn1(csr) - ]); - - return cri; -}; - -/** - * Converts a DistinguishedName (subject or issuer) to an ASN.1 object. - * - * @param dn the DistinguishedName. - * - * @return the asn1 representation of a DistinguishedName. - */ -pki$2.distinguishedNameToAsn1 = function(dn) { - return _dnToAsn1(dn); -}; - -/** - * Converts an X.509v3 RSA certificate to an ASN.1 object. - * - * @param cert the certificate. - * - * @return the asn1 representation of an X.509v3 RSA certificate. - */ -pki$2.certificateToAsn1 = function(cert) { - // prefer cached TBSCertificate over generating one - var tbsCertificate = cert.tbsCertificate || pki$2.getTBSCertificate(cert); - - // Certificate - return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - // TBSCertificate - tbsCertificate, - // AlgorithmIdentifier (signature algorithm) - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - // algorithm - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, - asn1$4.oidToDer(cert.signatureOid).getBytes()), - // parameters - _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) - ]), - // SignatureValue - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, - String.fromCharCode(0x00) + cert.signature) - ]); -}; - -/** - * Converts X.509v3 certificate extensions to ASN.1. - * - * @param exts the extensions to convert. - * - * @return the extensions in ASN.1 format. - */ -pki$2.certificateExtensionsToAsn1 = function(exts) { - // create top-level extension container - var rval = asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 3, true, []); - - // create extension sequence (stores a sequence for each extension) - var seq = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); - rval.value.push(seq); - - for(var i = 0; i < exts.length; ++i) { - seq.value.push(pki$2.certificateExtensionToAsn1(exts[i])); - } - - return rval; -}; - -/** - * Converts a single certificate extension to ASN.1. - * - * @param ext the extension to convert. - * - * @return the extension in ASN.1 format. - */ -pki$2.certificateExtensionToAsn1 = function(ext) { - // create a sequence for each extension - var extseq = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []); - - // extnID (OID) - extseq.value.push(asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, - asn1$4.oidToDer(ext.id).getBytes())); - - // critical defaults to false - if(ext.critical) { - // critical BOOLEAN DEFAULT FALSE - extseq.value.push(asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.BOOLEAN, false, - String.fromCharCode(0xFF))); - } - - var value = ext.value; - if(typeof ext.value !== 'string') { - // value is asn.1 - value = asn1$4.toDer(value).getBytes(); - } - - // extnValue (OCTET STRING) - extseq.value.push(asn1$4.create( - asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, value)); - - return extseq; -}; - -/** - * Converts a PKCS#10 certification request to an ASN.1 object. - * - * @param csr the certification request. - * - * @return the asn1 representation of a certification request. - */ -pki$2.certificationRequestToAsn1 = function(csr) { - // prefer cached CertificationRequestInfo over generating one - var cri = csr.certificationRequestInfo || - pki$2.getCertificationRequestInfo(csr); - - // Certificate - return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - // CertificationRequestInfo - cri, - // AlgorithmIdentifier (signature algorithm) - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [ - // algorithm - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false, - asn1$4.oidToDer(csr.signatureOid).getBytes()), - // parameters - _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) - ]), - // signature - asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, - String.fromCharCode(0x00) + csr.signature) - ]); -}; - -/** - * Creates a CA store. - * - * @param certs an optional array of certificate objects or PEM-formatted - * certificate strings to add to the CA store. - * - * @return the CA store. - */ -pki$2.createCaStore = function(certs) { - // create CA store - var caStore = { - // stored certificates - certs: {} - }; - - /** - * Gets the certificate that issued the passed certificate or its - * 'parent'. - * - * @param cert the certificate to get the parent for. - * - * @return the parent certificate or null if none was found. - */ - caStore.getIssuer = function(cert) { - var rval = getBySubject(cert.issuer); - - // see if there are multiple matches - /*if(forge.util.isArray(rval)) { - // TODO: resolve multiple matches by checking - // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc. - // FIXME: or alternatively do authority key mapping - // if possible (X.509v1 certs can't work?) - throw new Error('Resolving multiple issuer matches not implemented yet.'); - }*/ - - return rval; - }; - - /** - * Adds a trusted certificate to the store. - * - * @param cert the certificate to add as a trusted certificate (either a - * pki.certificate object or a PEM-formatted certificate). - */ - caStore.addCertificate = function(cert) { - // convert from pem if necessary - if(typeof cert === 'string') { - cert = forge$e.pki.certificateFromPem(cert); - } - - ensureSubjectHasHash(cert.subject); - - if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store - if(cert.subject.hash in caStore.certs) { - // subject hash already exists, append to array - var tmp = caStore.certs[cert.subject.hash]; - if(!forge$e.util.isArray(tmp)) { - tmp = [tmp]; - } - tmp.push(cert); - caStore.certs[cert.subject.hash] = tmp; - } else { - caStore.certs[cert.subject.hash] = cert; - } - } - }; - - /** - * Checks to see if the given certificate is in the store. - * - * @param cert the certificate to check (either a pki.certificate or a - * PEM-formatted certificate). - * - * @return true if the certificate is in the store, false if not. - */ - caStore.hasCertificate = function(cert) { - // convert from pem if necessary - if(typeof cert === 'string') { - cert = forge$e.pki.certificateFromPem(cert); - } - - var match = getBySubject(cert.subject); - if(!match) { - return false; - } - if(!forge$e.util.isArray(match)) { - match = [match]; - } - // compare DER-encoding of certificates - var der1 = asn1$4.toDer(pki$2.certificateToAsn1(cert)).getBytes(); - for(var i = 0; i < match.length; ++i) { - var der2 = asn1$4.toDer(pki$2.certificateToAsn1(match[i])).getBytes(); - if(der1 === der2) { - return true; - } - } - return false; - }; - - /** - * Lists all of the certificates kept in the store. - * - * @return an array of all of the pki.certificate objects in the store. - */ - caStore.listAllCertificates = function() { - var certList = []; - - for(var hash in caStore.certs) { - if(caStore.certs.hasOwnProperty(hash)) { - var value = caStore.certs[hash]; - if(!forge$e.util.isArray(value)) { - certList.push(value); - } else { - for(var i = 0; i < value.length; ++i) { - certList.push(value[i]); - } - } - } - } - - return certList; - }; - - /** - * Removes a certificate from the store. - * - * @param cert the certificate to remove (either a pki.certificate or a - * PEM-formatted certificate). - * - * @return the certificate that was removed or null if the certificate - * wasn't in store. - */ - caStore.removeCertificate = function(cert) { - var result; - - // convert from pem if necessary - if(typeof cert === 'string') { - cert = forge$e.pki.certificateFromPem(cert); - } - ensureSubjectHasHash(cert.subject); - if(!caStore.hasCertificate(cert)) { - return null; - } - - var match = getBySubject(cert.subject); - - if(!forge$e.util.isArray(match)) { - result = caStore.certs[cert.subject.hash]; - delete caStore.certs[cert.subject.hash]; - return result; - } - - // compare DER-encoding of certificates - var der1 = asn1$4.toDer(pki$2.certificateToAsn1(cert)).getBytes(); - for(var i = 0; i < match.length; ++i) { - var der2 = asn1$4.toDer(pki$2.certificateToAsn1(match[i])).getBytes(); - if(der1 === der2) { - result = match[i]; - match.splice(i, 1); - } - } - if(match.length === 0) { - delete caStore.certs[cert.subject.hash]; - } - - return result; - }; - - function getBySubject(subject) { - ensureSubjectHasHash(subject); - return caStore.certs[subject.hash] || null; - } - - function ensureSubjectHasHash(subject) { - // produce subject hash if it doesn't exist - if(!subject.hash) { - var md = forge$e.md.sha1.create(); - subject.attributes = pki$2.RDNAttributesAsArray(_dnToAsn1(subject), md); - subject.hash = md.digest().toHex(); - } - } - - // auto-add passed in certs - if(certs) { - // parse PEM-formatted certificates as necessary - for(var i = 0; i < certs.length; ++i) { - var cert = certs[i]; - caStore.addCertificate(cert); - } - } - - return caStore; -}; - -/** - * Certificate verification errors, based on TLS. - */ -pki$2.certificateError = { - bad_certificate: 'forge.pki.BadCertificate', - unsupported_certificate: 'forge.pki.UnsupportedCertificate', - certificate_revoked: 'forge.pki.CertificateRevoked', - certificate_expired: 'forge.pki.CertificateExpired', - certificate_unknown: 'forge.pki.CertificateUnknown', - unknown_ca: 'forge.pki.UnknownCertificateAuthority' -}; - -/** - * Verifies a certificate chain against the given Certificate Authority store - * with an optional custom verify callback. - * - * @param caStore a certificate store to verify against. - * @param chain the certificate chain to verify, with the root or highest - * authority at the end (an array of certificates). - * @param options a callback to be called for every certificate in the chain or - * an object with: - * verify a callback to be called for every certificate in the - * chain - * validityCheckDate the date against which the certificate - * validity period should be checked. Pass null to not check - * the validity period. By default, the current date is used. - * - * The verify callback has the following signature: - * - * verified - Set to true if certificate was verified, otherwise the - * pki.certificateError for why the certificate failed. - * depth - The current index in the chain, where 0 is the end point's cert. - * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous - * end point. - * - * The function returns true on success and on failure either the appropriate - * pki.certificateError or an object with 'error' set to the appropriate - * pki.certificateError and 'message' set to a custom error message. - * - * @return true if successful, error thrown if not. - */ -pki$2.verifyCertificateChain = function(caStore, chain, options) { - /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate - Section 6: Certification Path Validation - See inline parentheticals related to this particular implementation. - - The primary goal of path validation is to verify the binding between - a subject distinguished name or a subject alternative name and subject - public key, as represented in the end entity certificate, based on the - public key of the trust anchor. This requires obtaining a sequence of - certificates that support that binding. That sequence should be provided - in the passed 'chain'. The trust anchor should be in the given CA - store. The 'end entity' certificate is the certificate provided by the - end point (typically a server) and is the first in the chain. - - To meet this goal, the path validation process verifies, among other - things, that a prospective certification path (a sequence of n - certificates or a 'chain') satisfies the following conditions: - - (a) for all x in {1, ..., n-1}, the subject of certificate x is - the issuer of certificate x+1; - - (b) certificate 1 is issued by the trust anchor; - - (c) certificate n is the certificate to be validated; and - - (d) for all x in {1, ..., n}, the certificate was valid at the - time in question. - - Note that here 'n' is index 0 in the chain and 1 is the last certificate - in the chain and it must be signed by a certificate in the connection's - CA store. - - The path validation process also determines the set of certificate - policies that are valid for this path, based on the certificate policies - extension, policy mapping extension, policy constraints extension, and - inhibit any-policy extension. - - Note: Policy mapping extension not supported (Not Required). - - Note: If the certificate has an unsupported critical extension, then it - must be rejected. - - Note: A certificate is self-issued if the DNs that appear in the subject - and issuer fields are identical and are not empty. - - The path validation algorithm assumes the following seven inputs are - provided to the path processing logic. What this specific implementation - will use is provided parenthetically: - - (a) a prospective certification path of length n (the 'chain') - (b) the current date/time: ('now'). - (c) user-initial-policy-set: A set of certificate policy identifiers - naming the policies that are acceptable to the certificate user. - The user-initial-policy-set contains the special value any-policy - if the user is not concerned about certificate policy - (Not implemented. Any policy is accepted). - (d) trust anchor information, describing a CA that serves as a trust - anchor for the certification path. The trust anchor information - includes: - - (1) the trusted issuer name, - (2) the trusted public key algorithm, - (3) the trusted public key, and - (4) optionally, the trusted public key parameters associated - with the public key. - - (Trust anchors are provided via certificates in the CA store). - - The trust anchor information may be provided to the path processing - procedure in the form of a self-signed certificate. The trusted anchor - information is trusted because it was delivered to the path processing - procedure by some trustworthy out-of-band procedure. If the trusted - public key algorithm requires parameters, then the parameters are - provided along with the trusted public key (No parameters used in this - implementation). - - (e) initial-policy-mapping-inhibit, which indicates if policy mapping is - allowed in the certification path. - (Not implemented, no policy checking) - - (f) initial-explicit-policy, which indicates if the path must be valid - for at least one of the certificate policies in the user-initial- - policy-set. - (Not implemented, no policy checking) - - (g) initial-any-policy-inhibit, which indicates whether the - anyPolicy OID should be processed if it is included in a - certificate. - (Not implemented, so any policy is valid provided that it is - not marked as critical) */ - - /* Basic Path Processing: - - For each certificate in the 'chain', the following is checked: - - 1. The certificate validity period includes the current time. - 2. The certificate was signed by its parent (where the parent is either - the next in the chain or from the CA store). Allow processing to - continue to the next step if no parent is found but the certificate is - in the CA store. - 3. TODO: The certificate has not been revoked. - 4. The certificate issuer name matches the parent's subject name. - 5. TODO: If the certificate is self-issued and not the final certificate - in the chain, skip this step, otherwise verify that the subject name - is within one of the permitted subtrees of X.500 distinguished names - and that each of the alternative names in the subjectAltName extension - (critical or non-critical) is within one of the permitted subtrees for - that name type. - 6. TODO: If the certificate is self-issued and not the final certificate - in the chain, skip this step, otherwise verify that the subject name - is not within one of the excluded subtrees for X.500 distinguished - names and none of the subjectAltName extension names are excluded for - that name type. - 7. The other steps in the algorithm for basic path processing involve - handling the policy extension which is not presently supported in this - implementation. Instead, if a critical policy extension is found, the - certificate is rejected as not supported. - 8. If the certificate is not the first or if its the only certificate in - the chain (having no parent from the CA store or is self-signed) and it - has a critical key usage extension, verify that the keyCertSign bit is - set. If the key usage extension exists, verify that the basic - constraints extension exists. If the basic constraints extension exists, - verify that the cA flag is set. If pathLenConstraint is set, ensure that - the number of certificates that precede in the chain (come earlier - in the chain as implemented below), excluding the very first in the - chain (typically the end-entity one), isn't greater than the - pathLenConstraint. This constraint limits the number of intermediate - CAs that may appear below a CA before only end-entity certificates - may be issued. */ - - // if a verify callback is passed as the third parameter, package it within - // the options object. This is to support a legacy function signature that - // expected the verify callback as the third parameter. - if(typeof options === 'function') { - options = {verify: options}; - } - options = options || {}; - - // copy cert chain references to another array to protect against changes - // in verify callback - chain = chain.slice(0); - var certs = chain.slice(0); - - var validityCheckDate = options.validityCheckDate; - // if no validityCheckDate is specified, default to the current date. Make - // sure to maintain the value null because it indicates that the validity - // period should not be checked. - if(typeof validityCheckDate === 'undefined') { - validityCheckDate = new Date(); - } - - // verify each cert in the chain using its parent, where the parent - // is either the next in the chain or from the CA store - var first = true; - var error = null; - var depth = 0; - do { - var cert = chain.shift(); - var parent = null; - var selfSigned = false; - - if(validityCheckDate) { - // 1. check valid time - if(validityCheckDate < cert.validity.notBefore || - validityCheckDate > cert.validity.notAfter) { - error = { - message: 'Certificate is not valid yet or has expired.', - error: pki$2.certificateError.certificate_expired, - notBefore: cert.validity.notBefore, - notAfter: cert.validity.notAfter, - // TODO: we might want to reconsider renaming 'now' to - // 'validityCheckDate' should this API be changed in the future. - now: validityCheckDate - }; - } - } - - // 2. verify with parent from chain or CA store - if(error === null) { - parent = chain[0] || caStore.getIssuer(cert); - if(parent === null) { - // check for self-signed cert - if(cert.isIssuer(cert)) { - selfSigned = true; - parent = cert; - } - } - - if(parent) { - // FIXME: current CA store implementation might have multiple - // certificates where the issuer can't be determined from the - // certificate (happens rarely with, eg: old certificates) so normalize - // by always putting parents into an array - // TODO: there's may be an extreme degenerate case currently uncovered - // where an old intermediate certificate seems to have a matching parent - // but none of the parents actually verify ... but the intermediate - // is in the CA and it should pass this check; needs investigation - var parents = parent; - if(!forge$e.util.isArray(parents)) { - parents = [parents]; - } - - // try to verify with each possible parent (typically only one) - var verified = false; - while(!verified && parents.length > 0) { - parent = parents.shift(); - try { - verified = parent.verify(cert); - } catch(ex) { - // failure to verify, don't care why, try next one - } - } - - if(!verified) { - error = { - message: 'Certificate signature is invalid.', - error: pki$2.certificateError.bad_certificate - }; - } - } - - if(error === null && (!parent || selfSigned) && - !caStore.hasCertificate(cert)) { - // no parent issuer and certificate itself is not trusted - error = { - message: 'Certificate is not trusted.', - error: pki$2.certificateError.unknown_ca - }; - } - } - - // TODO: 3. check revoked - - // 4. check for matching issuer/subject - if(error === null && parent && !cert.isIssuer(parent)) { - // parent is not issuer - error = { - message: 'Certificate issuer is invalid.', - error: pki$2.certificateError.bad_certificate - }; - } - - // 5. TODO: check names with permitted names tree - - // 6. TODO: check names against excluded names tree - - // 7. check for unsupported critical extensions - if(error === null) { - // supported extensions - var se = { - keyUsage: true, - basicConstraints: true - }; - for(var i = 0; error === null && i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if(ext.critical && !(ext.name in se)) { - error = { - message: - 'Certificate has an unsupported critical extension.', - error: pki$2.certificateError.unsupported_certificate - }; - } - } - } - - // 8. check for CA if cert is not first or is the only certificate - // remaining in chain with no parent or is self-signed - if(error === null && - (!first || (chain.length === 0 && (!parent || selfSigned)))) { - // first check keyUsage extension and then basic constraints - var bcExt = cert.getExtension('basicConstraints'); - var keyUsageExt = cert.getExtension('keyUsage'); - if(keyUsageExt !== null) { - // keyCertSign must be true and there must be a basic - // constraints extension - if(!keyUsageExt.keyCertSign || bcExt === null) { - // bad certificate - error = { - message: - 'Certificate keyUsage or basicConstraints conflict ' + - 'or indicate that the certificate is not a CA. ' + - 'If the certificate is the only one in the chain or ' + - 'isn\'t the first then the certificate must be a ' + - 'valid CA.', - error: pki$2.certificateError.bad_certificate - }; - } - } - // basic constraints cA flag must be set - if(error === null && bcExt !== null && !bcExt.cA) { - // bad certificate - error = { - message: - 'Certificate basicConstraints indicates the certificate ' + - 'is not a CA.', - error: pki$2.certificateError.bad_certificate - }; - } - // if error is not null and keyUsage is available, then we know it - // has keyCertSign and there is a basic constraints extension too, - // which means we can check pathLenConstraint (if it exists) - if(error === null && keyUsageExt !== null && - 'pathLenConstraint' in bcExt) { - // pathLen is the maximum # of intermediate CA certs that can be - // found between the current certificate and the end-entity (depth 0) - // certificate; this number does not include the end-entity (depth 0, - // last in the chain) even if it happens to be a CA certificate itself - var pathLen = depth - 1; - if(pathLen > bcExt.pathLenConstraint) { - // pathLenConstraint violated, bad certificate - error = { - message: - 'Certificate basicConstraints pathLenConstraint violated.', - error: pki$2.certificateError.bad_certificate - }; - } - } - } - - // call application callback - var vfd = (error === null) ? true : error.error; - var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; - if(ret === true) { - // clear any set error - error = null; - } else { - // if passed basic tests, set default message and alert - if(vfd === true) { - error = { - message: 'The application rejected the certificate.', - error: pki$2.certificateError.bad_certificate - }; - } - - // check for custom error info - if(ret || ret === 0) { - // set custom message and error - if(typeof ret === 'object' && !forge$e.util.isArray(ret)) { - if(ret.message) { - error.message = ret.message; - } - if(ret.error) { - error.error = ret.error; - } - } else if(typeof ret === 'string') { - // set custom error - error.error = ret; - } - } - - // throw error - throw error; - } - - // no longer first cert in chain - first = false; - ++depth; - } while(chain.length > 0); - - return true; -}; - -/** - * Javascript implementation of PKCS#12. - * - * @author Dave Longley - * @author Stefan Siegl - * - * Copyright (c) 2010-2014 Digital Bazaar, Inc. - * Copyright (c) 2012 Stefan Siegl - * - * The ASN.1 representation of PKCS#12 is as follows - * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details) - * - * PFX ::= SEQUENCE { - * version INTEGER {v3(3)}(v3,...), - * authSafe ContentInfo, - * macData MacData OPTIONAL - * } - * - * MacData ::= SEQUENCE { - * mac DigestInfo, - * macSalt OCTET STRING, - * iterations INTEGER DEFAULT 1 - * } - * Note: The iterations default is for historical reasons and its use is - * deprecated. A higher value, like 1024, is recommended. - * - * DigestInfo is defined in PKCS#7 as follows: - * - * DigestInfo ::= SEQUENCE { - * digestAlgorithm DigestAlgorithmIdentifier, - * digest Digest - * } - * - * DigestAlgorithmIdentifier ::= AlgorithmIdentifier - * - * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters - * for the algorithm, if any. In the case of SHA1 there is none. - * - * AlgorithmIdentifer ::= SEQUENCE { - * algorithm OBJECT IDENTIFIER, - * parameters ANY DEFINED BY algorithm OPTIONAL - * } - * - * Digest ::= OCTET STRING - * - * - * ContentInfo ::= SEQUENCE { - * contentType ContentType, - * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL - * } - * - * ContentType ::= OBJECT IDENTIFIER - * - * AuthenticatedSafe ::= SEQUENCE OF ContentInfo - * -- Data if unencrypted - * -- EncryptedData if password-encrypted - * -- EnvelopedData if public key-encrypted - * - * - * SafeContents ::= SEQUENCE OF SafeBag - * - * SafeBag ::= SEQUENCE { - * bagId BAG-TYPE.&id ({PKCS12BagSet}) - * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}), - * bagAttributes SET OF PKCS12Attribute OPTIONAL - * } - * - * PKCS12Attribute ::= SEQUENCE { - * attrId ATTRIBUTE.&id ({PKCS12AttrSet}), - * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId}) - * } -- This type is compatible with the X.500 type 'Attribute' - * - * PKCS12AttrSet ATTRIBUTE ::= { - * friendlyName | -- from PKCS #9 - * localKeyId, -- from PKCS #9 - * ... -- Other attributes are allowed - * } - * - * CertBag ::= SEQUENCE { - * certId BAG-TYPE.&id ({CertTypes}), - * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId}) - * } - * - * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}} - * -- DER-encoded X.509 certificate stored in OCTET STRING - * - * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}} - * -- Base64-encoded SDSI certificate stored in IA5String - * - * CertTypes BAG-TYPE ::= { - * x509Certificate | - * sdsiCertificate, - * ... -- For future extensions - * } - */ - -var forge$d = forge$F; - - - - - - - - - - - -// shortcut for asn.1 & PKI API -var asn1$3 = forge$d.asn1; -var pki$1 = forge$d.pki; - -// shortcut for PKCS#12 API -var p12 = forge$d.pkcs12 = forge$d.pkcs12 || {}; - -var contentInfoValidator = { - name: 'ContentInfo', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SEQUENCE, // a ContentInfo - constructed: true, - value: [{ - name: 'ContentInfo.contentType', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.OID, - constructed: false, - capture: 'contentType' - }, { - name: 'ContentInfo.content', - tagClass: asn1$3.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: 'content' - }] -}; - -var pfxValidator = { - name: 'PFX', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'PFX.version', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.INTEGER, - constructed: false, - capture: 'version' - }, - contentInfoValidator, { - name: 'PFX.macData', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'mac', - value: [{ - name: 'PFX.macData.mac', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SEQUENCE, // DigestInfo - constructed: true, - value: [{ - name: 'PFX.macData.mac.digestAlgorithm', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SEQUENCE, // DigestAlgorithmIdentifier - constructed: true, - value: [{ - name: 'PFX.macData.mac.digestAlgorithm.algorithm', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.OID, - constructed: false, - capture: 'macAlgorithm' - }, { - name: 'PFX.macData.mac.digestAlgorithm.parameters', - tagClass: asn1$3.Class.UNIVERSAL, - captureAsn1: 'macAlgorithmParameters' - }] - }, { - name: 'PFX.macData.mac.digest', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.OCTETSTRING, - constructed: false, - capture: 'macDigest' - }] - }, { - name: 'PFX.macData.macSalt', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.OCTETSTRING, - constructed: false, - capture: 'macSalt' - }, { - name: 'PFX.macData.iterations', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.INTEGER, - constructed: false, - optional: true, - capture: 'macIterations' - }] - }] -}; - -var safeBagValidator = { - name: 'SafeBag', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'SafeBag.bagId', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.OID, - constructed: false, - capture: 'bagId' - }, { - name: 'SafeBag.bagValue', - tagClass: asn1$3.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: 'bagValue' - }, { - name: 'SafeBag.bagAttributes', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SET, - constructed: true, - optional: true, - capture: 'bagAttributes' - }] -}; - -var attributeValidator = { - name: 'Attribute', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'Attribute.attrId', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.OID, - constructed: false, - capture: 'oid' - }, { - name: 'Attribute.attrValues', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SET, - constructed: true, - capture: 'values' - }] -}; - -var certBagValidator = { - name: 'CertBag', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'CertBag.certId', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Type.OID, - constructed: false, - capture: 'certId' - }, { - name: 'CertBag.certValue', - tagClass: asn1$3.Class.CONTEXT_SPECIFIC, - constructed: true, - /* So far we only support X.509 certificates (which are wrapped in - an OCTET STRING, hence hard code that here). */ - value: [{ - name: 'CertBag.certValue[0]', - tagClass: asn1$3.Class.UNIVERSAL, - type: asn1$3.Class.OCTETSTRING, - constructed: false, - capture: 'cert' - }] - }] -}; - -/** - * Search SafeContents structure for bags with matching attributes. - * - * The search can optionally be narrowed by a certain bag type. - * - * @param safeContents the SafeContents structure to search in. - * @param attrName the name of the attribute to compare against. - * @param attrValue the attribute value to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of matching bags. - */ -function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { - var result = []; - - for(var i = 0; i < safeContents.length; i++) { - for(var j = 0; j < safeContents[i].safeBags.length; j++) { - var bag = safeContents[i].safeBags[j]; - if(bagType !== undefined && bag.type !== bagType) { - continue; - } - // only filter by bag type, no attribute specified - if(attrName === null) { - result.push(bag); - continue; - } - if(bag.attributes[attrName] !== undefined && - bag.attributes[attrName].indexOf(attrValue) >= 0) { - result.push(bag); - } - } - } - - return result; -} - -/** - * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object. - * - * @param obj The PKCS#12 PFX in ASN.1 notation. - * @param strict true to use strict DER decoding, false not to (default: true). - * @param {String} password Password to decrypt with (optional). - * - * @return PKCS#12 PFX object. - */ -p12.pkcs12FromAsn1 = function(obj, strict, password) { - // handle args - if(typeof strict === 'string') { - password = strict; - strict = true; - } else if(strict === undefined) { - strict = true; - } - - // validate PFX and capture data - var capture = {}; - var errors = []; - if(!asn1$3.validate(obj, pfxValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#12 PFX. ' + - 'ASN.1 object is not an PKCS#12 PFX.'); - error.errors = error; - throw error; - } - - var pfx = { - version: capture.version.charCodeAt(0), - safeContents: [], - - /** - * Gets bags with matching attributes. - * - * @param filter the attributes to filter by: - * [localKeyId] the localKeyId to search for. - * [localKeyIdHex] the localKeyId in hex to search for. - * [friendlyName] the friendly name to search for. - * [bagType] bag type to narrow each attribute search by. - * - * @return a map of attribute type to an array of matching bags or, if no - * attribute was given but a bag type, the map key will be the - * bag type. - */ - getBags: function(filter) { - var rval = {}; - - var localKeyId; - if('localKeyId' in filter) { - localKeyId = filter.localKeyId; - } else if('localKeyIdHex' in filter) { - localKeyId = forge$d.util.hexToBytes(filter.localKeyIdHex); - } - - // filter on bagType only - if(localKeyId === undefined && !('friendlyName' in filter) && - 'bagType' in filter) { - rval[filter.bagType] = _getBagsByAttribute( - pfx.safeContents, null, null, filter.bagType); - } - - if(localKeyId !== undefined) { - rval.localKeyId = _getBagsByAttribute( - pfx.safeContents, 'localKeyId', - localKeyId, filter.bagType); - } - if('friendlyName' in filter) { - rval.friendlyName = _getBagsByAttribute( - pfx.safeContents, 'friendlyName', - filter.friendlyName, filter.bagType); - } - - return rval; - }, - - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching friendlyName attribute. - * - * @param friendlyName the friendly name to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching friendlyName attribute. - */ - getBagsByFriendlyName: function(friendlyName, bagType) { - return _getBagsByAttribute( - pfx.safeContents, 'friendlyName', friendlyName, bagType); - }, - - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching localKeyId attribute. - * - * @param localKeyId the localKeyId to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching localKeyId attribute. - */ - getBagsByLocalKeyId: function(localKeyId, bagType) { - return _getBagsByAttribute( - pfx.safeContents, 'localKeyId', localKeyId, bagType); - } - }; - - if(capture.version.charCodeAt(0) !== 3) { - var error = new Error('PKCS#12 PFX of version other than 3 not supported.'); - error.version = capture.version.charCodeAt(0); - throw error; - } - - if(asn1$3.derToOid(capture.contentType) !== pki$1.oids.data) { - var error = new Error('Only PKCS#12 PFX in password integrity mode supported.'); - error.oid = asn1$3.derToOid(capture.contentType); - throw error; - } - - var data = capture.content.value[0]; - if(data.tagClass !== asn1$3.Class.UNIVERSAL || - data.type !== asn1$3.Type.OCTETSTRING) { - throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.'); - } - data = _decodePkcs7Data(data); - - // check for MAC - if(capture.mac) { - var md = null; - var macKeyBytes = 0; - var macAlgorithm = asn1$3.derToOid(capture.macAlgorithm); - switch(macAlgorithm) { - case pki$1.oids.sha1: - md = forge$d.md.sha1.create(); - macKeyBytes = 20; - break; - case pki$1.oids.sha256: - md = forge$d.md.sha256.create(); - macKeyBytes = 32; - break; - case pki$1.oids.sha384: - md = forge$d.md.sha384.create(); - macKeyBytes = 48; - break; - case pki$1.oids.sha512: - md = forge$d.md.sha512.create(); - macKeyBytes = 64; - break; - case pki$1.oids.md5: - md = forge$d.md.md5.create(); - macKeyBytes = 16; - break; - } - if(md === null) { - throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm); - } - - // verify MAC (iterations default to 1) - var macSalt = new forge$d.util.ByteBuffer(capture.macSalt); - var macIterations = (('macIterations' in capture) ? - parseInt(forge$d.util.bytesToHex(capture.macIterations), 16) : 1); - var macKey = p12.generateKey( - password, macSalt, 3, macIterations, macKeyBytes, md); - var mac = forge$d.hmac.create(); - mac.start(md, macKey); - mac.update(data.value); - var macValue = mac.getMac(); - if(macValue.getBytes() !== capture.macDigest) { - throw new Error('PKCS#12 MAC could not be verified. Invalid password?'); - } - } - - _decodeAuthenticatedSafe(pfx, data.value, strict, password); - return pfx; -}; - -/** - * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING, - * but it is sometimes an OCTET STRING that is composed/constructed of chunks, - * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This - * function transforms this corner-case into the usual simple, - * non-composed/constructed OCTET STRING. - * - * This function may be moved to ASN.1 at some point to better deal with - * more BER-encoding issues, should they arise. - * - * @param data the ASN.1 Data object to transform. - */ -function _decodePkcs7Data(data) { - // handle special case of "chunked" data content: an octet string composed - // of other octet strings - if(data.composed || data.constructed) { - var value = forge$d.util.createBuffer(); - for(var i = 0; i < data.value.length; ++i) { - value.putBytes(data.value[i].value); - } - data.composed = data.constructed = false; - data.value = value.getBytes(); - } - return data; -} - -/** - * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object. - * - * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo. - * - * @param pfx The PKCS#12 PFX object to fill. - * @param {String} authSafe BER-encoded AuthenticatedSafe. - * @param strict true to use strict DER decoding, false not to. - * @param {String} password Password to decrypt with (optional). - */ -function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { - authSafe = asn1$3.fromDer(authSafe, strict); /* actually it's BER encoded */ - - if(authSafe.tagClass !== asn1$3.Class.UNIVERSAL || - authSafe.type !== asn1$3.Type.SEQUENCE || - authSafe.constructed !== true) { - throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' + - 'SEQUENCE OF ContentInfo'); - } - - for(var i = 0; i < authSafe.value.length; i++) { - var contentInfo = authSafe.value[i]; - - // validate contentInfo and capture data - var capture = {}; - var errors = []; - if(!asn1$3.validate(contentInfo, contentInfoValidator, capture, errors)) { - var error = new Error('Cannot read ContentInfo.'); - error.errors = errors; - throw error; - } - - var obj = { - encrypted: false - }; - var safeContents = null; - var data = capture.content.value[0]; - switch(asn1$3.derToOid(capture.contentType)) { - case pki$1.oids.data: - if(data.tagClass !== asn1$3.Class.UNIVERSAL || - data.type !== asn1$3.Type.OCTETSTRING) { - throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.'); - } - safeContents = _decodePkcs7Data(data).value; - break; - case pki$1.oids.encryptedData: - safeContents = _decryptSafeContents(data, password); - obj.encrypted = true; - break; - default: - var error = new Error('Unsupported PKCS#12 contentType.'); - error.contentType = asn1$3.derToOid(capture.contentType); - throw error; - } - - obj.safeBags = _decodeSafeContents(safeContents, strict, password); - pfx.safeContents.push(obj); - } -} - -/** - * Decrypt PKCS#7 EncryptedData structure. - * - * @param data ASN.1 encoded EncryptedContentInfo object. - * @param password The user-provided password. - * - * @return The decrypted SafeContents (ASN.1 object). - */ -function _decryptSafeContents(data, password) { - var capture = {}; - var errors = []; - if(!asn1$3.validate( - data, forge$d.pkcs7.asn1.encryptedDataValidator, capture, errors)) { - var error = new Error('Cannot read EncryptedContentInfo.'); - error.errors = errors; - throw error; - } - - var oid = asn1$3.derToOid(capture.contentType); - if(oid !== pki$1.oids.data) { - var error = new Error( - 'PKCS#12 EncryptedContentInfo ContentType is not Data.'); - error.oid = oid; - throw error; - } - - // get cipher - oid = asn1$3.derToOid(capture.encAlgorithm); - var cipher = pki$1.pbe.getCipher(oid, capture.encParameter, password); - - // get encrypted data - var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); - var encrypted = forge$d.util.createBuffer(encryptedContentAsn1.value); - - cipher.update(encrypted); - if(!cipher.finish()) { - throw new Error('Failed to decrypt PKCS#12 SafeContents.'); - } - - return cipher.output.getBytes(); -} - -/** - * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects. - * - * The safeContents is a BER-encoded SEQUENCE OF SafeBag. - * - * @param {String} safeContents BER-encoded safeContents. - * @param strict true to use strict DER decoding, false not to. - * @param {String} password Password to decrypt with (optional). - * - * @return {Array} Array of Bag objects. - */ -function _decodeSafeContents(safeContents, strict, password) { - // if strict and no safe contents, return empty safes - if(!strict && safeContents.length === 0) { - return []; - } - - // actually it's BER-encoded - safeContents = asn1$3.fromDer(safeContents, strict); - - if(safeContents.tagClass !== asn1$3.Class.UNIVERSAL || - safeContents.type !== asn1$3.Type.SEQUENCE || - safeContents.constructed !== true) { - throw new Error( - 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.'); - } - - var res = []; - for(var i = 0; i < safeContents.value.length; i++) { - var safeBag = safeContents.value[i]; - - // validate SafeBag and capture data - var capture = {}; - var errors = []; - if(!asn1$3.validate(safeBag, safeBagValidator, capture, errors)) { - var error = new Error('Cannot read SafeBag.'); - error.errors = errors; - throw error; - } - - /* Create bag object and push to result array. */ - var bag = { - type: asn1$3.derToOid(capture.bagId), - attributes: _decodeBagAttributes(capture.bagAttributes) - }; - res.push(bag); - - var validator, decoder; - var bagAsn1 = capture.bagValue.value[0]; - switch(bag.type) { - case pki$1.oids.pkcs8ShroudedKeyBag: - /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt. - Afterwards we can handle it like a keyBag, - which is a PrivateKeyInfo. */ - bagAsn1 = pki$1.decryptPrivateKeyInfo(bagAsn1, password); - if(bagAsn1 === null) { - throw new Error( - 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?'); - } - - /* fall through */ - case pki$1.oids.keyBag: - /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our - PKI module, hence we don't have to do validation/capturing here, - just pass what we already got. */ - try { - bag.key = pki$1.privateKeyFromAsn1(bagAsn1); - } catch(e) { - // ignore unknown key type, pass asn1 value - bag.key = null; - bag.asn1 = bagAsn1; - } - continue; /* Nothing more to do. */ - - case pki$1.oids.certBag: - /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates. - Therefore put the SafeBag content through another validator to - capture the fields. Afterwards check & store the results. */ - validator = certBagValidator; - decoder = function() { - if(asn1$3.derToOid(capture.certId) !== pki$1.oids.x509Certificate) { - var error = new Error( - 'Unsupported certificate type, only X.509 supported.'); - error.oid = asn1$3.derToOid(capture.certId); - throw error; - } - - // true=produce cert hash - var certAsn1 = asn1$3.fromDer(capture.cert, strict); - try { - bag.cert = pki$1.certificateFromAsn1(certAsn1, true); - } catch(e) { - // ignore unknown cert type, pass asn1 value - bag.cert = null; - bag.asn1 = certAsn1; - } - }; - break; - - default: - var error = new Error('Unsupported PKCS#12 SafeBag type.'); - error.oid = bag.type; - throw error; - } - - /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */ - if(validator !== undefined && - !asn1$3.validate(bagAsn1, validator, capture, errors)) { - var error = new Error('Cannot read PKCS#12 ' + validator.name); - error.errors = errors; - throw error; - } - - /* Call decoder function from above to store the results. */ - decoder(); - } - - return res; -} - -/** - * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object. - * - * @param attributes SET OF PKCS12Attribute (ASN.1 object). - * - * @return the decoded attributes. - */ -function _decodeBagAttributes(attributes) { - var decodedAttrs = {}; - - if(attributes !== undefined) { - for(var i = 0; i < attributes.length; ++i) { - var capture = {}; - var errors = []; - if(!asn1$3.validate(attributes[i], attributeValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#12 BagAttribute.'); - error.errors = errors; - throw error; - } - - var oid = asn1$3.derToOid(capture.oid); - if(pki$1.oids[oid] === undefined) { - // unsupported attribute type, ignore. - continue; - } - - decodedAttrs[pki$1.oids[oid]] = []; - for(var j = 0; j < capture.values.length; ++j) { - decodedAttrs[pki$1.oids[oid]].push(capture.values[j].value); - } - } - } - - return decodedAttrs; -} - -/** - * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a - * password is provided then the private key will be encrypted. - * - * An entire certificate chain may also be included. To do this, pass - * an array for the "cert" parameter where the first certificate is - * the one that is paired with the private key and each subsequent one - * verifies the previous one. The certificates may be in PEM format or - * have been already parsed by Forge. - * - * @todo implement password-based-encryption for the whole package - * - * @param key the private key. - * @param cert the certificate (may be an array of certificates in order - * to specify a certificate chain). - * @param password the password to use, null for none. - * @param options: - * algorithm the encryption algorithm to use - * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. - * count the iteration count to use. - * saltSize the salt size to use. - * useMac true to include a MAC, false not to, defaults to true. - * localKeyId the local key ID to use, in hex. - * friendlyName the friendly name to use. - * generateLocalKeyId true to generate a random local key ID, - * false not to, defaults to true. - * - * @return the PKCS#12 PFX ASN.1 object. - */ -p12.toPkcs12Asn1 = function(key, cert, password, options) { - // set default options - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || options.encAlgorithm || 'aes128'; - if(!('useMac' in options)) { - options.useMac = true; - } - if(!('localKeyId' in options)) { - options.localKeyId = null; - } - if(!('generateLocalKeyId' in options)) { - options.generateLocalKeyId = true; - } - - var localKeyId = options.localKeyId; - var bagAttrs; - if(localKeyId !== null) { - localKeyId = forge$d.util.hexToBytes(localKeyId); - } else if(options.generateLocalKeyId) { - // use SHA-1 of paired cert, if available - if(cert) { - var pairedCert = forge$d.util.isArray(cert) ? cert[0] : cert; - if(typeof pairedCert === 'string') { - pairedCert = pki$1.certificateFromPem(pairedCert); - } - var sha1 = forge$d.md.sha1.create(); - sha1.update(asn1$3.toDer(pki$1.certificateToAsn1(pairedCert)).getBytes()); - localKeyId = sha1.digest().getBytes(); - } else { - // FIXME: consider using SHA-1 of public key (which can be generated - // from private key components), see: cert.generateSubjectKeyIdentifier - // generate random bytes - localKeyId = forge$d.random.getBytes(20); - } - } - - var attrs = []; - if(localKeyId !== null) { - attrs.push( - // localKeyID - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // attrId - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - asn1$3.oidToDer(pki$1.oids.localKeyId).getBytes()), - // attrValues - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SET, true, [ - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, - localKeyId) - ]) - ])); - } - if('friendlyName' in options) { - attrs.push( - // friendlyName - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // attrId - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - asn1$3.oidToDer(pki$1.oids.friendlyName).getBytes()), - // attrValues - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SET, true, [ - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.BMPSTRING, false, - options.friendlyName) - ]) - ])); - } - - if(attrs.length > 0) { - bagAttrs = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SET, true, attrs); - } - - // collect contents for AuthenticatedSafe - var contents = []; - - // create safe bag(s) for certificate chain - var chain = []; - if(cert !== null) { - if(forge$d.util.isArray(cert)) { - chain = cert; - } else { - chain = [cert]; - } - } - - var certSafeBags = []; - for(var i = 0; i < chain.length; ++i) { - // convert cert from PEM as necessary - cert = chain[i]; - if(typeof cert === 'string') { - cert = pki$1.certificateFromPem(cert); - } - - // SafeBag - var certBagAttrs = (i === 0) ? bagAttrs : undefined; - var certAsn1 = pki$1.certificateToAsn1(cert); - var certSafeBag = - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // bagId - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - asn1$3.oidToDer(pki$1.oids.certBag).getBytes()), - // bagValue - asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ - // CertBag - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // certId - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - asn1$3.oidToDer(pki$1.oids.x509Certificate).getBytes()), - // certValue (x509Certificate) - asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1$3.create( - asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, - asn1$3.toDer(certAsn1).getBytes()) - ])])]), - // bagAttributes (OPTIONAL) - certBagAttrs - ]); - certSafeBags.push(certSafeBag); - } - - if(certSafeBags.length > 0) { - // SafeContents - var certSafeContents = asn1$3.create( - asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, certSafeBags); - - // ContentInfo - var certCI = - // PKCS#7 ContentInfo - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // contentType - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - // OID for the content type is 'data' - asn1$3.oidToDer(pki$1.oids.data).getBytes()), - // content - asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1$3.create( - asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, - asn1$3.toDer(certSafeContents).getBytes()) - ]) - ]); - contents.push(certCI); - } - - // create safe contents for private key - var keyBag = null; - if(key !== null) { - // SafeBag - var pkAsn1 = pki$1.wrapRsaPrivateKey(pki$1.privateKeyToAsn1(key)); - if(password === null) { - // no encryption - keyBag = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // bagId - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - asn1$3.oidToDer(pki$1.oids.keyBag).getBytes()), - // bagValue - asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ - // PrivateKeyInfo - pkAsn1 - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } else { - // encrypted PrivateKeyInfo - keyBag = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // bagId - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - asn1$3.oidToDer(pki$1.oids.pkcs8ShroudedKeyBag).getBytes()), - // bagValue - asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ - // EncryptedPrivateKeyInfo - pki$1.encryptPrivateKeyInfo(pkAsn1, password, options) - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } - - // SafeContents - var keySafeContents = - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [keyBag]); - - // ContentInfo - var keyCI = - // PKCS#7 ContentInfo - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // contentType - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - // OID for the content type is 'data' - asn1$3.oidToDer(pki$1.oids.data).getBytes()), - // content - asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1$3.create( - asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, - asn1$3.toDer(keySafeContents).getBytes()) - ]) - ]); - contents.push(keyCI); - } - - // create AuthenticatedSafe by stringing together the contents - var safe = asn1$3.create( - asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, contents); - - var macData; - if(options.useMac) { - // MacData - var sha1 = forge$d.md.sha1.create(); - var macSalt = new forge$d.util.ByteBuffer( - forge$d.random.getBytes(options.saltSize)); - var count = options.count; - // 160-bit key - var key = p12.generateKey(password, macSalt, 3, count, 20); - var mac = forge$d.hmac.create(); - mac.start(sha1, key); - mac.update(asn1$3.toDer(safe).getBytes()); - var macValue = mac.getMac(); - macData = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // mac DigestInfo - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // digestAlgorithm - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // algorithm = SHA-1 - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - asn1$3.oidToDer(pki$1.oids.sha1).getBytes()), - // parameters = Null - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.NULL, false, '') - ]), - // digest - asn1$3.create( - asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, - false, macValue.getBytes()) - ]), - // macSalt OCTET STRING - asn1$3.create( - asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, macSalt.getBytes()), - // iterations INTEGER (XXX: Only support count < 65536) - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.INTEGER, false, - asn1$3.integerToDer(count).getBytes() - ) - ]); - } - - // PFX - return asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // version (3) - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.INTEGER, false, - asn1$3.integerToDer(3).getBytes()), - // PKCS#7 ContentInfo - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [ - // contentType - asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false, - // OID for the content type is 'data' - asn1$3.oidToDer(pki$1.oids.data).getBytes()), - // content - asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1$3.create( - asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, - asn1$3.toDer(safe).getBytes()) - ]) - ]), - macData - ]); -}; - -/** - * Derives a PKCS#12 key. - * - * @param password the password to derive the key material from, null or - * undefined for none. - * @param salt the salt, as a ByteBuffer, to use. - * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). - * @param iter the iteration count. - * @param n the number of bytes to derive from the password. - * @param md the message digest to use, defaults to SHA-1. - * - * @return a ByteBuffer with the bytes derived from the password. - */ -p12.generateKey = forge$d.pbe.generatePkcs12Key; - -/** - * Javascript implementation of a basic Public Key Infrastructure, including - * support for RSA public and private keys. - * - * @author Dave Longley - * - * Copyright (c) 2010-2013 Digital Bazaar, Inc. - */ - -var forge$c = forge$F; - - - - - - - - - - - -// shortcut for asn.1 API -var asn1$2 = forge$c.asn1; - -/* Public Key Infrastructure (PKI) implementation. */ -var pki = forge$c.pki = forge$c.pki || {}; - -/** - * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead. - * - * Converts PEM-formatted data to DER. - * - * @param pem the PEM-formatted data. - * - * @return the DER-formatted data. - */ -pki.pemToDer = function(pem) { - var msg = forge$c.pem.decode(pem)[0]; - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert PEM to DER; PEM is encrypted.'); - } - return forge$c.util.createBuffer(msg.body); -}; - -/** - * Converts an RSA private key from PEM format. - * - * @param pem the PEM-formatted private key. - * - * @return the private key. - */ -pki.privateKeyFromPem = function(pem) { - var msg = forge$c.pem.decode(pem)[0]; - - if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { - var error = new Error('Could not convert private key from PEM; PEM ' + - 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert private key from PEM; PEM is encrypted.'); - } - - // convert DER to ASN.1 object - var obj = asn1$2.fromDer(msg.body); - - return pki.privateKeyFromAsn1(obj); -}; - -/** - * Converts an RSA private key to PEM format. - * - * @param key the private key. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted private key. - */ -pki.privateKeyToPem = function(key, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var msg = { - type: 'RSA PRIVATE KEY', - body: asn1$2.toDer(pki.privateKeyToAsn1(key)).getBytes() - }; - return forge$c.pem.encode(msg, {maxline: maxline}); -}; - -/** - * Converts a PrivateKeyInfo to PEM format. - * - * @param pki the PrivateKeyInfo. - * @param maxline the maximum characters per line, defaults to 64. - * - * @return the PEM-formatted private key. - */ -pki.privateKeyInfoToPem = function(pki, maxline) { - // convert to DER, then PEM-encode - var msg = { - type: 'PRIVATE KEY', - body: asn1$2.toDer(pki).getBytes() - }; - return forge$c.pem.encode(msg, {maxline: maxline}); -}; - -/** - * A Javascript implementation of Transport Layer Security (TLS). - * - * @author Dave Longley - * - * Copyright (c) 2009-2014 Digital Bazaar, Inc. - * - * The TLS Handshake Protocol involves the following steps: - * - * - Exchange hello messages to agree on algorithms, exchange random values, - * and check for session resumption. - * - * - Exchange the necessary cryptographic parameters to allow the client and - * server to agree on a premaster secret. - * - * - Exchange certificates and cryptographic information to allow the client - * and server to authenticate themselves. - * - * - Generate a master secret from the premaster secret and exchanged random - * values. - * - * - Provide security parameters to the record layer. - * - * - Allow the client and server to verify that their peer has calculated the - * same security parameters and that the handshake occurred without tampering - * by an attacker. - * - * Up to 4 different messages may be sent during a key exchange. The server - * certificate, the server key exchange, the client certificate, and the - * client key exchange. - * - * A typical handshake (from the client's perspective). - * - * 1. Client sends ClientHello. - * 2. Client receives ServerHello. - * 3. Client receives optional Certificate. - * 4. Client receives optional ServerKeyExchange. - * 5. Client receives ServerHelloDone. - * 6. Client sends optional Certificate. - * 7. Client sends ClientKeyExchange. - * 8. Client sends optional CertificateVerify. - * 9. Client sends ChangeCipherSpec. - * 10. Client sends Finished. - * 11. Client receives ChangeCipherSpec. - * 12. Client receives Finished. - * 13. Client sends/receives application data. - * - * To reuse an existing session: - * - * 1. Client sends ClientHello with session ID for reuse. - * 2. Client receives ServerHello with same session ID if reusing. - * 3. Client receives ChangeCipherSpec message if reusing. - * 4. Client receives Finished. - * 5. Client sends ChangeCipherSpec. - * 6. Client sends Finished. - * - * Note: Client ignores HelloRequest if in the middle of a handshake. - * - * Record Layer: - * - * The record layer fragments information blocks into TLSPlaintext records - * carrying data in chunks of 2^14 bytes or less. Client message boundaries are - * not preserved in the record layer (i.e., multiple client messages of the - * same ContentType MAY be coalesced into a single TLSPlaintext record, or a - * single message MAY be fragmented across several records). - * - * struct { - * uint8 major; - * uint8 minor; - * } ProtocolVersion; - * - * struct { - * ContentType type; - * ProtocolVersion version; - * uint16 length; - * opaque fragment[TLSPlaintext.length]; - * } TLSPlaintext; - * - * type: - * The higher-level protocol used to process the enclosed fragment. - * - * version: - * The version of the protocol being employed. TLS Version 1.2 uses version - * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that - * supports multiple versions of TLS may not know what version will be - * employed before it receives the ServerHello. - * - * length: - * The length (in bytes) of the following TLSPlaintext.fragment. The length - * MUST NOT exceed 2^14 = 16384 bytes. - * - * fragment: - * The application data. This data is transparent and treated as an - * independent block to be dealt with by the higher-level protocol specified - * by the type field. - * - * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or - * ChangeCipherSpec content types. Zero-length fragments of Application data - * MAY be sent as they are potentially useful as a traffic analysis - * countermeasure. - * - * Note: Data of different TLS record layer content types MAY be interleaved. - * Application data is generally of lower precedence for transmission than - * other content types. However, records MUST be delivered to the network in - * the same order as they are protected by the record layer. Recipients MUST - * receive and process interleaved application layer traffic during handshakes - * subsequent to the first one on a connection. - * - * struct { - * ContentType type; // same as TLSPlaintext.type - * ProtocolVersion version;// same as TLSPlaintext.version - * uint16 length; - * opaque fragment[TLSCompressed.length]; - * } TLSCompressed; - * - * length: - * The length (in bytes) of the following TLSCompressed.fragment. - * The length MUST NOT exceed 2^14 + 1024. - * - * fragment: - * The compressed form of TLSPlaintext.fragment. - * - * Note: A CompressionMethod.null operation is an identity operation; no fields - * are altered. In this implementation, since no compression is supported, - * uncompressed records are always the same as compressed records. - * - * Encryption Information: - * - * The encryption and MAC functions translate a TLSCompressed structure into a - * TLSCiphertext. The decryption functions reverse the process. The MAC of the - * record also includes a sequence number so that missing, extra, or repeated - * messages are detectable. - * - * struct { - * ContentType type; - * ProtocolVersion version; - * uint16 length; - * select (SecurityParameters.cipher_type) { - * case stream: GenericStreamCipher; - * case block: GenericBlockCipher; - * case aead: GenericAEADCipher; - * } fragment; - * } TLSCiphertext; - * - * type: - * The type field is identical to TLSCompressed.type. - * - * version: - * The version field is identical to TLSCompressed.version. - * - * length: - * The length (in bytes) of the following TLSCiphertext.fragment. - * The length MUST NOT exceed 2^14 + 2048. - * - * fragment: - * The encrypted form of TLSCompressed.fragment, with the MAC. - * - * Note: Only CBC Block Ciphers are supported by this implementation. - * - * The TLSCompressed.fragment structures are converted to/from block - * TLSCiphertext.fragment structures. - * - * struct { - * opaque IV[SecurityParameters.record_iv_length]; - * block-ciphered struct { - * opaque content[TLSCompressed.length]; - * opaque MAC[SecurityParameters.mac_length]; - * uint8 padding[GenericBlockCipher.padding_length]; - * uint8 padding_length; - * }; - * } GenericBlockCipher; - * - * The MAC is generated as described in Section 6.2.3.1. - * - * IV: - * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be - * unpredictable. Note that in versions of TLS prior to 1.1, there was no - * IV field, and the last ciphertext block of the previous record (the "CBC - * residue") was used as the IV. This was changed to prevent the attacks - * described in [CBCATT]. For block ciphers, the IV length is of length - * SecurityParameters.record_iv_length, which is equal to the - * SecurityParameters.block_size. - * - * padding: - * Padding that is added to force the length of the plaintext to be an - * integral multiple of the block cipher's block length. The padding MAY be - * any length up to 255 bytes, as long as it results in the - * TLSCiphertext.length being an integral multiple of the block length. - * Lengths longer than necessary might be desirable to frustrate attacks on - * a protocol that are based on analysis of the lengths of exchanged - * messages. Each uint8 in the padding data vector MUST be filled with the - * padding length value. The receiver MUST check this padding and MUST use - * the bad_record_mac alert to indicate padding errors. - * - * padding_length: - * The padding length MUST be such that the total size of the - * GenericBlockCipher structure is a multiple of the cipher's block length. - * Legal values range from zero to 255, inclusive. This length specifies the - * length of the padding field exclusive of the padding_length field itself. - * - * The encrypted data length (TLSCiphertext.length) is one more than the sum of - * SecurityParameters.block_length, TLSCompressed.length, - * SecurityParameters.mac_length, and padding_length. - * - * Example: If the block length is 8 bytes, the content length - * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the - * length before padding is 82 bytes (this does not include the IV. Thus, the - * padding length modulo 8 must be equal to 6 in order to make the total length - * an even multiple of 8 bytes (the block length). The padding length can be - * 6, 14, 22, and so on, through 254. If the padding length were the minimum - * necessary, 6, the padding would be 6 bytes, each containing the value 6. - * Thus, the last 8 octets of the GenericBlockCipher before block encryption - * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC. - * - * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical - * that the entire plaintext of the record be known before any ciphertext is - * transmitted. Otherwise, it is possible for the attacker to mount the attack - * described in [CBCATT]. - * - * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing - * attack on CBC padding based on the time required to compute the MAC. In - * order to defend against this attack, implementations MUST ensure that - * record processing time is essentially the same whether or not the padding - * is correct. In general, the best way to do this is to compute the MAC even - * if the padding is incorrect, and only then reject the packet. For instance, - * if the pad appears to be incorrect, the implementation might assume a - * zero-length pad and then compute the MAC. This leaves a small timing - * channel, since MAC performance depends, to some extent, on the size of the - * data fragment, but it is not believed to be large enough to be exploitable, - * due to the large block size of existing MACs and the small size of the - * timing signal. - */ - -var forge$b = forge$F; - - - - - - - - - -/** - * Generates pseudo random bytes by mixing the result of two hash functions, - * MD5 and SHA-1. - * - * prf_TLS1(secret, label, seed) = - * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed); - * - * Each P_hash function functions as follows: - * - * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + - * HMAC_hash(secret, A(2) + seed) + - * HMAC_hash(secret, A(3) + seed) + ... - * A() is defined as: - * A(0) = seed - * A(i) = HMAC_hash(secret, A(i-1)) - * - * The '+' operator denotes concatenation. - * - * As many iterations A(N) as are needed are performed to generate enough - * pseudo random byte output. If an iteration creates more data than is - * necessary, then it is truncated. - * - * Therefore: - * A(1) = HMAC_hash(secret, A(0)) - * = HMAC_hash(secret, seed) - * A(2) = HMAC_hash(secret, A(1)) - * = HMAC_hash(secret, HMAC_hash(secret, seed)) - * - * Therefore: - * P_hash(secret, seed) = - * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) + - * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) + - * ... - * - * Therefore: - * P_hash(secret, seed) = - * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) + - * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) + - * ... - * - * @param secret the secret to use. - * @param label the label to use. - * @param seed the seed value to use. - * @param length the number of bytes to generate. - * - * @return the pseudo random bytes in a byte buffer. - */ -var prf_TLS1 = function(secret, label, seed, length) { - var rval = forge$b.util.createBuffer(); - - /* For TLS 1.0, the secret is split in half, into two secrets of equal - length. If the secret has an odd length then the last byte of the first - half will be the same as the first byte of the second. The length of the - two secrets is half of the secret rounded up. */ - var idx = (secret.length >> 1); - var slen = idx + (secret.length & 1); - var s1 = secret.substr(0, slen); - var s2 = secret.substr(idx, slen); - var ai = forge$b.util.createBuffer(); - var hmac = forge$b.hmac.create(); - seed = label + seed; - - // determine the number of iterations that must be performed to generate - // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20 - var md5itr = Math.ceil(length / 16); - var sha1itr = Math.ceil(length / 20); - - // do md5 iterations - hmac.start('MD5', s1); - var md5bytes = forge$b.util.createBuffer(); - ai.putBytes(seed); - for(var i = 0; i < md5itr; ++i) { - // HMAC_hash(secret, A(i-1)) - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - - // HMAC_hash(secret, A(i) + seed) - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - md5bytes.putBuffer(hmac.digest()); - } - - // do sha1 iterations - hmac.start('SHA1', s2); - var sha1bytes = forge$b.util.createBuffer(); - ai.clear(); - ai.putBytes(seed); - for(var i = 0; i < sha1itr; ++i) { - // HMAC_hash(secret, A(i-1)) - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - - // HMAC_hash(secret, A(i) + seed) - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - sha1bytes.putBuffer(hmac.digest()); - } - - // XOR the md5 bytes with the sha1 bytes - rval.putBytes(forge$b.util.xorBytes( - md5bytes.getBytes(), sha1bytes.getBytes(), length)); - - return rval; -}; - -/** - * Gets a MAC for a record using the SHA-1 hash algorithm. - * - * @param key the mac key. - * @param state the sequence number (array of two 32-bit integers). - * @param record the record. - * - * @return the sha-1 hash (20 bytes) for the given record. - */ -var hmac_sha1 = function(key, seqNum, record) { - /* MAC is computed like so: - HMAC_hash( - key, seqNum + - TLSCompressed.type + - TLSCompressed.version + - TLSCompressed.length + - TLSCompressed.fragment) - */ - var hmac = forge$b.hmac.create(); - hmac.start('SHA1', key); - var b = forge$b.util.createBuffer(); - b.putInt32(seqNum[0]); - b.putInt32(seqNum[1]); - b.putByte(record.type); - b.putByte(record.version.major); - b.putByte(record.version.minor); - b.putInt16(record.length); - b.putBytes(record.fragment.bytes()); - hmac.update(b.getBytes()); - return hmac.digest().getBytes(); -}; - -/** - * Compresses the TLSPlaintext record into a TLSCompressed record using the - * deflate algorithm. - * - * @param c the TLS connection. - * @param record the TLSPlaintext record to compress. - * @param s the ConnectionState to use. - * - * @return true on success, false on failure. - */ -var deflate = function(c, record, s) { - var rval = false; - - try { - var bytes = c.deflate(record.fragment.getBytes()); - record.fragment = forge$b.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch(ex) { - // deflate error, fail out - } - - return rval; -}; - -/** - * Decompresses the TLSCompressed record into a TLSPlaintext record using the - * deflate algorithm. - * - * @param c the TLS connection. - * @param record the TLSCompressed record to decompress. - * @param s the ConnectionState to use. - * - * @return true on success, false on failure. - */ -var inflate = function(c, record, s) { - var rval = false; - - try { - var bytes = c.inflate(record.fragment.getBytes()); - record.fragment = forge$b.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch(ex) { - // inflate error, fail out - } - - return rval; -}; - -/** - * Reads a TLS variable-length vector from a byte buffer. - * - * Variable-length vectors are defined by specifying a subrange of legal - * lengths, inclusively, using the notation . When these are - * encoded, the actual length precedes the vector's contents in the byte - * stream. The length will be in the form of a number consuming as many bytes - * as required to hold the vector's specified maximum (ceiling) length. A - * variable-length vector with an actual length field of zero is referred to - * as an empty vector. - * - * @param b the byte buffer. - * @param lenBytes the number of bytes required to store the length. - * - * @return the resulting byte buffer. - */ -var readVector = function(b, lenBytes) { - var len = 0; - switch(lenBytes) { - case 1: - len = b.getByte(); - break; - case 2: - len = b.getInt16(); - break; - case 3: - len = b.getInt24(); - break; - case 4: - len = b.getInt32(); - break; - } - - // read vector bytes into a new buffer - return forge$b.util.createBuffer(b.getBytes(len)); -}; - -/** - * Writes a TLS variable-length vector to a byte buffer. - * - * @param b the byte buffer. - * @param lenBytes the number of bytes required to store the length. - * @param v the byte buffer vector. - */ -var writeVector = function(b, lenBytes, v) { - // encode length at the start of the vector, where the number of bytes for - // the length is the maximum number of bytes it would take to encode the - // vector's ceiling - b.putInt(v.length(), lenBytes << 3); - b.putBuffer(v); -}; - -/** - * The tls implementation. - */ -var tls$1 = {}; - -/** - * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and - * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time - * of this implementation so TLS 1.0 was implemented instead. - */ -tls$1.Versions = { - TLS_1_0: {major: 3, minor: 1}, - TLS_1_1: {major: 3, minor: 2}, - TLS_1_2: {major: 3, minor: 3} -}; -tls$1.SupportedVersions = [ - tls$1.Versions.TLS_1_1, - tls$1.Versions.TLS_1_0 -]; -tls$1.Version = tls$1.SupportedVersions[0]; - -/** - * Maximum fragment size. True maximum is 16384, but we fragment before that - * to allow for unusual small increases during compression. - */ -tls$1.MaxFragment = 16384 - 1024; - -/** - * Whether this entity is considered the "client" or "server". - * enum { server, client } ConnectionEnd; - */ -tls$1.ConnectionEnd = { - server: 0, - client: 1 -}; - -/** - * Pseudo-random function algorithm used to generate keys from the master - * secret. - * enum { tls_prf_sha256 } PRFAlgorithm; - */ -tls$1.PRFAlgorithm = { - tls_prf_sha256: 0 -}; - -/** - * Bulk encryption algorithms. - * enum { null, rc4, des3, aes } BulkCipherAlgorithm; - */ -tls$1.BulkCipherAlgorithm = { - none: null, - rc4: 0, - des3: 1, - aes: 2 -}; - -/** - * Cipher types. - * enum { stream, block, aead } CipherType; - */ -tls$1.CipherType = { - stream: 0, - block: 1, - aead: 2 -}; - -/** - * MAC (Message Authentication Code) algorithms. - * enum { null, hmac_md5, hmac_sha1, hmac_sha256, - * hmac_sha384, hmac_sha512} MACAlgorithm; - */ -tls$1.MACAlgorithm = { - none: null, - hmac_md5: 0, - hmac_sha1: 1, - hmac_sha256: 2, - hmac_sha384: 3, - hmac_sha512: 4 -}; - -/** - * Compression algorithms. - * enum { null(0), deflate(1), (255) } CompressionMethod; - */ -tls$1.CompressionMethod = { - none: 0, - deflate: 1 -}; - -/** - * TLS record content types. - * enum { - * change_cipher_spec(20), alert(21), handshake(22), - * application_data(23), (255) - * } ContentType; - */ -tls$1.ContentType = { - change_cipher_spec: 20, - alert: 21, - handshake: 22, - application_data: 23, - heartbeat: 24 -}; - -/** - * TLS handshake types. - * enum { - * hello_request(0), client_hello(1), server_hello(2), - * certificate(11), server_key_exchange (12), - * certificate_request(13), server_hello_done(14), - * certificate_verify(15), client_key_exchange(16), - * finished(20), (255) - * } HandshakeType; - */ -tls$1.HandshakeType = { - hello_request: 0, - client_hello: 1, - server_hello: 2, - certificate: 11, - server_key_exchange: 12, - certificate_request: 13, - server_hello_done: 14, - certificate_verify: 15, - client_key_exchange: 16, - finished: 20 -}; - -/** - * TLS Alert Protocol. - * - * enum { warning(1), fatal(2), (255) } AlertLevel; - * - * enum { - * close_notify(0), - * unexpected_message(10), - * bad_record_mac(20), - * decryption_failed(21), - * record_overflow(22), - * decompression_failure(30), - * handshake_failure(40), - * bad_certificate(42), - * unsupported_certificate(43), - * certificate_revoked(44), - * certificate_expired(45), - * certificate_unknown(46), - * illegal_parameter(47), - * unknown_ca(48), - * access_denied(49), - * decode_error(50), - * decrypt_error(51), - * export_restriction(60), - * protocol_version(70), - * insufficient_security(71), - * internal_error(80), - * user_canceled(90), - * no_renegotiation(100), - * (255) - * } AlertDescription; - * - * struct { - * AlertLevel level; - * AlertDescription description; - * } Alert; - */ -tls$1.Alert = {}; -tls$1.Alert.Level = { - warning: 1, - fatal: 2 -}; -tls$1.Alert.Description = { - close_notify: 0, - unexpected_message: 10, - bad_record_mac: 20, - decryption_failed: 21, - record_overflow: 22, - decompression_failure: 30, - handshake_failure: 40, - bad_certificate: 42, - unsupported_certificate: 43, - certificate_revoked: 44, - certificate_expired: 45, - certificate_unknown: 46, - illegal_parameter: 47, - unknown_ca: 48, - access_denied: 49, - decode_error: 50, - decrypt_error: 51, - export_restriction: 60, - protocol_version: 70, - insufficient_security: 71, - internal_error: 80, - user_canceled: 90, - no_renegotiation: 100 -}; - -/** - * TLS Heartbeat Message types. - * enum { - * heartbeat_request(1), - * heartbeat_response(2), - * (255) - * } HeartbeatMessageType; - */ -tls$1.HeartbeatMessageType = { - heartbeat_request: 1, - heartbeat_response: 2 -}; - -/** - * Supported cipher suites. - */ -tls$1.CipherSuites = {}; - -/** - * Gets a supported cipher suite from its 2 byte ID. - * - * @param twoBytes two bytes in a string. - * - * @return the matching supported cipher suite or null. - */ -tls$1.getCipherSuite = function(twoBytes) { - var rval = null; - for(var key in tls$1.CipherSuites) { - var cs = tls$1.CipherSuites[key]; - if(cs.id[0] === twoBytes.charCodeAt(0) && - cs.id[1] === twoBytes.charCodeAt(1)) { - rval = cs; - break; - } - } - return rval; -}; - -/** - * Called when an unexpected record is encountered. - * - * @param c the connection. - * @param record the record. - */ -tls$1.handleUnexpected = function(c, record) { - // if connection is client and closed, ignore unexpected messages - var ignore = (!c.open && c.entity === tls$1.ConnectionEnd.client); - if(!ignore) { - c.error(c, { - message: 'Unexpected message. Received TLS record out of order.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.unexpected_message - } - }); - } -}; - -/** - * Called when a client receives a HelloRequest record. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleHelloRequest = function(c, record, length) { - // ignore renegotiation requests from the server during a handshake, but - // if handshaking, send a warning alert that renegotation is denied - if(!c.handshaking && c.handshakes > 0) { - // send alert warning - tls$1.queue(c, tls$1.createAlert(c, { - level: tls$1.Alert.Level.warning, - description: tls$1.Alert.Description.no_renegotiation - })); - tls$1.flush(c); - } - - // continue - c.process(); -}; - -/** - * Parses a hello message from a ClientHello or ServerHello record. - * - * @param record the record to parse. - * - * @return the parsed message. - */ -tls$1.parseHelloMessage = function(c, record, length) { - var msg = null; - - var client = (c.entity === tls$1.ConnectionEnd.client); - - // minimum of 38 bytes in message - if(length < 38) { - c.error(c, { - message: client ? - 'Invalid ServerHello message. Message too short.' : - 'Invalid ClientHello message. Message too short.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.illegal_parameter - } - }); - } else { - // use 'remaining' to calculate # of remaining bytes in the message - var b = record.fragment; - var remaining = b.length(); - msg = { - version: { - major: b.getByte(), - minor: b.getByte() - }, - random: forge$b.util.createBuffer(b.getBytes(32)), - session_id: readVector(b, 1), - extensions: [] - }; - if(client) { - msg.cipher_suite = b.getBytes(2); - msg.compression_method = b.getByte(); - } else { - msg.cipher_suites = readVector(b, 2); - msg.compression_methods = readVector(b, 1); - } - - // read extensions if there are any bytes left in the message - remaining = length - (remaining - b.length()); - if(remaining > 0) { - // parse extensions - var exts = readVector(b, 2); - while(exts.length() > 0) { - msg.extensions.push({ - type: [exts.getByte(), exts.getByte()], - data: readVector(exts, 2) - }); - } - - // TODO: make extension support modular - if(!client) { - for(var i = 0; i < msg.extensions.length; ++i) { - var ext = msg.extensions[i]; - - // support SNI extension - if(ext.type[0] === 0x00 && ext.type[1] === 0x00) { - // get server name list - var snl = readVector(ext.data, 2); - while(snl.length() > 0) { - // read server name type - var snType = snl.getByte(); - - // only HostName type (0x00) is known, break out if - // another type is detected - if(snType !== 0x00) { - break; - } - - // add host name to server name list - c.session.extensions.server_name.serverNameList.push( - readVector(snl, 2).getBytes()); - } - } - } - } - } - - // version already set, do not allow version change - if(c.session.version) { - if(msg.version.major !== c.session.version.major || - msg.version.minor !== c.session.version.minor) { - return c.error(c, { - message: 'TLS version change is disallowed during renegotiation.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.protocol_version - } - }); - } - } - - // get the chosen (ServerHello) cipher suite - if(client) { - // FIXME: should be checking configured acceptable cipher suites - c.session.cipherSuite = tls$1.getCipherSuite(msg.cipher_suite); - } else { - // get a supported preferred (ClientHello) cipher suite - // choose the first supported cipher suite - var tmp = forge$b.util.createBuffer(msg.cipher_suites.bytes()); - while(tmp.length() > 0) { - // FIXME: should be checking configured acceptable suites - // cipher suites take up 2 bytes - c.session.cipherSuite = tls$1.getCipherSuite(tmp.getBytes(2)); - if(c.session.cipherSuite !== null) { - break; - } - } - } - - // cipher suite not supported - if(c.session.cipherSuite === null) { - return c.error(c, { - message: 'No cipher suites in common.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.handshake_failure - }, - cipherSuite: forge$b.util.bytesToHex(msg.cipher_suite) - }); - } - - // TODO: handle compression methods - if(client) { - c.session.compressionMethod = msg.compression_method; - } else { - // no compression - c.session.compressionMethod = tls$1.CompressionMethod.none; - } - } - - return msg; -}; - -/** - * Creates security parameters for the given connection based on the given - * hello message. - * - * @param c the TLS connection. - * @param msg the hello message. - */ -tls$1.createSecurityParameters = function(c, msg) { - /* Note: security params are from TLS 1.2, some values like prf_algorithm - are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is - used. */ - - // TODO: handle other options from server when more supported - - // get client and server randoms - var client = (c.entity === tls$1.ConnectionEnd.client); - var msgRandom = msg.random.bytes(); - var cRandom = client ? c.session.sp.client_random : msgRandom; - var sRandom = client ? msgRandom : tls$1.createRandom().getBytes(); - - // create new security parameters - c.session.sp = { - entity: c.entity, - prf_algorithm: tls$1.PRFAlgorithm.tls_prf_sha256, - bulk_cipher_algorithm: null, - cipher_type: null, - enc_key_length: null, - block_length: null, - fixed_iv_length: null, - record_iv_length: null, - mac_algorithm: null, - mac_length: null, - mac_key_length: null, - compression_algorithm: c.session.compressionMethod, - pre_master_secret: null, - master_secret: null, - client_random: cRandom, - server_random: sRandom - }; -}; - -/** - * Called when a client receives a ServerHello record. - * - * When a ServerHello message will be sent: - * The server will send this message in response to a client hello message - * when it was able to find an acceptable set of algorithms. If it cannot - * find such a match, it will respond with a handshake failure alert. - * - * uint24 length; - * struct { - * ProtocolVersion server_version; - * Random random; - * SessionID session_id; - * CipherSuite cipher_suite; - * CompressionMethod compression_method; - * select(extensions_present) { - * case false: - * struct {}; - * case true: - * Extension extensions<0..2^16-1>; - * }; - * } ServerHello; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleServerHello = function(c, record, length) { - var msg = tls$1.parseHelloMessage(c, record, length); - if(c.fail) { - return; - } - - // ensure server version is compatible - if(msg.version.minor <= c.version.minor) { - c.version.minor = msg.version.minor; - } else { - return c.error(c, { - message: 'Incompatible TLS version.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.protocol_version - } - }); - } - - // indicate session version has been set - c.session.version = c.version; - - // get the session ID from the message - var sessionId = msg.session_id.bytes(); - - // if the session ID is not blank and matches the cached one, resume - // the session - if(sessionId.length > 0 && sessionId === c.session.id) { - // resuming session, expect a ChangeCipherSpec next - c.expect = SCC; - c.session.resuming = true; - - // get new server random - c.session.sp.server_random = msg.random.bytes(); - } else { - // not resuming, expect a server Certificate message next - c.expect = SCE; - c.session.resuming = false; - - // create new security parameters - tls$1.createSecurityParameters(c, msg); - } - - // set new session ID - c.session.id = sessionId; - - // continue - c.process(); -}; - -/** - * Called when a server receives a ClientHello record. - * - * When a ClientHello message will be sent: - * When a client first connects to a server it is required to send the - * client hello as its first message. The client can also send a client - * hello in response to a hello request or on its own initiative in order - * to renegotiate the security parameters in an existing connection. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleClientHello = function(c, record, length) { - var msg = tls$1.parseHelloMessage(c, record, length); - if(c.fail) { - return; - } - - // get the session ID from the message - var sessionId = msg.session_id.bytes(); - - // see if the given session ID is in the cache - var session = null; - if(c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - if(session === null) { - // session ID not found - sessionId = ''; - } else if(session.version.major !== msg.version.major || - session.version.minor > msg.version.minor) { - // if session version is incompatible with client version, do not resume - session = null; - sessionId = ''; - } - } - - // no session found to resume, generate a new session ID - if(sessionId.length === 0) { - sessionId = forge$b.random.getBytes(32); - } - - // update session - c.session.id = sessionId; - c.session.clientHelloVersion = msg.version; - c.session.sp = {}; - if(session) { - // use version and security parameters from resumed session - c.version = c.session.version = session.version; - c.session.sp = session.sp; - } else { - // use highest compatible minor version - var version; - for(var i = 1; i < tls$1.SupportedVersions.length; ++i) { - version = tls$1.SupportedVersions[i]; - if(version.minor <= msg.version.minor) { - break; - } - } - c.version = {major: version.major, minor: version.minor}; - c.session.version = c.version; - } - - // if a session is set, resume it - if(session !== null) { - // resuming session, expect a ChangeCipherSpec next - c.expect = CCC; - c.session.resuming = true; - - // get new client random - c.session.sp.client_random = msg.random.bytes(); - } else { - // not resuming, expect a Certificate or ClientKeyExchange - c.expect = (c.verifyClient !== false) ? CCE : CKE; - c.session.resuming = false; - - // create new security parameters - tls$1.createSecurityParameters(c, msg); - } - - // connection now open - c.open = true; - - // queue server hello - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createServerHello(c) - })); - - if(c.session.resuming) { - // queue change cipher spec message - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.change_cipher_spec, - data: tls$1.createChangeCipherSpec() - })); - - // create pending state - c.state.pending = tls$1.createConnectionState(c); - - // change current write state to pending write state - c.state.current.write = c.state.pending.write; - - // queue finished - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createFinished(c) - })); - } else { - // queue server certificate - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createCertificate(c) - })); - - if(!c.fail) { - // queue server key exchange - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createServerKeyExchange(c) - })); - - // request client certificate if set - if(c.verifyClient !== false) { - // queue certificate request - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createCertificateRequest(c) - })); - } - - // queue server hello done - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createServerHelloDone(c) - })); - } - } - - // send records - tls$1.flush(c); - - // continue - c.process(); -}; - -/** - * Called when a client receives a Certificate record. - * - * When this message will be sent: - * The server must send a certificate whenever the agreed-upon key exchange - * method is not an anonymous one. This message will always immediately - * follow the server hello message. - * - * Meaning of this message: - * The certificate type must be appropriate for the selected cipher suite's - * key exchange algorithm, and is generally an X.509v3 certificate. It must - * contain a key which matches the key exchange method, as follows. Unless - * otherwise specified, the signing algorithm for the certificate must be - * the same as the algorithm for the certificate key. Unless otherwise - * specified, the public key may be of any length. - * - * opaque ASN.1Cert<1..2^24-1>; - * struct { - * ASN.1Cert certificate_list<1..2^24-1>; - * } Certificate; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleCertificate = function(c, record, length) { - // minimum of 3 bytes in message - if(length < 3) { - return c.error(c, { - message: 'Invalid Certificate message. Message too short.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.illegal_parameter - } - }); - } - - var b = record.fragment; - var msg = { - certificate_list: readVector(b, 3) - }; - - /* The sender's certificate will be first in the list (chain), each - subsequent one that follows will certify the previous one, but root - certificates (self-signed) that specify the certificate authority may - be omitted under the assumption that clients must already possess it. */ - var cert, asn1; - var certs = []; - try { - while(msg.certificate_list.length() > 0) { - // each entry in msg.certificate_list is a vector with 3 len bytes - cert = readVector(msg.certificate_list, 3); - asn1 = forge$b.asn1.fromDer(cert); - cert = forge$b.pki.certificateFromAsn1(asn1, true); - certs.push(cert); - } - } catch(ex) { - return c.error(c, { - message: 'Could not parse certificate list.', - cause: ex, - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.bad_certificate - } - }); - } - - // ensure at least 1 certificate was provided if in client-mode - // or if verifyClient was set to true to require a certificate - // (as opposed to 'optional') - var client = (c.entity === tls$1.ConnectionEnd.client); - if((client || c.verifyClient === true) && certs.length === 0) { - // error, no certificate - c.error(c, { - message: client ? - 'No server certificate provided.' : - 'No client certificate provided.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.illegal_parameter - } - }); - } else if(certs.length === 0) { - // no certs to verify - // expect a ServerKeyExchange or ClientKeyExchange message next - c.expect = client ? SKE : CKE; - } else { - // save certificate in session - if(client) { - c.session.serverCertificate = certs[0]; - } else { - c.session.clientCertificate = certs[0]; - } - - if(tls$1.verifyCertificateChain(c, certs)) { - // expect a ServerKeyExchange or ClientKeyExchange message next - c.expect = client ? SKE : CKE; - } - } - - // continue - c.process(); -}; - -/** - * Called when a client receives a ServerKeyExchange record. - * - * When this message will be sent: - * This message will be sent immediately after the server certificate - * message (or the server hello message, if this is an anonymous - * negotiation). - * - * The server key exchange message is sent by the server only when the - * server certificate message (if sent) does not contain enough data to - * allow the client to exchange a premaster secret. - * - * Meaning of this message: - * This message conveys cryptographic information to allow the client to - * communicate the premaster secret: either an RSA public key to encrypt - * the premaster secret with, or a Diffie-Hellman public key with which the - * client can complete a key exchange (with the result being the premaster - * secret.) - * - * enum { - * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa - * } KeyExchangeAlgorithm; - * - * struct { - * opaque dh_p<1..2^16-1>; - * opaque dh_g<1..2^16-1>; - * opaque dh_Ys<1..2^16-1>; - * } ServerDHParams; - * - * struct { - * select(KeyExchangeAlgorithm) { - * case dh_anon: - * ServerDHParams params; - * case dhe_dss: - * case dhe_rsa: - * ServerDHParams params; - * digitally-signed struct { - * opaque client_random[32]; - * opaque server_random[32]; - * ServerDHParams params; - * } signed_params; - * case rsa: - * case dh_dss: - * case dh_rsa: - * struct {}; - * }; - * } ServerKeyExchange; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleServerKeyExchange = function(c, record, length) { - // this implementation only supports RSA, no Diffie-Hellman support - // so any length > 0 is invalid - if(length > 0) { - return c.error(c, { - message: 'Invalid key parameters. Only RSA is supported.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.unsupported_certificate - } - }); - } - - // expect an optional CertificateRequest message next - c.expect = SCR; - - // continue - c.process(); -}; - -/** - * Called when a client receives a ClientKeyExchange record. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleClientKeyExchange = function(c, record, length) { - // this implementation only supports RSA, no Diffie-Hellman support - // so any length < 48 is invalid - if(length < 48) { - return c.error(c, { - message: 'Invalid key parameters. Only RSA is supported.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.unsupported_certificate - } - }); - } - - var b = record.fragment; - var msg = { - enc_pre_master_secret: readVector(b, 2).getBytes() - }; - - // do rsa decryption - var privateKey = null; - if(c.getPrivateKey) { - try { - privateKey = c.getPrivateKey(c, c.session.serverCertificate); - privateKey = forge$b.pki.privateKeyFromPem(privateKey); - } catch(ex) { - c.error(c, { - message: 'Could not get private key.', - cause: ex, - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.internal_error - } - }); - } - } - - if(privateKey === null) { - return c.error(c, { - message: 'No private key set.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.internal_error - } - }); - } - - try { - // decrypt 48-byte pre-master secret - var sp = c.session.sp; - sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); - - // ensure client hello version matches first 2 bytes - var version = c.session.clientHelloVersion; - if(version.major !== sp.pre_master_secret.charCodeAt(0) || - version.minor !== sp.pre_master_secret.charCodeAt(1)) { - // error, do not send alert (see BLEI attack below) - throw new Error('TLS version rollback attack detected.'); - } - } catch(ex) { - /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a - TLS server which is using PKCS#1 encoded RSA, so instead of - failing here, we generate 48 random bytes and use that as - the pre-master secret. */ - sp.pre_master_secret = forge$b.random.getBytes(48); - } - - // expect a CertificateVerify message if a Certificate was received that - // does not have fixed Diffie-Hellman params, otherwise expect - // ChangeCipherSpec - c.expect = CCC; - if(c.session.clientCertificate !== null) { - // only RSA support, so expect CertificateVerify - // TODO: support Diffie-Hellman - c.expect = CCV; - } - - // continue - c.process(); -}; - -/** - * Called when a client receives a CertificateRequest record. - * - * When this message will be sent: - * A non-anonymous server can optionally request a certificate from the - * client, if appropriate for the selected cipher suite. This message, if - * sent, will immediately follow the Server Key Exchange message (if it is - * sent; otherwise, the Server Certificate message). - * - * enum { - * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4), - * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6), - * fortezza_dms_RESERVED(20), (255) - * } ClientCertificateType; - * - * opaque DistinguishedName<1..2^16-1>; - * - * struct { - * ClientCertificateType certificate_types<1..2^8-1>; - * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>; - * DistinguishedName certificate_authorities<0..2^16-1>; - * } CertificateRequest; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleCertificateRequest = function(c, record, length) { - // minimum of 3 bytes in message - if(length < 3) { - return c.error(c, { - message: 'Invalid CertificateRequest. Message too short.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.illegal_parameter - } - }); - } - - // TODO: TLS 1.2+ has different format including - // SignatureAndHashAlgorithm after cert types - var b = record.fragment; - var msg = { - certificate_types: readVector(b, 1), - certificate_authorities: readVector(b, 2) - }; - - // save certificate request in session - c.session.certificateRequest = msg; - - // expect a ServerHelloDone message next - c.expect = SHD; - - // continue - c.process(); -}; - -/** - * Called when a server receives a CertificateVerify record. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleCertificateVerify = function(c, record, length) { - if(length < 2) { - return c.error(c, { - message: 'Invalid CertificateVerify. Message too short.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.illegal_parameter - } - }); - } - - // rewind to get full bytes for message so it can be manually - // digested below (special case for CertificateVerify messages because - // they must be digested *after* handling as opposed to all others) - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - - var msg = { - signature: readVector(b, 2).getBytes() - }; - - // TODO: add support for DSA - - // generate data to verify - var verify = forge$b.util.createBuffer(); - verify.putBuffer(c.session.md5.digest()); - verify.putBuffer(c.session.sha1.digest()); - verify = verify.getBytes(); - - try { - var cert = c.session.clientCertificate; - /*b = forge.pki.rsa.decrypt( - msg.signature, cert.publicKey, true, verify.length); - if(b !== verify) {*/ - if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) { - throw new Error('CertificateVerify signature does not match.'); - } - - // digest message now that it has been handled - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - } catch(ex) { - return c.error(c, { - message: 'Bad signature in CertificateVerify.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.handshake_failure - } - }); - } - - // expect ChangeCipherSpec - c.expect = CCC; - - // continue - c.process(); -}; - -/** - * Called when a client receives a ServerHelloDone record. - * - * When this message will be sent: - * The server hello done message is sent by the server to indicate the end - * of the server hello and associated messages. After sending this message - * the server will wait for a client response. - * - * Meaning of this message: - * This message means that the server is done sending messages to support - * the key exchange, and the client can proceed with its phase of the key - * exchange. - * - * Upon receipt of the server hello done message the client should verify - * that the server provided a valid certificate if required and check that - * the server hello parameters are acceptable. - * - * struct {} ServerHelloDone; - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleServerHelloDone = function(c, record, length) { - // len must be 0 bytes - if(length > 0) { - return c.error(c, { - message: 'Invalid ServerHelloDone message. Invalid length.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.record_overflow - } - }); - } - - if(c.serverCertificate === null) { - // no server certificate was provided - var error = { - message: 'No server certificate provided. Not enough security.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.insufficient_security - } - }; - - // call application callback - var depth = 0; - var ret = c.verify(c, error.alert.description, depth, []); - if(ret !== true) { - // check for custom alert info - if(ret || ret === 0) { - // set custom message and alert description - if(typeof ret === 'object' && !forge$b.util.isArray(ret)) { - if(ret.message) { - error.message = ret.message; - } - if(ret.alert) { - error.alert.description = ret.alert; - } - } else if(typeof ret === 'number') { - // set custom alert description - error.alert.description = ret; - } - } - - // send error - return c.error(c, error); - } - } - - // create client certificate message if requested - if(c.session.certificateRequest !== null) { - record = tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createCertificate(c) - }); - tls$1.queue(c, record); - } - - // create client key exchange message - record = tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createClientKeyExchange(c) - }); - tls$1.queue(c, record); - - // expect no messages until the following callback has been called - c.expect = SER; - - // create callback to handle client signature (for client-certs) - var callback = function(c, signature) { - if(c.session.certificateRequest !== null && - c.session.clientCertificate !== null) { - // create certificate verify message - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createCertificateVerify(c, signature) - })); - } - - // create change cipher spec message - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.change_cipher_spec, - data: tls$1.createChangeCipherSpec() - })); - - // create pending state - c.state.pending = tls$1.createConnectionState(c); - - // change current write state to pending write state - c.state.current.write = c.state.pending.write; - - // create finished message - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createFinished(c) - })); - - // expect a server ChangeCipherSpec message next - c.expect = SCC; - - // send records - tls$1.flush(c); - - // continue - c.process(); - }; - - // if there is no certificate request or no client certificate, do - // callback immediately - if(c.session.certificateRequest === null || - c.session.clientCertificate === null) { - return callback(c, null); - } - - // otherwise get the client signature - tls$1.getClientSignature(c, callback); -}; - -/** - * Called when a ChangeCipherSpec record is received. - * - * @param c the connection. - * @param record the record. - */ -tls$1.handleChangeCipherSpec = function(c, record) { - if(record.fragment.getByte() !== 0x01) { - return c.error(c, { - message: 'Invalid ChangeCipherSpec message received.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.illegal_parameter - } - }); - } - - // create pending state if: - // 1. Resuming session in client mode OR - // 2. NOT resuming session in server mode - var client = (c.entity === tls$1.ConnectionEnd.client); - if((c.session.resuming && client) || (!c.session.resuming && !client)) { - c.state.pending = tls$1.createConnectionState(c); - } - - // change current read state to pending read state - c.state.current.read = c.state.pending.read; - - // clear pending state if: - // 1. NOT resuming session in client mode OR - // 2. resuming a session in server mode - if((!c.session.resuming && client) || (c.session.resuming && !client)) { - c.state.pending = null; - } - - // expect a Finished record next - c.expect = client ? SFI : CFI; - - // continue - c.process(); -}; - -/** - * Called when a Finished record is received. - * - * When this message will be sent: - * A finished message is always sent immediately after a change - * cipher spec message to verify that the key exchange and - * authentication processes were successful. It is essential that a - * change cipher spec message be received between the other - * handshake messages and the Finished message. - * - * Meaning of this message: - * The finished message is the first protected with the just- - * negotiated algorithms, keys, and secrets. Recipients of finished - * messages must verify that the contents are correct. Once a side - * has sent its Finished message and received and validated the - * Finished message from its peer, it may begin to send and receive - * application data over the connection. - * - * struct { - * opaque verify_data[verify_data_length]; - * } Finished; - * - * verify_data - * PRF(master_secret, finished_label, Hash(handshake_messages)) - * [0..verify_data_length-1]; - * - * finished_label - * For Finished messages sent by the client, the string - * "client finished". For Finished messages sent by the server, the - * string "server finished". - * - * verify_data_length depends on the cipher suite. If it is not specified - * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used - * 12 bytes. - * - * @param c the connection. - * @param record the record. - * @param length the length of the handshake message. - */ -tls$1.handleFinished = function(c, record, length) { - // rewind to get full bytes for message so it can be manually - // digested below (special case for Finished messages because they - // must be digested *after* handling as opposed to all others) - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - - // message contains only verify_data - var vd = record.fragment.getBytes(); - - // ensure verify data is correct - b = forge$b.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - - // set label based on entity type - var client = (c.entity === tls$1.ConnectionEnd.client); - var label = client ? 'server finished' : 'client finished'; - - // TODO: determine prf function and verify length for TLS 1.2 - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - if(b.getBytes() !== vd) { - return c.error(c, { - message: 'Invalid verify_data in Finished message.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.decrypt_error - } - }); - } - - // digest finished message now that it has been handled - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - - // resuming session as client or NOT resuming session as server - if((c.session.resuming && client) || (!c.session.resuming && !client)) { - // create change cipher spec message - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.change_cipher_spec, - data: tls$1.createChangeCipherSpec() - })); - - // change current write state to pending write state, clear pending - c.state.current.write = c.state.pending.write; - c.state.pending = null; - - // create finished message - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createFinished(c) - })); - } - - // expect application data next - c.expect = client ? SAD : CAD; - - // handshake complete - c.handshaking = false; - ++c.handshakes; - - // save access to peer certificate - c.peerCertificate = client ? - c.session.serverCertificate : c.session.clientCertificate; - - // send records - tls$1.flush(c); - - // now connected - c.isConnected = true; - c.connected(c); - - // continue - c.process(); -}; - -/** - * Called when an Alert record is received. - * - * @param c the connection. - * @param record the record. - */ -tls$1.handleAlert = function(c, record) { - // read alert - var b = record.fragment; - var alert = { - level: b.getByte(), - description: b.getByte() - }; - - // TODO: consider using a table? - // get appropriate message - var msg; - switch(alert.description) { - case tls$1.Alert.Description.close_notify: - msg = 'Connection closed.'; - break; - case tls$1.Alert.Description.unexpected_message: - msg = 'Unexpected message.'; - break; - case tls$1.Alert.Description.bad_record_mac: - msg = 'Bad record MAC.'; - break; - case tls$1.Alert.Description.decryption_failed: - msg = 'Decryption failed.'; - break; - case tls$1.Alert.Description.record_overflow: - msg = 'Record overflow.'; - break; - case tls$1.Alert.Description.decompression_failure: - msg = 'Decompression failed.'; - break; - case tls$1.Alert.Description.handshake_failure: - msg = 'Handshake failure.'; - break; - case tls$1.Alert.Description.bad_certificate: - msg = 'Bad certificate.'; - break; - case tls$1.Alert.Description.unsupported_certificate: - msg = 'Unsupported certificate.'; - break; - case tls$1.Alert.Description.certificate_revoked: - msg = 'Certificate revoked.'; - break; - case tls$1.Alert.Description.certificate_expired: - msg = 'Certificate expired.'; - break; - case tls$1.Alert.Description.certificate_unknown: - msg = 'Certificate unknown.'; - break; - case tls$1.Alert.Description.illegal_parameter: - msg = 'Illegal parameter.'; - break; - case tls$1.Alert.Description.unknown_ca: - msg = 'Unknown certificate authority.'; - break; - case tls$1.Alert.Description.access_denied: - msg = 'Access denied.'; - break; - case tls$1.Alert.Description.decode_error: - msg = 'Decode error.'; - break; - case tls$1.Alert.Description.decrypt_error: - msg = 'Decrypt error.'; - break; - case tls$1.Alert.Description.export_restriction: - msg = 'Export restriction.'; - break; - case tls$1.Alert.Description.protocol_version: - msg = 'Unsupported protocol version.'; - break; - case tls$1.Alert.Description.insufficient_security: - msg = 'Insufficient security.'; - break; - case tls$1.Alert.Description.internal_error: - msg = 'Internal error.'; - break; - case tls$1.Alert.Description.user_canceled: - msg = 'User canceled.'; - break; - case tls$1.Alert.Description.no_renegotiation: - msg = 'Renegotiation not supported.'; - break; - default: - msg = 'Unknown error.'; - break; - } - - // close connection on close_notify, not an error - if(alert.description === tls$1.Alert.Description.close_notify) { - return c.close(); - } - - // call error handler - c.error(c, { - message: msg, - send: false, - // origin is the opposite end - origin: (c.entity === tls$1.ConnectionEnd.client) ? 'server' : 'client', - alert: alert - }); - - // continue - c.process(); -}; - -/** - * Called when a Handshake record is received. - * - * @param c the connection. - * @param record the record. - */ -tls$1.handleHandshake = function(c, record) { - // get the handshake type and message length - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt24(); - - // see if the record fragment doesn't yet contain the full message - if(length > b.length()) { - // cache the record, clear its fragment, and reset the buffer read - // pointer before the type and length were read - c.fragmented = record; - record.fragment = forge$b.util.createBuffer(); - b.read -= 4; - - // continue - return c.process(); - } - - // full message now available, clear cache, reset read pointer to - // before type and length - c.fragmented = null; - b.read -= 4; - - // save the handshake bytes for digestion after handler is found - // (include type and length of handshake msg) - var bytes = b.bytes(length + 4); - - // restore read pointer - b.read += 4; - - // handle expected message - if(type in hsTable[c.entity][c.expect]) { - // initialize server session - if(c.entity === tls$1.ConnectionEnd.server && !c.open && !c.fail) { - c.handshaking = true; - c.session = { - version: null, - extensions: { - server_name: { - serverNameList: [] - } - }, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - clientCertificate: null, - md5: forge$b.md.md5.create(), - sha1: forge$b.md.sha1.create() - }; - } - - /* Update handshake messages digest. Finished and CertificateVerify - messages are not digested here. They can't be digested as part of - the verify_data that they contain. These messages are manually - digested in their handlers. HelloRequest messages are simply never - included in the handshake message digest according to spec. */ - if(type !== tls$1.HandshakeType.hello_request && - type !== tls$1.HandshakeType.certificate_verify && - type !== tls$1.HandshakeType.finished) { - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - } - - // handle specific handshake type record - hsTable[c.entity][c.expect][type](c, record, length); - } else { - // unexpected record - tls$1.handleUnexpected(c, record); - } -}; - -/** - * Called when an ApplicationData record is received. - * - * @param c the connection. - * @param record the record. - */ -tls$1.handleApplicationData = function(c, record) { - // buffer data, notify that its ready - c.data.putBuffer(record.fragment); - c.dataReady(c); - - // continue - c.process(); -}; - -/** - * Called when a Heartbeat record is received. - * - * @param c the connection. - * @param record the record. - */ -tls$1.handleHeartbeat = function(c, record) { - // get the heartbeat type and payload - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt16(); - var payload = b.getBytes(length); - - if(type === tls$1.HeartbeatMessageType.heartbeat_request) { - // discard request during handshake or if length is too large - if(c.handshaking || length > payload.length) { - // continue - return c.process(); - } - // retransmit payload - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.heartbeat, - data: tls$1.createHeartbeat( - tls$1.HeartbeatMessageType.heartbeat_response, payload) - })); - tls$1.flush(c); - } else if(type === tls$1.HeartbeatMessageType.heartbeat_response) { - // check payload against expected payload, discard heartbeat if no match - if(payload !== c.expectedHeartbeatPayload) { - // continue - return c.process(); - } - - // notify that a valid heartbeat was received - if(c.heartbeatReceived) { - c.heartbeatReceived(c, forge$b.util.createBuffer(payload)); - } - } - - // continue - c.process(); -}; - -/** - * The transistional state tables for receiving TLS records. It maps the - * current TLS engine state and a received record to a function to handle the - * record and update the state. - * - * For instance, if the current state is SHE, then the TLS engine is expecting - * a ServerHello record. Once a record is received, the handler function is - * looked up using the state SHE and the record's content type. - * - * The resulting function will either be an error handler or a record handler. - * The function will take whatever action is appropriate and update the state - * for the next record. - * - * The states are all based on possible server record types. Note that the - * client will never specifically expect to receive a HelloRequest or an alert - * from the server so there is no state that reflects this. These messages may - * occur at any time. - * - * There are two tables for mapping states because there is a second tier of - * types for handshake messages. Once a record with a content type of handshake - * is received, the handshake record handler will look up the handshake type in - * the secondary map to get its appropriate handler. - * - * Valid message orders are as follows: - * - * =======================FULL HANDSHAKE====================== - * Client Server - * - * ClientHello --------> - * ServerHello - * Certificate* - * ServerKeyExchange* - * CertificateRequest* - * <-------- ServerHelloDone - * Certificate* - * ClientKeyExchange - * CertificateVerify* - * [ChangeCipherSpec] - * Finished --------> - * [ChangeCipherSpec] - * <-------- Finished - * Application Data <-------> Application Data - * - * =====================SESSION RESUMPTION===================== - * Client Server - * - * ClientHello --------> - * ServerHello - * [ChangeCipherSpec] - * <-------- Finished - * [ChangeCipherSpec] - * Finished --------> - * Application Data <-------> Application Data - */ -// client expect states (indicate which records are expected to be received) -var SHE = 0; // rcv server hello -var SCE = 1; // rcv server certificate -var SKE = 2; // rcv server key exchange -var SCR = 3; // rcv certificate request -var SHD = 4; // rcv server hello done -var SCC = 5; // rcv change cipher spec -var SFI = 6; // rcv finished -var SAD = 7; // rcv application data -var SER = 8; // not expecting any messages at this point - -// server expect states -var CHE = 0; // rcv client hello -var CCE = 1; // rcv client certificate -var CKE = 2; // rcv client key exchange -var CCV = 3; // rcv certificate verify -var CCC = 4; // rcv change cipher spec -var CFI = 5; // rcv finished -var CAD = 6; // rcv application data - -// map client current expect state and content type to function -var __ = tls$1.handleUnexpected; -var R0 = tls$1.handleChangeCipherSpec; -var R1 = tls$1.handleAlert; -var R2 = tls$1.handleHandshake; -var R3 = tls$1.handleApplicationData; -var R4 = tls$1.handleHeartbeat; -var ctTable = []; -ctTable[tls$1.ConnectionEnd.client] = [ -// CC,AL,HS,AD,HB -/*SHE*/[__,R1,R2,__,R4], -/*SCE*/[__,R1,R2,__,R4], -/*SKE*/[__,R1,R2,__,R4], -/*SCR*/[__,R1,R2,__,R4], -/*SHD*/[__,R1,R2,__,R4], -/*SCC*/[R0,R1,__,__,R4], -/*SFI*/[__,R1,R2,__,R4], -/*SAD*/[__,R1,R2,R3,R4], -/*SER*/[__,R1,R2,__,R4] -]; - -// map server current expect state and content type to function -ctTable[tls$1.ConnectionEnd.server] = [ -// CC,AL,HS,AD -/*CHE*/[__,R1,R2,__,R4], -/*CCE*/[__,R1,R2,__,R4], -/*CKE*/[__,R1,R2,__,R4], -/*CCV*/[__,R1,R2,__,R4], -/*CCC*/[R0,R1,__,__,R4], -/*CFI*/[__,R1,R2,__,R4], -/*CAD*/[__,R1,R2,R3,R4], -/*CER*/[__,R1,R2,__,R4] -]; - -// map client current expect state and handshake type to function -var H0 = tls$1.handleHelloRequest; -var H1 = tls$1.handleServerHello; -var H2 = tls$1.handleCertificate; -var H3 = tls$1.handleServerKeyExchange; -var H4 = tls$1.handleCertificateRequest; -var H5 = tls$1.handleServerHelloDone; -var H6 = tls$1.handleFinished; -var hsTable = []; -hsTable[tls$1.ConnectionEnd.client] = [ -// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI -/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__], -/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__], -/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__], -/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__], -/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], -/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] -]; - -// map server current expect state and handshake type to function -// Note: CAD[CH] does not map to FB because renegotation is prohibited -var H7 = tls$1.handleClientHello; -var H8 = tls$1.handleClientKeyExchange; -var H9 = tls$1.handleCertificateVerify; -hsTable[tls$1.ConnectionEnd.server] = [ -// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI -/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__], -/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__], -/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__], -/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], -/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], -/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] -]; - -/** - * Generates the master_secret and keys using the given security parameters. - * - * The security parameters for a TLS connection state are defined as such: - * - * struct { - * ConnectionEnd entity; - * PRFAlgorithm prf_algorithm; - * BulkCipherAlgorithm bulk_cipher_algorithm; - * CipherType cipher_type; - * uint8 enc_key_length; - * uint8 block_length; - * uint8 fixed_iv_length; - * uint8 record_iv_length; - * MACAlgorithm mac_algorithm; - * uint8 mac_length; - * uint8 mac_key_length; - * CompressionMethod compression_algorithm; - * opaque master_secret[48]; - * opaque client_random[32]; - * opaque server_random[32]; - * } SecurityParameters; - * - * Note that this definition is from TLS 1.2. In TLS 1.0 some of these - * parameters are ignored because, for instance, the PRFAlgorithm is a - * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0. - * - * The Record Protocol requires an algorithm to generate keys required by the - * current connection state. - * - * The master secret is expanded into a sequence of secure bytes, which is then - * split to a client write MAC key, a server write MAC key, a client write - * encryption key, and a server write encryption key. In TLS 1.0 a client write - * IV and server write IV are also generated. Each of these is generated from - * the byte sequence in that order. Unused values are empty. In TLS 1.2, some - * AEAD ciphers may additionally require a client write IV and a server write - * IV (see Section 6.2.3.3). - * - * When keys, MAC keys, and IVs are generated, the master secret is used as an - * entropy source. - * - * To generate the key material, compute: - * - * master_secret = PRF(pre_master_secret, "master secret", - * ClientHello.random + ServerHello.random) - * - * key_block = PRF(SecurityParameters.master_secret, - * "key expansion", - * SecurityParameters.server_random + - * SecurityParameters.client_random); - * - * until enough output has been generated. Then, the key_block is - * partitioned as follows: - * - * client_write_MAC_key[SecurityParameters.mac_key_length] - * server_write_MAC_key[SecurityParameters.mac_key_length] - * client_write_key[SecurityParameters.enc_key_length] - * server_write_key[SecurityParameters.enc_key_length] - * client_write_IV[SecurityParameters.fixed_iv_length] - * server_write_IV[SecurityParameters.fixed_iv_length] - * - * In TLS 1.2, the client_write_IV and server_write_IV are only generated for - * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This - * implementation uses TLS 1.0 so IVs are generated. - * - * Implementation note: The currently defined cipher suite which requires the - * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32 - * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also - * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material. - * - * @param c the connection. - * @param sp the security parameters to use. - * - * @return the security keys. - */ -tls$1.generateKeys = function(c, sp) { - // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) & - // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented - // at present - - // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with - // TLS 1.0 but we don't care right now because AES is better and we have - // an implementation for it - - // TODO: TLS 1.2 implementation - /* - // determine the PRF - var prf; - switch(sp.prf_algorithm) { - case tls.PRFAlgorithm.tls_prf_sha256: - prf = prf_sha256; - break; - default: - // should never happen - throw new Error('Invalid PRF'); - } - */ - - // TLS 1.0/1.1 implementation - var prf = prf_TLS1; - - // concatenate server and client random - var random = sp.client_random + sp.server_random; - - // only create master secret if session is new - if(!c.session.resuming) { - // create master secret, clean up pre-master secret - sp.master_secret = prf( - sp.pre_master_secret, 'master secret', random, 48).bytes(); - sp.pre_master_secret = null; - } - - // generate the amount of key material needed - random = sp.server_random + sp.client_random; - var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; - - // include IV for TLS/1.0 - var tls10 = (c.version.major === tls$1.Versions.TLS_1_0.major && - c.version.minor === tls$1.Versions.TLS_1_0.minor); - if(tls10) { - length += 2 * sp.fixed_iv_length; - } - var km = prf(sp.master_secret, 'key expansion', random, length); - - // split the key material into the MAC and encryption keys - var rval = { - client_write_MAC_key: km.getBytes(sp.mac_key_length), - server_write_MAC_key: km.getBytes(sp.mac_key_length), - client_write_key: km.getBytes(sp.enc_key_length), - server_write_key: km.getBytes(sp.enc_key_length) - }; - - // include TLS 1.0 IVs - if(tls10) { - rval.client_write_IV = km.getBytes(sp.fixed_iv_length); - rval.server_write_IV = km.getBytes(sp.fixed_iv_length); - } - - return rval; -}; - -/** - * Creates a new initialized TLS connection state. A connection state has - * a read mode and a write mode. - * - * compression state: - * The current state of the compression algorithm. - * - * cipher state: - * The current state of the encryption algorithm. This will consist of the - * scheduled key for that connection. For stream ciphers, this will also - * contain whatever state information is necessary to allow the stream to - * continue to encrypt or decrypt data. - * - * MAC key: - * The MAC key for the connection. - * - * sequence number: - * Each connection state contains a sequence number, which is maintained - * separately for read and write states. The sequence number MUST be set to - * zero whenever a connection state is made the active state. Sequence - * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do - * not wrap. If a TLS implementation would need to wrap a sequence number, - * it must renegotiate instead. A sequence number is incremented after each - * record: specifically, the first record transmitted under a particular - * connection state MUST use sequence number 0. - * - * @param c the connection. - * - * @return the new initialized TLS connection state. - */ -tls$1.createConnectionState = function(c) { - var client = (c.entity === tls$1.ConnectionEnd.client); - - var createMode = function() { - var mode = { - // two 32-bit numbers, first is most significant - sequenceNumber: [0, 0], - macKey: null, - macLength: 0, - macFunction: null, - cipherState: null, - cipherFunction: function(record) {return true;}, - compressionState: null, - compressFunction: function(record) {return true;}, - updateSequenceNumber: function() { - if(mode.sequenceNumber[1] === 0xFFFFFFFF) { - mode.sequenceNumber[1] = 0; - ++mode.sequenceNumber[0]; - } else { - ++mode.sequenceNumber[1]; - } - } - }; - return mode; - }; - var state = { - read: createMode(), - write: createMode() - }; - - // update function in read mode will decrypt then decompress a record - state.read.update = function(c, record) { - if(!state.read.cipherFunction(record, state.read)) { - c.error(c, { - message: 'Could not decrypt record or bad MAC.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - // doesn't matter if decryption failed or MAC was - // invalid, return the same error so as not to reveal - // which one occurred - description: tls$1.Alert.Description.bad_record_mac - } - }); - } else if(!state.read.compressFunction(c, record, state.read)) { - c.error(c, { - message: 'Could not decompress record.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.decompression_failure - } - }); - } - return !c.fail; - }; - - // update function in write mode will compress then encrypt a record - state.write.update = function(c, record) { - if(!state.write.compressFunction(c, record, state.write)) { - // error, but do not send alert since it would require - // compression as well - c.error(c, { - message: 'Could not compress record.', - send: false, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.internal_error - } - }); - } else if(!state.write.cipherFunction(record, state.write)) { - // error, but do not send alert since it would require - // encryption as well - c.error(c, { - message: 'Could not encrypt record.', - send: false, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.internal_error - } - }); - } - return !c.fail; - }; - - // handle security parameters - if(c.session) { - var sp = c.session.sp; - c.session.cipherSuite.initSecurityParameters(sp); - - // generate keys - sp.keys = tls$1.generateKeys(c, sp); - state.read.macKey = client ? - sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; - state.write.macKey = client ? - sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; - - // cipher suite setup - c.session.cipherSuite.initConnectionState(state, c, sp); - - // compression setup - switch(sp.compression_algorithm) { - case tls$1.CompressionMethod.none: - break; - case tls$1.CompressionMethod.deflate: - state.read.compressFunction = inflate; - state.write.compressFunction = deflate; - break; - default: - throw new Error('Unsupported compression algorithm.'); - } - } - - return state; -}; - -/** - * Creates a Random structure. - * - * struct { - * uint32 gmt_unix_time; - * opaque random_bytes[28]; - * } Random; - * - * gmt_unix_time: - * The current time and date in standard UNIX 32-bit format (seconds since - * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according - * to the sender's internal clock. Clocks are not required to be set - * correctly by the basic TLS protocol; higher-level or application - * protocols may define additional requirements. Note that, for historical - * reasons, the data element is named using GMT, the predecessor of the - * current worldwide time base, UTC. - * random_bytes: - * 28 bytes generated by a secure random number generator. - * - * @return the Random structure as a byte array. - */ -tls$1.createRandom = function() { - // get UTC milliseconds - var d = new Date(); - var utc = +d + d.getTimezoneOffset() * 60000; - var rval = forge$b.util.createBuffer(); - rval.putInt32(utc); - rval.putBytes(forge$b.random.getBytes(28)); - return rval; -}; - -/** - * Creates a TLS record with the given type and data. - * - * @param c the connection. - * @param options: - * type: the record type. - * data: the plain text data in a byte buffer. - * - * @return the created record. - */ -tls$1.createRecord = function(c, options) { - if(!options.data) { - return null; - } - var record = { - type: options.type, - version: { - major: c.version.major, - minor: c.version.minor - }, - length: options.data.length(), - fragment: options.data - }; - return record; -}; - -/** - * Creates a TLS alert record. - * - * @param c the connection. - * @param alert: - * level: the TLS alert level. - * description: the TLS alert description. - * - * @return the created alert record. - */ -tls$1.createAlert = function(c, alert) { - var b = forge$b.util.createBuffer(); - b.putByte(alert.level); - b.putByte(alert.description); - return tls$1.createRecord(c, { - type: tls$1.ContentType.alert, - data: b - }); -}; - -/* The structure of a TLS handshake message. - * - * struct { - * HandshakeType msg_type; // handshake type - * uint24 length; // bytes in message - * select(HandshakeType) { - * case hello_request: HelloRequest; - * case client_hello: ClientHello; - * case server_hello: ServerHello; - * case certificate: Certificate; - * case server_key_exchange: ServerKeyExchange; - * case certificate_request: CertificateRequest; - * case server_hello_done: ServerHelloDone; - * case certificate_verify: CertificateVerify; - * case client_key_exchange: ClientKeyExchange; - * case finished: Finished; - * } body; - * } Handshake; - */ - -/** - * Creates a ClientHello message. - * - * opaque SessionID<0..32>; - * enum { null(0), deflate(1), (255) } CompressionMethod; - * uint8 CipherSuite[2]; - * - * struct { - * ProtocolVersion client_version; - * Random random; - * SessionID session_id; - * CipherSuite cipher_suites<2..2^16-2>; - * CompressionMethod compression_methods<1..2^8-1>; - * select(extensions_present) { - * case false: - * struct {}; - * case true: - * Extension extensions<0..2^16-1>; - * }; - * } ClientHello; - * - * The extension format for extended client hellos and server hellos is: - * - * struct { - * ExtensionType extension_type; - * opaque extension_data<0..2^16-1>; - * } Extension; - * - * Here: - * - * - "extension_type" identifies the particular extension type. - * - "extension_data" contains information specific to the particular - * extension type. - * - * The extension types defined in this document are: - * - * enum { - * server_name(0), max_fragment_length(1), - * client_certificate_url(2), trusted_ca_keys(3), - * truncated_hmac(4), status_request(5), (65535) - * } ExtensionType; - * - * @param c the connection. - * - * @return the ClientHello byte buffer. - */ -tls$1.createClientHello = function(c) { - // save hello version - c.session.clientHelloVersion = { - major: c.version.major, - minor: c.version.minor - }; - - // create supported cipher suites - var cipherSuites = forge$b.util.createBuffer(); - for(var i = 0; i < c.cipherSuites.length; ++i) { - var cs = c.cipherSuites[i]; - cipherSuites.putByte(cs.id[0]); - cipherSuites.putByte(cs.id[1]); - } - var cSuites = cipherSuites.length(); - - // create supported compression methods, null always supported, but - // also support deflate if connection has inflate and deflate methods - var compressionMethods = forge$b.util.createBuffer(); - compressionMethods.putByte(tls$1.CompressionMethod.none); - // FIXME: deflate support disabled until issues with raw deflate data - // without zlib headers are resolved - /* - if(c.inflate !== null && c.deflate !== null) { - compressionMethods.putByte(tls.CompressionMethod.deflate); - } - */ - var cMethods = compressionMethods.length(); - - // create TLS SNI (server name indication) extension if virtual host - // has been specified, see RFC 3546 - var extensions = forge$b.util.createBuffer(); - if(c.virtualHost) { - // create extension struct - var ext = forge$b.util.createBuffer(); - ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes) - ext.putByte(0x00); - - /* In order to provide the server name, clients MAY include an - * extension of type "server_name" in the (extended) client hello. - * The "extension_data" field of this extension SHALL contain - * "ServerNameList" where: - * - * struct { - * NameType name_type; - * select(name_type) { - * case host_name: HostName; - * } name; - * } ServerName; - * - * enum { - * host_name(0), (255) - * } NameType; - * - * opaque HostName<1..2^16-1>; - * - * struct { - * ServerName server_name_list<1..2^16-1> - * } ServerNameList; - */ - var serverName = forge$b.util.createBuffer(); - serverName.putByte(0x00); // type host_name - writeVector(serverName, 2, forge$b.util.createBuffer(c.virtualHost)); - - // ServerNameList is in extension_data - var snList = forge$b.util.createBuffer(); - writeVector(snList, 2, serverName); - writeVector(ext, 2, snList); - extensions.putBuffer(ext); - } - var extLength = extensions.length(); - if(extLength > 0) { - // add extension vector length - extLength += 2; - } - - // determine length of the handshake message - // cipher suites and compression methods size will need to be - // updated if more get added to the list - var sessionId = c.session.id; - var length = - sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + cSuites + // cipher suites vector - 1 + cMethods + // compression methods vector - extLength; // extensions vector - - // build record fragment - var rval = forge$b.util.createBuffer(); - rval.putByte(tls$1.HandshakeType.client_hello); - rval.putInt24(length); // handshake length - rval.putByte(c.version.major); // major version - rval.putByte(c.version.minor); // minor version - rval.putBytes(c.session.sp.client_random); // random time + bytes - writeVector(rval, 1, forge$b.util.createBuffer(sessionId)); - writeVector(rval, 2, cipherSuites); - writeVector(rval, 1, compressionMethods); - if(extLength > 0) { - writeVector(rval, 2, extensions); - } - return rval; -}; - -/** - * Creates a ServerHello message. - * - * @param c the connection. - * - * @return the ServerHello byte buffer. - */ -tls$1.createServerHello = function(c) { - // determine length of the handshake message - var sessionId = c.session.id; - var length = - sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + // chosen cipher suite - 1; // chosen compression method - - // build record fragment - var rval = forge$b.util.createBuffer(); - rval.putByte(tls$1.HandshakeType.server_hello); - rval.putInt24(length); // handshake length - rval.putByte(c.version.major); // major version - rval.putByte(c.version.minor); // minor version - rval.putBytes(c.session.sp.server_random); // random time + bytes - writeVector(rval, 1, forge$b.util.createBuffer(sessionId)); - rval.putByte(c.session.cipherSuite.id[0]); - rval.putByte(c.session.cipherSuite.id[1]); - rval.putByte(c.session.compressionMethod); - return rval; -}; - -/** - * Creates a Certificate message. - * - * When this message will be sent: - * This is the first message the client can send after receiving a server - * hello done message and the first message the server can send after - * sending a ServerHello. This client message is only sent if the server - * requests a certificate. If no suitable certificate is available, the - * client should send a certificate message containing no certificates. If - * client authentication is required by the server for the handshake to - * continue, it may respond with a fatal handshake failure alert. - * - * opaque ASN.1Cert<1..2^24-1>; - * - * struct { - * ASN.1Cert certificate_list<0..2^24-1>; - * } Certificate; - * - * @param c the connection. - * - * @return the Certificate byte buffer. - */ -tls$1.createCertificate = function(c) { - // TODO: check certificate request to ensure types are supported - - // get a certificate (a certificate as a PEM string) - var client = (c.entity === tls$1.ConnectionEnd.client); - var cert = null; - if(c.getCertificate) { - var hint; - if(client) { - hint = c.session.certificateRequest; - } else { - hint = c.session.extensions.server_name.serverNameList; - } - cert = c.getCertificate(c, hint); - } - - // buffer to hold certificate list - var certList = forge$b.util.createBuffer(); - if(cert !== null) { - try { - // normalize cert to a chain of certificates - if(!forge$b.util.isArray(cert)) { - cert = [cert]; - } - var asn1 = null; - for(var i = 0; i < cert.length; ++i) { - var msg = forge$b.pem.decode(cert[i])[0]; - if(msg.type !== 'CERTIFICATE' && - msg.type !== 'X509 CERTIFICATE' && - msg.type !== 'TRUSTED CERTIFICATE') { - var error = new Error('Could not convert certificate from PEM; PEM ' + - 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' + - '"TRUSTED CERTIFICATE".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert certificate from PEM; PEM is encrypted.'); - } - - var der = forge$b.util.createBuffer(msg.body); - if(asn1 === null) { - asn1 = forge$b.asn1.fromDer(der.bytes(), false); - } - - // certificate entry is itself a vector with 3 length bytes - var certBuffer = forge$b.util.createBuffer(); - writeVector(certBuffer, 3, der); - - // add cert vector to cert list vector - certList.putBuffer(certBuffer); - } - - // save certificate - cert = forge$b.pki.certificateFromAsn1(asn1); - if(client) { - c.session.clientCertificate = cert; - } else { - c.session.serverCertificate = cert; - } - } catch(ex) { - return c.error(c, { - message: 'Could not send certificate list.', - cause: ex, - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.bad_certificate - } - }); - } - } - - // determine length of the handshake message - var length = 3 + certList.length(); // cert list vector - - // build record fragment - var rval = forge$b.util.createBuffer(); - rval.putByte(tls$1.HandshakeType.certificate); - rval.putInt24(length); - writeVector(rval, 3, certList); - return rval; -}; - -/** - * Creates a ClientKeyExchange message. - * - * When this message will be sent: - * This message is always sent by the client. It will immediately follow the - * client certificate message, if it is sent. Otherwise it will be the first - * message sent by the client after it receives the server hello done - * message. - * - * Meaning of this message: - * With this message, the premaster secret is set, either though direct - * transmission of the RSA-encrypted secret, or by the transmission of - * Diffie-Hellman parameters which will allow each side to agree upon the - * same premaster secret. When the key exchange method is DH_RSA or DH_DSS, - * client certification has been requested, and the client was able to - * respond with a certificate which contained a Diffie-Hellman public key - * whose parameters (group and generator) matched those specified by the - * server in its certificate, this message will not contain any data. - * - * Meaning of this message: - * If RSA is being used for key agreement and authentication, the client - * generates a 48-byte premaster secret, encrypts it using the public key - * from the server's certificate or the temporary RSA key provided in a - * server key exchange message, and sends the result in an encrypted - * premaster secret message. This structure is a variant of the client - * key exchange message, not a message in itself. - * - * struct { - * select(KeyExchangeAlgorithm) { - * case rsa: EncryptedPreMasterSecret; - * case diffie_hellman: ClientDiffieHellmanPublic; - * } exchange_keys; - * } ClientKeyExchange; - * - * struct { - * ProtocolVersion client_version; - * opaque random[46]; - * } PreMasterSecret; - * - * struct { - * public-key-encrypted PreMasterSecret pre_master_secret; - * } EncryptedPreMasterSecret; - * - * A public-key-encrypted element is encoded as a vector <0..2^16-1>. - * - * @param c the connection. - * - * @return the ClientKeyExchange byte buffer. - */ -tls$1.createClientKeyExchange = function(c) { - // create buffer to encrypt - var b = forge$b.util.createBuffer(); - - // add highest client-supported protocol to help server avoid version - // rollback attacks - b.putByte(c.session.clientHelloVersion.major); - b.putByte(c.session.clientHelloVersion.minor); - - // generate and add 46 random bytes - b.putBytes(forge$b.random.getBytes(46)); - - // save pre-master secret - var sp = c.session.sp; - sp.pre_master_secret = b.getBytes(); - - // RSA-encrypt the pre-master secret - var key = c.session.serverCertificate.publicKey; - b = key.encrypt(sp.pre_master_secret); - - /* Note: The encrypted pre-master secret will be stored in a - public-key-encrypted opaque vector that has the length prefixed using - 2 bytes, so include those 2 bytes in the handshake message length. This - is done as a minor optimization instead of calling writeVector(). */ - - // determine length of the handshake message - var length = b.length + 2; - - // build record fragment - var rval = forge$b.util.createBuffer(); - rval.putByte(tls$1.HandshakeType.client_key_exchange); - rval.putInt24(length); - // add vector length bytes - rval.putInt16(b.length); - rval.putBytes(b); - return rval; -}; - -/** - * Creates a ServerKeyExchange message. - * - * @param c the connection. - * - * @return the ServerKeyExchange byte buffer. - */ -tls$1.createServerKeyExchange = function(c) { - - // build record fragment - var rval = forge$b.util.createBuffer(); - return rval; -}; - -/** - * Gets the signed data used to verify a client-side certificate. See - * tls.createCertificateVerify() for details. - * - * @param c the connection. - * @param callback the callback to call once the signed data is ready. - */ -tls$1.getClientSignature = function(c, callback) { - // generate data to RSA encrypt - var b = forge$b.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - b = b.getBytes(); - - // create default signing function as necessary - c.getSignature = c.getSignature || function(c, b, callback) { - // do rsa encryption, call callback - var privateKey = null; - if(c.getPrivateKey) { - try { - privateKey = c.getPrivateKey(c, c.session.clientCertificate); - privateKey = forge$b.pki.privateKeyFromPem(privateKey); - } catch(ex) { - c.error(c, { - message: 'Could not get private key.', - cause: ex, - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.internal_error - } - }); - } - } - if(privateKey === null) { - c.error(c, { - message: 'No private key set.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.internal_error - } - }); - } else { - b = privateKey.sign(b, null); - } - callback(c, b); - }; - - // get client signature - c.getSignature(c, b, callback); -}; - -/** - * Creates a CertificateVerify message. - * - * Meaning of this message: - * This structure conveys the client's Diffie-Hellman public value - * (Yc) if it was not already included in the client's certificate. - * The encoding used for Yc is determined by the enumerated - * PublicValueEncoding. This structure is a variant of the client - * key exchange message, not a message in itself. - * - * When this message will be sent: - * This message is used to provide explicit verification of a client - * certificate. This message is only sent following a client - * certificate that has signing capability (i.e. all certificates - * except those containing fixed Diffie-Hellman parameters). When - * sent, it will immediately follow the client key exchange message. - * - * struct { - * Signature signature; - * } CertificateVerify; - * - * CertificateVerify.signature.md5_hash - * MD5(handshake_messages); - * - * Certificate.signature.sha_hash - * SHA(handshake_messages); - * - * Here handshake_messages refers to all handshake messages sent or - * received starting at client hello up to but not including this - * message, including the type and length fields of the handshake - * messages. - * - * select(SignatureAlgorithm) { - * case anonymous: struct { }; - * case rsa: - * digitally-signed struct { - * opaque md5_hash[16]; - * opaque sha_hash[20]; - * }; - * case dsa: - * digitally-signed struct { - * opaque sha_hash[20]; - * }; - * } Signature; - * - * In digital signing, one-way hash functions are used as input for a - * signing algorithm. A digitally-signed element is encoded as an opaque - * vector <0..2^16-1>, where the length is specified by the signing - * algorithm and key. - * - * In RSA signing, a 36-byte structure of two hashes (one SHA and one - * MD5) is signed (encrypted with the private key). It is encoded with - * PKCS #1 block type 0 or type 1 as described in [PKCS1]. - * - * In DSS, the 20 bytes of the SHA hash are run directly through the - * Digital Signing Algorithm with no additional hashing. - * - * @param c the connection. - * @param signature the signature to include in the message. - * - * @return the CertificateVerify byte buffer. - */ -tls$1.createCertificateVerify = function(c, signature) { - /* Note: The signature will be stored in a "digitally-signed" opaque - vector that has the length prefixed using 2 bytes, so include those - 2 bytes in the handshake message length. This is done as a minor - optimization instead of calling writeVector(). */ - - // determine length of the handshake message - var length = signature.length + 2; - - // build record fragment - var rval = forge$b.util.createBuffer(); - rval.putByte(tls$1.HandshakeType.certificate_verify); - rval.putInt24(length); - // add vector length bytes - rval.putInt16(signature.length); - rval.putBytes(signature); - return rval; -}; - -/** - * Creates a CertificateRequest message. - * - * @param c the connection. - * - * @return the CertificateRequest byte buffer. - */ -tls$1.createCertificateRequest = function(c) { - // TODO: support other certificate types - var certTypes = forge$b.util.createBuffer(); - - // common RSA certificate type - certTypes.putByte(0x01); - - // add distinguished names from CA store - var cAs = forge$b.util.createBuffer(); - for(var key in c.caStore.certs) { - var cert = c.caStore.certs[key]; - var dn = forge$b.pki.distinguishedNameToAsn1(cert.subject); - var byteBuffer = forge$b.asn1.toDer(dn); - cAs.putInt16(byteBuffer.length()); - cAs.putBuffer(byteBuffer); - } - - // TODO: TLS 1.2+ has a different format - - // determine length of the handshake message - var length = - 1 + certTypes.length() + - 2 + cAs.length(); - - // build record fragment - var rval = forge$b.util.createBuffer(); - rval.putByte(tls$1.HandshakeType.certificate_request); - rval.putInt24(length); - writeVector(rval, 1, certTypes); - writeVector(rval, 2, cAs); - return rval; -}; - -/** - * Creates a ServerHelloDone message. - * - * @param c the connection. - * - * @return the ServerHelloDone byte buffer. - */ -tls$1.createServerHelloDone = function(c) { - // build record fragment - var rval = forge$b.util.createBuffer(); - rval.putByte(tls$1.HandshakeType.server_hello_done); - rval.putInt24(0); - return rval; -}; - -/** - * Creates a ChangeCipherSpec message. - * - * The change cipher spec protocol exists to signal transitions in - * ciphering strategies. The protocol consists of a single message, - * which is encrypted and compressed under the current (not the pending) - * connection state. The message consists of a single byte of value 1. - * - * struct { - * enum { change_cipher_spec(1), (255) } type; - * } ChangeCipherSpec; - * - * @return the ChangeCipherSpec byte buffer. - */ -tls$1.createChangeCipherSpec = function() { - var rval = forge$b.util.createBuffer(); - rval.putByte(0x01); - return rval; -}; - -/** - * Creates a Finished message. - * - * struct { - * opaque verify_data[12]; - * } Finished; - * - * verify_data - * PRF(master_secret, finished_label, MD5(handshake_messages) + - * SHA-1(handshake_messages)) [0..11]; - * - * finished_label - * For Finished messages sent by the client, the string "client - * finished". For Finished messages sent by the server, the - * string "server finished". - * - * handshake_messages - * All of the data from all handshake messages up to but not - * including this message. This is only data visible at the - * handshake layer and does not include record layer headers. - * This is the concatenation of all the Handshake structures as - * defined in 7.4 exchanged thus far. - * - * @param c the connection. - * - * @return the Finished byte buffer. - */ -tls$1.createFinished = function(c) { - // generate verify_data - var b = forge$b.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - - // TODO: determine prf function and verify length for TLS 1.2 - var client = (c.entity === tls$1.ConnectionEnd.client); - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - var label = client ? 'client finished' : 'server finished'; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - - // build record fragment - var rval = forge$b.util.createBuffer(); - rval.putByte(tls$1.HandshakeType.finished); - rval.putInt24(b.length()); - rval.putBuffer(b); - return rval; -}; - -/** - * Creates a HeartbeatMessage (See RFC 6520). - * - * struct { - * HeartbeatMessageType type; - * uint16 payload_length; - * opaque payload[HeartbeatMessage.payload_length]; - * opaque padding[padding_length]; - * } HeartbeatMessage; - * - * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or - * max_fragment_length when negotiated as defined in [RFC6066]. - * - * type: The message type, either heartbeat_request or heartbeat_response. - * - * payload_length: The length of the payload. - * - * payload: The payload consists of arbitrary content. - * - * padding: The padding is random content that MUST be ignored by the - * receiver. The length of a HeartbeatMessage is TLSPlaintext.length - * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the - * length of the type field is 1 byte, and the length of the - * payload_length is 2. Therefore, the padding_length is - * TLSPlaintext.length - payload_length - 3 for TLS and - * DTLSPlaintext.length - payload_length - 3 for DTLS. The - * padding_length MUST be at least 16. - * - * The sender of a HeartbeatMessage MUST use a random padding of at - * least 16 bytes. The padding of a received HeartbeatMessage message - * MUST be ignored. - * - * If the payload_length of a received HeartbeatMessage is too large, - * the received HeartbeatMessage MUST be discarded silently. - * - * @param c the connection. - * @param type the tls.HeartbeatMessageType. - * @param payload the heartbeat data to send as the payload. - * @param [payloadLength] the payload length to use, defaults to the - * actual payload length. - * - * @return the HeartbeatRequest byte buffer. - */ -tls$1.createHeartbeat = function(type, payload, payloadLength) { - if(typeof payloadLength === 'undefined') { - payloadLength = payload.length; - } - // build record fragment - var rval = forge$b.util.createBuffer(); - rval.putByte(type); // heartbeat message type - rval.putInt16(payloadLength); // payload length - rval.putBytes(payload); // payload - // padding - var plaintextLength = rval.length(); - var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); - rval.putBytes(forge$b.random.getBytes(paddingLength)); - return rval; -}; - -/** - * Fragments, compresses, encrypts, and queues a record for delivery. - * - * @param c the connection. - * @param record the record to queue. - */ -tls$1.queue = function(c, record) { - // error during record creation - if(!record) { - return; - } - - if(record.fragment.length() === 0) { - if(record.type === tls$1.ContentType.handshake || - record.type === tls$1.ContentType.alert || - record.type === tls$1.ContentType.change_cipher_spec) { - // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent. - return; - } - } - - // if the record is a handshake record, update handshake hashes - if(record.type === tls$1.ContentType.handshake) { - var bytes = record.fragment.bytes(); - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - bytes = null; - } - - // handle record fragmentation - var records; - if(record.fragment.length() <= tls$1.MaxFragment) { - records = [record]; - } else { - // fragment data as long as it is too long - records = []; - var data = record.fragment.bytes(); - while(data.length > tls$1.MaxFragment) { - records.push(tls$1.createRecord(c, { - type: record.type, - data: forge$b.util.createBuffer(data.slice(0, tls$1.MaxFragment)) - })); - data = data.slice(tls$1.MaxFragment); - } - // add last record - if(data.length > 0) { - records.push(tls$1.createRecord(c, { - type: record.type, - data: forge$b.util.createBuffer(data) - })); - } - } - - // compress and encrypt all fragmented records - for(var i = 0; i < records.length && !c.fail; ++i) { - // update the record using current write state - var rec = records[i]; - var s = c.state.current.write; - if(s.update(c, rec)) { - // store record - c.records.push(rec); - } - } -}; - -/** - * Flushes all queued records to the output buffer and calls the - * tlsDataReady() handler on the given connection. - * - * @param c the connection. - * - * @return true on success, false on failure. - */ -tls$1.flush = function(c) { - for(var i = 0; i < c.records.length; ++i) { - var record = c.records[i]; - - // add record header and fragment - c.tlsData.putByte(record.type); - c.tlsData.putByte(record.version.major); - c.tlsData.putByte(record.version.minor); - c.tlsData.putInt16(record.fragment.length()); - c.tlsData.putBuffer(c.records[i].fragment); - } - c.records = []; - return c.tlsDataReady(c); -}; - -/** - * Maps a pki.certificateError to a tls.Alert.Description. - * - * @param error the error to map. - * - * @return the alert description. - */ -var _certErrorToAlertDesc = function(error) { - switch(error) { - case true: - return true; - case forge$b.pki.certificateError.bad_certificate: - return tls$1.Alert.Description.bad_certificate; - case forge$b.pki.certificateError.unsupported_certificate: - return tls$1.Alert.Description.unsupported_certificate; - case forge$b.pki.certificateError.certificate_revoked: - return tls$1.Alert.Description.certificate_revoked; - case forge$b.pki.certificateError.certificate_expired: - return tls$1.Alert.Description.certificate_expired; - case forge$b.pki.certificateError.certificate_unknown: - return tls$1.Alert.Description.certificate_unknown; - case forge$b.pki.certificateError.unknown_ca: - return tls$1.Alert.Description.unknown_ca; - default: - return tls$1.Alert.Description.bad_certificate; - } -}; - -/** - * Maps a tls.Alert.Description to a pki.certificateError. - * - * @param desc the alert description. - * - * @return the certificate error. - */ -var _alertDescToCertError = function(desc) { - switch(desc) { - case true: - return true; - case tls$1.Alert.Description.bad_certificate: - return forge$b.pki.certificateError.bad_certificate; - case tls$1.Alert.Description.unsupported_certificate: - return forge$b.pki.certificateError.unsupported_certificate; - case tls$1.Alert.Description.certificate_revoked: - return forge$b.pki.certificateError.certificate_revoked; - case tls$1.Alert.Description.certificate_expired: - return forge$b.pki.certificateError.certificate_expired; - case tls$1.Alert.Description.certificate_unknown: - return forge$b.pki.certificateError.certificate_unknown; - case tls$1.Alert.Description.unknown_ca: - return forge$b.pki.certificateError.unknown_ca; - default: - return forge$b.pki.certificateError.bad_certificate; - } -}; - -/** - * Verifies a certificate chain against the given connection's - * Certificate Authority store. - * - * @param c the TLS connection. - * @param chain the certificate chain to verify, with the root or highest - * authority at the end. - * - * @return true if successful, false if not. - */ -tls$1.verifyCertificateChain = function(c, chain) { - try { - // Make a copy of c.verifyOptions so that we can modify options.verify - // without modifying c.verifyOptions. - var options = {}; - for (var key in c.verifyOptions) { - options[key] = c.verifyOptions[key]; - } - - options.verify = function(vfd, depth, chain) { - - // call application callback - var ret = c.verify(c, vfd, depth, chain); - if(ret !== true) { - if(typeof ret === 'object' && !forge$b.util.isArray(ret)) { - // throw custom error - var error = new Error('The application rejected the certificate.'); - error.send = true; - error.alert = { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.bad_certificate - }; - if(ret.message) { - error.message = ret.message; - } - if(ret.alert) { - error.alert.description = ret.alert; - } - throw error; - } - - // convert tls alert description to pki.certificateError - if(ret !== vfd) { - ret = _alertDescToCertError(ret); - } - } - - return ret; - }; - - // verify chain - forge$b.pki.verifyCertificateChain(c.caStore, chain, options); - } catch(ex) { - // build tls error if not already customized - var err = ex; - if(typeof err !== 'object' || forge$b.util.isArray(err)) { - err = { - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: _certErrorToAlertDesc(ex) - } - }; - } - if(!('send' in err)) { - err.send = true; - } - if(!('alert' in err)) { - err.alert = { - level: tls$1.Alert.Level.fatal, - description: _certErrorToAlertDesc(err.error) - }; - } - - // send error - c.error(c, err); - } - - return !c.fail; -}; - -/** - * Creates a new TLS session cache. - * - * @param cache optional map of session ID to cached session. - * @param capacity the maximum size for the cache (default: 100). - * - * @return the new TLS session cache. - */ -tls$1.createSessionCache = function(cache, capacity) { - var rval = null; - - // assume input is already a session cache object - if(cache && cache.getSession && cache.setSession && cache.order) { - rval = cache; - } else { - // create cache - rval = {}; - rval.cache = cache || {}; - rval.capacity = Math.max(capacity || 100, 1); - rval.order = []; - - // store order for sessions, delete session overflow - for(var key in cache) { - if(rval.order.length <= capacity) { - rval.order.push(key); - } else { - delete cache[key]; - } - } - - // get a session from a session ID (or get any session) - rval.getSession = function(sessionId) { - var session = null; - var key = null; - - // if session ID provided, use it - if(sessionId) { - key = forge$b.util.bytesToHex(sessionId); - } else if(rval.order.length > 0) { - // get first session from cache - key = rval.order[0]; - } - - if(key !== null && key in rval.cache) { - // get cached session and remove from cache - session = rval.cache[key]; - delete rval.cache[key]; - for(var i in rval.order) { - if(rval.order[i] === key) { - rval.order.splice(i, 1); - break; - } - } - } - - return session; - }; - - // set a session in the cache - rval.setSession = function(sessionId, session) { - // remove session from cache if at capacity - if(rval.order.length === rval.capacity) { - var key = rval.order.shift(); - delete rval.cache[key]; - } - // add session to cache - var key = forge$b.util.bytesToHex(sessionId); - rval.order.push(key); - rval.cache[key] = session; - }; - } - - return rval; -}; - -/** - * Creates a new TLS connection. - * - * See public createConnection() docs for more details. - * - * @param options the options for this connection. - * - * @return the new TLS connection. - */ -tls$1.createConnection = function(options) { - var caStore = null; - if(options.caStore) { - // if CA store is an array, convert it to a CA store object - if(forge$b.util.isArray(options.caStore)) { - caStore = forge$b.pki.createCaStore(options.caStore); - } else { - caStore = options.caStore; - } - } else { - // create empty CA store - caStore = forge$b.pki.createCaStore(); - } - - // setup default cipher suites - var cipherSuites = options.cipherSuites || null; - if(cipherSuites === null) { - cipherSuites = []; - for(var key in tls$1.CipherSuites) { - cipherSuites.push(tls$1.CipherSuites[key]); - } - } - - // set default entity - var entity = (options.server || false) ? - tls$1.ConnectionEnd.server : tls$1.ConnectionEnd.client; - - // create session cache if requested - var sessionCache = options.sessionCache ? - tls$1.createSessionCache(options.sessionCache) : null; - - // create TLS connection - var c = { - version: {major: tls$1.Version.major, minor: tls$1.Version.minor}, - entity: entity, - sessionId: options.sessionId, - caStore: caStore, - sessionCache: sessionCache, - cipherSuites: cipherSuites, - connected: options.connected, - virtualHost: options.virtualHost || null, - verifyClient: options.verifyClient || false, - verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;}, - verifyOptions: options.verifyOptions || {}, - getCertificate: options.getCertificate || null, - getPrivateKey: options.getPrivateKey || null, - getSignature: options.getSignature || null, - input: forge$b.util.createBuffer(), - tlsData: forge$b.util.createBuffer(), - data: forge$b.util.createBuffer(), - tlsDataReady: options.tlsDataReady, - dataReady: options.dataReady, - heartbeatReceived: options.heartbeatReceived, - closed: options.closed, - error: function(c, ex) { - // set origin if not set - ex.origin = ex.origin || - ((c.entity === tls$1.ConnectionEnd.client) ? 'client' : 'server'); - - // send TLS alert - if(ex.send) { - tls$1.queue(c, tls$1.createAlert(c, ex.alert)); - tls$1.flush(c); - } - - // error is fatal by default - var fatal = (ex.fatal !== false); - if(fatal) { - // set fail flag - c.fail = true; - } - - // call error handler first - options.error(c, ex); - - if(fatal) { - // fatal error, close connection, do not clear fail - c.close(false); - } - }, - deflate: options.deflate || null, - inflate: options.inflate || null - }; - - /** - * Resets a closed TLS connection for reuse. Called in c.close(). - * - * @param clearFail true to clear the fail flag (default: true). - */ - c.reset = function(clearFail) { - c.version = {major: tls$1.Version.major, minor: tls$1.Version.minor}; - c.record = null; - c.session = null; - c.peerCertificate = null; - c.state = { - pending: null, - current: null - }; - c.expect = (c.entity === tls$1.ConnectionEnd.client) ? SHE : CHE; - c.fragmented = null; - c.records = []; - c.open = false; - c.handshakes = 0; - c.handshaking = false; - c.isConnected = false; - c.fail = !(clearFail || typeof(clearFail) === 'undefined'); - c.input.clear(); - c.tlsData.clear(); - c.data.clear(); - c.state.current = tls$1.createConnectionState(c); - }; - - // do initial reset of connection - c.reset(); - - /** - * Updates the current TLS engine state based on the given record. - * - * @param c the TLS connection. - * @param record the TLS record to act on. - */ - var _update = function(c, record) { - // get record handler (align type in table by subtracting lowest) - var aligned = record.type - tls$1.ContentType.change_cipher_spec; - var handlers = ctTable[c.entity][c.expect]; - if(aligned in handlers) { - handlers[aligned](c, record); - } else { - // unexpected record - tls$1.handleUnexpected(c, record); - } - }; - - /** - * Reads the record header and initializes the next record on the given - * connection. - * - * @param c the TLS connection with the next record. - * - * @return 0 if the input data could be processed, otherwise the - * number of bytes required for data to be processed. - */ - var _readRecordHeader = function(c) { - var rval = 0; - - // get input buffer and its length - var b = c.input; - var len = b.length(); - - // need at least 5 bytes to initialize a record - if(len < 5) { - rval = 5 - len; - } else { - // enough bytes for header - // initialize record - c.record = { - type: b.getByte(), - version: { - major: b.getByte(), - minor: b.getByte() - }, - length: b.getInt16(), - fragment: forge$b.util.createBuffer(), - ready: false - }; - - // check record version - var compatibleVersion = (c.record.version.major === c.version.major); - if(compatibleVersion && c.session && c.session.version) { - // session version already set, require same minor version - compatibleVersion = (c.record.version.minor === c.version.minor); - } - if(!compatibleVersion) { - c.error(c, { - message: 'Incompatible TLS version.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: tls$1.Alert.Description.protocol_version - } - }); - } - } - - return rval; - }; - - /** - * Reads the next record's contents and appends its message to any - * previously fragmented message. - * - * @param c the TLS connection with the next record. - * - * @return 0 if the input data could be processed, otherwise the - * number of bytes required for data to be processed. - */ - var _readRecord = function(c) { - var rval = 0; - - // ensure there is enough input data to get the entire record - var b = c.input; - var len = b.length(); - if(len < c.record.length) { - // not enough data yet, return how much is required - rval = c.record.length - len; - } else { - // there is enough data to parse the pending record - // fill record fragment and compact input buffer - c.record.fragment.putBytes(b.getBytes(c.record.length)); - b.compact(); - - // update record using current read state - var s = c.state.current.read; - if(s.update(c, c.record)) { - // see if there is a previously fragmented message that the - // new record's message fragment should be appended to - if(c.fragmented !== null) { - // if the record type matches a previously fragmented - // record, append the record fragment to it - if(c.fragmented.type === c.record.type) { - // concatenate record fragments - c.fragmented.fragment.putBuffer(c.record.fragment); - c.record = c.fragmented; - } else { - // error, invalid fragmented record - c.error(c, { - message: 'Invalid fragmented record.', - send: true, - alert: { - level: tls$1.Alert.Level.fatal, - description: - tls$1.Alert.Description.unexpected_message - } - }); - } - } - - // record is now ready - c.record.ready = true; - } - } - - return rval; - }; - - /** - * Performs a handshake using the TLS Handshake Protocol, as a client. - * - * This method should only be called if the connection is in client mode. - * - * @param sessionId the session ID to use, null to start a new one. - */ - c.handshake = function(sessionId) { - // error to call this in non-client mode - if(c.entity !== tls$1.ConnectionEnd.client) { - // not fatal error - c.error(c, { - message: 'Cannot initiate handshake as a server.', - fatal: false - }); - } else if(c.handshaking) { - // handshake is already in progress, fail but not fatal error - c.error(c, { - message: 'Handshake already in progress.', - fatal: false - }); - } else { - // clear fail flag on reuse - if(c.fail && !c.open && c.handshakes === 0) { - c.fail = false; - } - - // now handshaking - c.handshaking = true; - - // default to blank (new session) - sessionId = sessionId || ''; - - // if a session ID was specified, try to find it in the cache - var session = null; - if(sessionId.length > 0) { - if(c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - } - - // matching session not found in cache, clear session ID - if(session === null) { - sessionId = ''; - } - } - - // no session given, grab a session from the cache, if available - if(sessionId.length === 0 && c.sessionCache) { - session = c.sessionCache.getSession(); - if(session !== null) { - sessionId = session.id; - } - } - - // set up session - c.session = { - id: sessionId, - version: null, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - certificateRequest: null, - clientCertificate: null, - sp: {}, - md5: forge$b.md.md5.create(), - sha1: forge$b.md.sha1.create() - }; - - // use existing session information - if(session) { - // only update version on connection, session version not yet set - c.version = session.version; - c.session.sp = session.sp; - } - - // generate new client random - c.session.sp.client_random = tls$1.createRandom().getBytes(); - - // connection now open - c.open = true; - - // send hello - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.handshake, - data: tls$1.createClientHello(c) - })); - tls$1.flush(c); - } - }; - - /** - * Called when TLS protocol data has been received from somewhere and should - * be processed by the TLS engine. - * - * @param data the TLS protocol data, as a string, to process. - * - * @return 0 if the data could be processed, otherwise the number of bytes - * required for data to be processed. - */ - c.process = function(data) { - var rval = 0; - - // buffer input data - if(data) { - c.input.putBytes(data); - } - - // process next record if no failure, process will be called after - // each record is handled (since handling can be asynchronous) - if(!c.fail) { - // reset record if ready and now empty - if(c.record !== null && - c.record.ready && c.record.fragment.isEmpty()) { - c.record = null; - } - - // if there is no pending record, try to read record header - if(c.record === null) { - rval = _readRecordHeader(c); - } - - // read the next record (if record not yet ready) - if(!c.fail && c.record !== null && !c.record.ready) { - rval = _readRecord(c); - } - - // record ready to be handled, update engine state - if(!c.fail && c.record !== null && c.record.ready) { - _update(c, c.record); - } - } - - return rval; - }; - - /** - * Requests that application data be packaged into a TLS record. The - * tlsDataReady handler will be called when the TLS record(s) have been - * prepared. - * - * @param data the application data, as a raw 'binary' encoded string, to - * be sent; to send utf-16/utf-8 string data, use the return value - * of util.encodeUtf8(str). - * - * @return true on success, false on failure. - */ - c.prepare = function(data) { - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.application_data, - data: forge$b.util.createBuffer(data) - })); - return tls$1.flush(c); - }; - - /** - * Requests that a heartbeat request be packaged into a TLS record for - * transmission. The tlsDataReady handler will be called when TLS record(s) - * have been prepared. - * - * When a heartbeat response has been received, the heartbeatReceived - * handler will be called with the matching payload. This handler can - * be used to clear a retransmission timer, etc. - * - * @param payload the heartbeat data to send as the payload in the message. - * @param [payloadLength] the payload length to use, defaults to the - * actual payload length. - * - * @return true on success, false on failure. - */ - c.prepareHeartbeatRequest = function(payload, payloadLength) { - if(payload instanceof forge$b.util.ByteBuffer) { - payload = payload.bytes(); - } - if(typeof payloadLength === 'undefined') { - payloadLength = payload.length; - } - c.expectedHeartbeatPayload = payload; - tls$1.queue(c, tls$1.createRecord(c, { - type: tls$1.ContentType.heartbeat, - data: tls$1.createHeartbeat( - tls$1.HeartbeatMessageType.heartbeat_request, payload, payloadLength) - })); - return tls$1.flush(c); - }; - - /** - * Closes the connection (sends a close_notify alert). - * - * @param clearFail true to clear the fail flag (default: true). - */ - c.close = function(clearFail) { - // save session if connection didn't fail - if(!c.fail && c.sessionCache && c.session) { - // only need to preserve session ID, version, and security params - var session = { - id: c.session.id, - version: c.session.version, - sp: c.session.sp - }; - session.sp.keys = null; - c.sessionCache.setSession(session.id, session); - } - - if(c.open) { - // connection no longer open, clear input - c.open = false; - c.input.clear(); - - // if connected or handshaking, send an alert - if(c.isConnected || c.handshaking) { - c.isConnected = c.handshaking = false; - - // send close_notify alert - tls$1.queue(c, tls$1.createAlert(c, { - level: tls$1.Alert.Level.warning, - description: tls$1.Alert.Description.close_notify - })); - tls$1.flush(c); - } - - // call handler - c.closed(c); - } - - // reset TLS connection, do not clear fail flag - c.reset(clearFail); - }; - - return c; -}; - -/* TLS API */ -forge$b.tls = forge$b.tls || {}; - -// expose non-functions -for(var key in tls$1) { - if(typeof tls$1[key] !== 'function') { - forge$b.tls[key] = tls$1[key]; - } -} - -// expose prf_tls1 for testing -forge$b.tls.prf_tls1 = prf_TLS1; - -// expose sha1 hmac method -forge$b.tls.hmac_sha1 = hmac_sha1; - -// expose session cache creation -forge$b.tls.createSessionCache = tls$1.createSessionCache; - -/** - * Creates a new TLS connection. This does not make any assumptions about the - * transport layer that TLS is working on top of, ie: it does not assume there - * is a TCP/IP connection or establish one. A TLS connection is totally - * abstracted away from the layer is runs on top of, it merely establishes a - * secure channel between a client" and a "server". - * - * A TLS connection contains 4 connection states: pending read and write, and - * current read and write. - * - * At initialization, the current read and write states will be null. Only once - * the security parameters have been set and the keys have been generated can - * the pending states be converted into current states. Current states will be - * updated for each record processed. - * - * A custom certificate verify callback may be provided to check information - * like the common name on the server's certificate. It will be called for - * every certificate in the chain. It has the following signature: - * - * variable func(c, certs, index, preVerify) - * Where: - * c The TLS connection - * verified Set to true if certificate was verified, otherwise the alert - * tls.Alert.Description for why the certificate failed. - * depth The current index in the chain, where 0 is the server's cert. - * certs The certificate chain, *NOTE* if the server was anonymous then - * the chain will be empty. - * - * The function returns true on success and on failure either the appropriate - * tls.Alert.Description or an object with 'alert' set to the appropriate - * tls.Alert.Description and 'message' set to a custom error message. If true - * is not returned then the connection will abort using, in order of - * availability, first the returned alert description, second the preVerify - * alert description, and lastly the default 'bad_certificate'. - * - * There are three callbacks that can be used to make use of client-side - * certificates where each takes the TLS connection as the first parameter: - * - * getCertificate(conn, hint) - * The second parameter is a hint as to which certificate should be - * returned. If the connection entity is a client, then the hint will be - * the CertificateRequest message from the server that is part of the - * TLS protocol. If the connection entity is a server, then it will be - * the servername list provided via an SNI extension the ClientHello, if - * one was provided (empty array if not). The hint can be examined to - * determine which certificate to use (advanced). Most implementations - * will just return a certificate. The return value must be a - * PEM-formatted certificate or an array of PEM-formatted certificates - * that constitute a certificate chain, with the first in the array/chain - * being the client's certificate. - * getPrivateKey(conn, certificate) - * The second parameter is an forge.pki X.509 certificate object that - * is associated with the requested private key. The return value must - * be a PEM-formatted private key. - * getSignature(conn, bytes, callback) - * This callback can be used instead of getPrivateKey if the private key - * is not directly accessible in javascript or should not be. For - * instance, a secure external web service could provide the signature - * in exchange for appropriate credentials. The second parameter is a - * string of bytes to be signed that are part of the TLS protocol. These - * bytes are used to verify that the private key for the previously - * provided client-side certificate is accessible to the client. The - * callback is a function that takes 2 parameters, the TLS connection - * and the RSA encrypted (signed) bytes as a string. This callback must - * be called once the signature is ready. - * - * @param options the options for this connection: - * server: true if the connection is server-side, false for client. - * sessionId: a session ID to reuse, null for a new connection. - * caStore: an array of certificates to trust. - * sessionCache: a session cache to use. - * cipherSuites: an optional array of cipher suites to use, - * see tls.CipherSuites. - * connected: function(conn) called when the first handshake completes. - * virtualHost: the virtual server name to use in a TLS SNI extension. - * verifyClient: true to require a client certificate in server mode, - * 'optional' to request one, false not to (default: false). - * verify: a handler used to custom verify certificates in the chain. - * verifyOptions: an object with options for the certificate chain validation. - * See documentation of pki.verifyCertificateChain for possible options. - * verifyOptions.verify is ignored. If you wish to specify a verify handler - * use the verify key. - * getCertificate: an optional callback used to get a certificate or - * a chain of certificates (as an array). - * getPrivateKey: an optional callback used to get a private key. - * getSignature: an optional callback used to get a signature. - * tlsDataReady: function(conn) called when TLS protocol data has been - * prepared and is ready to be used (typically sent over a socket - * connection to its destination), read from conn.tlsData buffer. - * dataReady: function(conn) called when application data has - * been parsed from a TLS record and should be consumed by the - * application, read from conn.data buffer. - * closed: function(conn) called when the connection has been closed. - * error: function(conn, error) called when there was an error. - * deflate: function(inBytes) if provided, will deflate TLS records using - * the deflate algorithm if the server supports it. - * inflate: function(inBytes) if provided, will inflate TLS records using - * the deflate algorithm if the server supports it. - * - * @return the new TLS connection. - */ -forge$b.tls.createConnection = tls$1.createConnection; - -/** - * A Javascript implementation of AES Cipher Suites for TLS. - * - * @author Dave Longley - * - * Copyright (c) 2009-2015 Digital Bazaar, Inc. - * - */ - -var forge$a = forge$F; - - - -var tls = forge$a.tls; - -/** - * Supported cipher suites. - */ -tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = { - id: [0x00, 0x2f], - name: 'TLS_RSA_WITH_AES_128_CBC_SHA', - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 16; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState: initConnectionState -}; -tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = { - id: [0x00, 0x35], - name: 'TLS_RSA_WITH_AES_256_CBC_SHA', - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 32; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState: initConnectionState -}; - -function initConnectionState(state, c, sp) { - var client = (c.entity === forge$a.tls.ConnectionEnd.client); - - // cipher setup - state.read.cipherState = { - init: false, - cipher: forge$a.cipher.createDecipher('AES-CBC', client ? - sp.keys.server_write_key : sp.keys.client_write_key), - iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV - }; - state.write.cipherState = { - init: false, - cipher: forge$a.cipher.createCipher('AES-CBC', client ? - sp.keys.client_write_key : sp.keys.server_write_key), - iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV - }; - state.read.cipherFunction = decrypt_aes_cbc_sha1; - state.write.cipherFunction = encrypt_aes_cbc_sha1; - - // MAC setup - state.read.macLength = state.write.macLength = sp.mac_length; - state.read.macFunction = state.write.macFunction = tls.hmac_sha1; -} - -/** - * Encrypts the TLSCompressed record into a TLSCipherText record using AES - * in CBC mode. - * - * @param record the TLSCompressed record to encrypt. - * @param s the ConnectionState to use. - * - * @return true on success, false on failure. - */ -function encrypt_aes_cbc_sha1(record, s) { - var rval = false; - - // append MAC to fragment, update sequence number - var mac = s.macFunction(s.macKey, s.sequenceNumber, record); - record.fragment.putBytes(mac); - s.updateSequenceNumber(); - - // TLS 1.1+ use an explicit IV every time to protect against CBC attacks - var iv; - if(record.version.minor === tls.Versions.TLS_1_0.minor) { - // use the pre-generated IV when initializing for TLS 1.0, otherwise use - // the residue from the previous encryption - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = forge$a.random.getBytesSync(16); - } - - s.cipherState.init = true; - - // start cipher - var cipher = s.cipherState.cipher; - cipher.start({iv: iv}); - - // TLS 1.1+ write IV into output - if(record.version.minor >= tls.Versions.TLS_1_1.minor) { - cipher.output.putBytes(iv); - } - - // do encryption (default padding is appropriate) - cipher.update(record.fragment); - if(cipher.finish(encrypt_aes_cbc_sha1_padding)) { - // set record fragment to encrypted output - record.fragment = cipher.output; - record.length = record.fragment.length(); - rval = true; - } - - return rval; -} - -/** - * Handles padding for aes_cbc_sha1 in encrypt mode. - * - * @param blockSize the block size. - * @param input the input buffer. - * @param decrypt true in decrypt mode, false in encrypt mode. - * - * @return true on success, false on failure. - */ -function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { - /* The encrypted data length (TLSCiphertext.length) is one more than the sum - of SecurityParameters.block_length, TLSCompressed.length, - SecurityParameters.mac_length, and padding_length. - - The padding may be any length up to 255 bytes long, as long as it results in - the TLSCiphertext.length being an integral multiple of the block length. - Lengths longer than necessary might be desirable to frustrate attacks on a - protocol based on analysis of the lengths of exchanged messages. Each uint8 - in the padding data vector must be filled with the padding length value. - - The padding length should be such that the total size of the - GenericBlockCipher structure is a multiple of the cipher's block length. - Legal values range from zero to 255, inclusive. This length specifies the - length of the padding field exclusive of the padding_length field itself. - - This is slightly different from PKCS#7 because the padding value is 1 - less than the actual number of padding bytes if you include the - padding_length uint8 itself as a padding byte. */ - if(!decrypt) { - // get the number of padding bytes required to reach the blockSize and - // subtract 1 for the padding value (to make room for the padding_length - // uint8) - var padding = blockSize - (input.length() % blockSize); - input.fillWithByte(padding - 1, padding); - } - return true; -} - -/** - * Handles padding for aes_cbc_sha1 in decrypt mode. - * - * @param blockSize the block size. - * @param output the output buffer. - * @param decrypt true in decrypt mode, false in encrypt mode. - * - * @return true on success, false on failure. - */ -function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { - var rval = true; - if(decrypt) { - /* The last byte in the output specifies the number of padding bytes not - including itself. Each of the padding bytes has the same value as that - last byte (known as the padding_length). Here we check all padding - bytes to ensure they have the value of padding_length even if one of - them is bad in order to ward-off timing attacks. */ - var len = output.length(); - var paddingLength = output.last(); - for(var i = len - 1 - paddingLength; i < len - 1; ++i) { - rval = rval && (output.at(i) == paddingLength); - } - if(rval) { - // trim off padding bytes and last padding length byte - output.truncate(paddingLength + 1); - } - } - return rval; -} - -/** - * Decrypts a TLSCipherText record into a TLSCompressed record using - * AES in CBC mode. - * - * @param record the TLSCipherText record to decrypt. - * @param s the ConnectionState to use. - * - * @return true on success, false on failure. - */ -function decrypt_aes_cbc_sha1(record, s) { - var rval = false; - - var iv; - if(record.version.minor === tls.Versions.TLS_1_0.minor) { - // use pre-generated IV when initializing for TLS 1.0, otherwise use the - // residue from the previous decryption - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - // TLS 1.1+ use an explicit IV every time to protect against CBC attacks - // that is appended to the record fragment - iv = record.fragment.getBytes(16); - } - - s.cipherState.init = true; - - // start cipher - var cipher = s.cipherState.cipher; - cipher.start({iv: iv}); - - // do decryption - cipher.update(record.fragment); - rval = cipher.finish(decrypt_aes_cbc_sha1_padding); - - // even if decryption fails, keep going to minimize timing attacks - - // decrypted data: - // first (len - 20) bytes = application data - // last 20 bytes = MAC - var macLen = s.macLength; - - // create a random MAC to check against should the mac length check fail - // Note: do this regardless of the failure to keep timing consistent - var mac = forge$a.random.getBytesSync(macLen); - - // get fragment and mac - var len = cipher.output.length(); - if(len >= macLen) { - record.fragment = cipher.output.getBytes(len - macLen); - mac = cipher.output.getBytes(macLen); - } else { - // bad data, but get bytes anyway to try to keep timing consistent - record.fragment = cipher.output.getBytes(); - } - record.fragment = forge$a.util.createBuffer(record.fragment); - record.length = record.fragment.length(); - - // see if data integrity checks out, update sequence number - var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); - s.updateSequenceNumber(); - rval = compareMacs(s.macKey, mac, mac2) && rval; - return rval; -} - -/** - * Safely compare two MACs. This function will compare two MACs in a way - * that protects against timing attacks. - * - * TODO: Expose elsewhere as a utility API. - * - * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/ - * - * @param key the MAC key to use. - * @param mac1 as a binary-encoded string of bytes. - * @param mac2 as a binary-encoded string of bytes. - * - * @return true if the MACs are the same, false if not. - */ -function compareMacs(key, mac1, mac2) { - var hmac = forge$a.hmac.create(); - - hmac.start('SHA1', key); - hmac.update(mac1); - mac1 = hmac.digest().getBytes(); - - hmac.start(null, null); - hmac.update(mac2); - mac2 = hmac.digest().getBytes(); - - return mac1 === mac2; -} - -/** - * Debugging support for web applications. - * - * @author David I. Lehn - * - * Copyright 2008-2013 Digital Bazaar, Inc. - */ - -var forge$9 = forge$F; - -/* DEBUG API */ -forge$9.debug = forge$9.debug || {}; - -// Private storage for debugging. -// Useful to expose data that is otherwise unviewable behind closures. -// NOTE: remember that this can hold references to data and cause leaks! -// format is "forge._debug.. = data" -// Example: -// (function() { -// var cat = 'forge.test.Test'; // debugging category -// var sState = {...}; // local state -// forge.debug.set(cat, 'sState', sState); -// })(); -forge$9.debug.storage = {}; - -/** - * Gets debug data. Omit name for all cat data Omit name and cat for - * all data. - * - * @param cat name of debugging category. - * @param name name of data to get (optional). - * @return object with requested debug data or undefined. - */ -forge$9.debug.get = function(cat, name) { - var rval; - if(typeof(cat) === 'undefined') { - rval = forge$9.debug.storage; - } else if(cat in forge$9.debug.storage) { - if(typeof(name) === 'undefined') { - rval = forge$9.debug.storage[cat]; - } else { - rval = forge$9.debug.storage[cat][name]; - } - } - return rval; -}; - -/** - * Sets debug data. - * - * @param cat name of debugging category. - * @param name name of data to set. - * @param data data to set. - */ -forge$9.debug.set = function(cat, name, data) { - if(!(cat in forge$9.debug.storage)) { - forge$9.debug.storage[cat] = {}; - } - forge$9.debug.storage[cat][name] = data; -}; - -/** - * Clears debug data. Omit name for all cat data. Omit name and cat for - * all data. - * - * @param cat name of debugging category. - * @param name name of data to clear or omit to clear entire category. - */ -forge$9.debug.clear = function(cat, name) { - if(typeof(cat) === 'undefined') { - forge$9.debug.storage = {}; - } else if(cat in forge$9.debug.storage) { - if(typeof(name) === 'undefined') { - delete forge$9.debug.storage[cat]; - } else { - delete forge$9.debug.storage[cat][name]; - } - } -}; - -/** - * Secure Hash Algorithm with a 1024-bit block size implementation. - * - * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For - * SHA-256 (block size 512 bits), see sha256.js. - * - * See FIPS 180-4 for details. - * - * @author Dave Longley - * - * Copyright (c) 2014-2015 Digital Bazaar, Inc. - */ - -var forge$8 = forge$F; - - - -var sha512$1 = forge$8.sha512 = forge$8.sha512 || {}; - -// SHA-512 -forge$8.md.sha512 = forge$8.md.algorithms.sha512 = sha512$1; - -// SHA-384 -var sha384 = forge$8.sha384 = forge$8.sha512.sha384 = forge$8.sha512.sha384 || {}; -sha384.create = function() { - return sha512$1.create('SHA-384'); -}; -forge$8.md.sha384 = forge$8.md.algorithms.sha384 = sha384; - -// SHA-512/256 -forge$8.sha512.sha256 = forge$8.sha512.sha256 || { - create: function() { - return sha512$1.create('SHA-512/256'); - } -}; -forge$8.md['sha512/256'] = forge$8.md.algorithms['sha512/256'] = - forge$8.sha512.sha256; - -// SHA-512/224 -forge$8.sha512.sha224 = forge$8.sha512.sha224 || { - create: function() { - return sha512$1.create('SHA-512/224'); - } -}; -forge$8.md['sha512/224'] = forge$8.md.algorithms['sha512/224'] = - forge$8.sha512.sha224; - -/** - * Creates a SHA-2 message digest object. - * - * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224, - * SHA-512/256). - * - * @return a message digest object. - */ -sha512$1.create = function(algorithm) { - // do initialization as necessary - if(!_initialized) { - _init(); - } - - if(typeof algorithm === 'undefined') { - algorithm = 'SHA-512'; - } - - if(!(algorithm in _states)) { - throw new Error('Invalid SHA-512 algorithm: ' + algorithm); - } - - // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints) - var _state = _states[algorithm]; - var _h = null; - - // input buffer - var _input = forge$8.util.createBuffer(); - - // used for 64-bit word storage - var _w = new Array(80); - for(var wi = 0; wi < 80; ++wi) { - _w[wi] = new Array(2); - } - - // determine digest length by algorithm name (default) - var digestLength = 64; - switch(algorithm) { - case 'SHA-384': - digestLength = 48; - break; - case 'SHA-512/256': - digestLength = 32; - break; - case 'SHA-512/224': - digestLength = 28; - break; - } - - // message digest object - var md = { - // SHA-512 => sha512 - algorithm: algorithm.replace('-', '').toLowerCase(), - blockLength: 128, - digestLength: digestLength, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 16 - }; - - /** - * Starts the digest. - * - * @return this digest object. - */ - md.start = function() { - // up to 56-bit message length for convenience - md.messageLength = 0; - - // full message length (set md.messageLength128 for backwards-compatibility) - md.fullMessageLength = md.messageLength128 = []; - var int32s = md.messageLengthSize / 4; - for(var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge$8.util.createBuffer(); - _h = new Array(_state.length); - for(var i = 0; i < _state.length; ++i) { - _h[i] = _state[i].slice(0); - } - return md; - }; - // start digest automatically for first time - md.start(); - - /** - * Updates the digest with the given message input. The given input can - * treated as raw input (no encoding will be applied) or an encoding of - * 'utf8' maybe given to encode the input using UTF-8. - * - * @param msg the message input to update with. - * @param encoding the encoding to use (default: 'raw', other: 'utf8'). - * - * @return this digest object. - */ - md.update = function(msg, encoding) { - if(encoding === 'utf8') { - msg = forge$8.util.encodeUtf8(msg); - } - - // update message length - var len = msg.length; - md.messageLength += len; - len = [(len / 0x100000000) >>> 0, len >>> 0]; - for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = ((len[1] / 0x100000000) >>> 0); - } - - // add bytes to input buffer - _input.putBytes(msg); - - // process bytes - _update(_h, _w, _input); - - // compact input buffer every 2K or if empty - if(_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - - return md; - }; - - /** - * Produces the digest. - * - * @return a byte buffer containing the digest value. - */ - md.digest = function() { - /* Note: Here we copy the remaining bytes in the input buffer and - add the appropriate SHA-512 padding. Then we do the final update - on a copy of the state so that if the user wants to get - intermediate digests they can do so. */ - - /* Determine the number of bytes that must be added to the message - to ensure its length is congruent to 896 mod 1024. In other words, - the data to be digested must be a multiple of 1024 bits (or 128 bytes). - This data includes the message, some padding, and the length of the - message. Since the length of the message will be encoded as 16 bytes (128 - bits), that means that the last segment of the data must have 112 bytes - (896 bits) of message and padding. Therefore, the length of the message - plus the padding must be congruent to 896 mod 1024 because - 1024 - 128 = 896. - - In order to fill up the message length it must be filled with - padding that begins with 1 bit followed by all 0 bits. Padding - must *always* be present, so if the message length is already - congruent to 896 mod 1024, then 1024 padding bits must be added. */ - - var finalBlock = forge$8.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - - // compute remaining size to be digested (include message length size) - var remaining = ( - md.fullMessageLength[md.fullMessageLength.length - 1] + - md.messageLengthSize); - - // add padding for overflow blockSize - overflow - // _padding starts with 1 byte with first bit is set (byte value 128), then - // there may be up to (blockSize - 1) other pad bytes - var overflow = remaining & (md.blockLength - 1); - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - - // serialize message length in bits in big-endian order; since length - // is stored in bytes we multiply by 8 and add carry from next int - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = (next / 0x100000000) >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - - var h = new Array(_h.length); - for(var i = 0; i < _h.length; ++i) { - h[i] = _h[i].slice(0); - } - _update(h, _w, finalBlock); - var rval = forge$8.util.createBuffer(); - var hlen; - if(algorithm === 'SHA-512') { - hlen = h.length; - } else if(algorithm === 'SHA-384') { - hlen = h.length - 2; - } else { - hlen = h.length - 4; - } - for(var i = 0; i < hlen; ++i) { - rval.putInt32(h[i][0]); - if(i !== hlen - 1 || algorithm !== 'SHA-512/224') { - rval.putInt32(h[i][1]); - } - } - return rval; - }; - - return md; -}; - -// sha-512 padding bytes not initialized yet -var _padding = null; -var _initialized = false; - -// table of constants -var _k = null; - -// initial hash states -var _states = null; - -/** - * Initializes the constant tables. - */ -function _init() { - // create padding - _padding = String.fromCharCode(128); - _padding += forge$8.util.fillString(String.fromCharCode(0x00), 128); - - // create K table for SHA-512 - _k = [ - [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd], - [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc], - [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019], - [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118], - [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe], - [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2], - [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1], - [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694], - [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3], - [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65], - [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483], - [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5], - [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210], - [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4], - [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725], - [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70], - [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926], - [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df], - [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8], - [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b], - [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001], - [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30], - [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910], - [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8], - [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53], - [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8], - [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb], - [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3], - [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60], - [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec], - [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9], - [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b], - [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207], - [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178], - [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6], - [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b], - [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493], - [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c], - [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a], - [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817] - ]; - - // initial hash states - _states = {}; - _states['SHA-512'] = [ - [0x6a09e667, 0xf3bcc908], - [0xbb67ae85, 0x84caa73b], - [0x3c6ef372, 0xfe94f82b], - [0xa54ff53a, 0x5f1d36f1], - [0x510e527f, 0xade682d1], - [0x9b05688c, 0x2b3e6c1f], - [0x1f83d9ab, 0xfb41bd6b], - [0x5be0cd19, 0x137e2179] - ]; - _states['SHA-384'] = [ - [0xcbbb9d5d, 0xc1059ed8], - [0x629a292a, 0x367cd507], - [0x9159015a, 0x3070dd17], - [0x152fecd8, 0xf70e5939], - [0x67332667, 0xffc00b31], - [0x8eb44a87, 0x68581511], - [0xdb0c2e0d, 0x64f98fa7], - [0x47b5481d, 0xbefa4fa4] - ]; - _states['SHA-512/256'] = [ - [0x22312194, 0xFC2BF72C], - [0x9F555FA3, 0xC84C64C2], - [0x2393B86B, 0x6F53B151], - [0x96387719, 0x5940EABD], - [0x96283EE2, 0xA88EFFE3], - [0xBE5E1E25, 0x53863992], - [0x2B0199FC, 0x2C85B8AA], - [0x0EB72DDC, 0x81C52CA2] - ]; - _states['SHA-512/224'] = [ - [0x8C3D37C8, 0x19544DA2], - [0x73E19966, 0x89DCD4D6], - [0x1DFAB7AE, 0x32FF9C82], - [0x679DD514, 0x582F9FCF], - [0x0F6D2B69, 0x7BD44DA8], - [0x77E36F73, 0x04C48942], - [0x3F9D85A8, 0x6A1D36C8], - [0x1112E6AD, 0x91D692A1] - ]; - - // now initialized - _initialized = true; -} - -/** - * Updates a SHA-512 state with the given byte buffer. - * - * @param s the SHA-512 state to update. - * @param w the array to use to store words. - * @param bytes the byte buffer to update with. - */ -function _update(s, w, bytes) { - // consume 512 bit (128 byte) chunks - var t1_hi, t1_lo; - var t2_hi, t2_lo; - var s0_hi, s0_lo; - var s1_hi, s1_lo; - var ch_hi, ch_lo; - var maj_hi, maj_lo; - var a_hi, a_lo; - var b_hi, b_lo; - var c_hi, c_lo; - var d_hi, d_lo; - var e_hi, e_lo; - var f_hi, f_lo; - var g_hi, g_lo; - var h_hi, h_lo; - var i, hi, lo, w2, w7, w15, w16; - var len = bytes.length(); - while(len >= 128) { - // the w array will be populated with sixteen 64-bit big-endian words - // and then extended into 64 64-bit words according to SHA-512 - for(i = 0; i < 16; ++i) { - w[i][0] = bytes.getInt32() >>> 0; - w[i][1] = bytes.getInt32() >>> 0; - } - for(; i < 80; ++i) { - // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x) - w2 = w[i - 2]; - hi = w2[0]; - lo = w2[1]; - - // high bits - t1_hi = ( - ((hi >>> 19) | (lo << 13)) ^ // ROTR 19 - ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29) - (hi >>> 6)) >>> 0; // SHR 6 - // low bits - t1_lo = ( - ((hi << 13) | (lo >>> 19)) ^ // ROTR 19 - ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29) - ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6 - - // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x) - w15 = w[i - 15]; - hi = w15[0]; - lo = w15[1]; - - // high bits - t2_hi = ( - ((hi >>> 1) | (lo << 31)) ^ // ROTR 1 - ((hi >>> 8) | (lo << 24)) ^ // ROTR 8 - (hi >>> 7)) >>> 0; // SHR 7 - // low bits - t2_lo = ( - ((hi << 31) | (lo >>> 1)) ^ // ROTR 1 - ((hi << 24) | (lo >>> 8)) ^ // ROTR 8 - ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7 - - // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow) - w7 = w[i - 7]; - w16 = w[i - 16]; - lo = (t1_lo + w7[1] + t2_lo + w16[1]); - w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] + - ((lo / 0x100000000) >>> 0)) >>> 0; - w[i][1] = lo >>> 0; - } - - // initialize hash value for this chunk - a_hi = s[0][0]; - a_lo = s[0][1]; - b_hi = s[1][0]; - b_lo = s[1][1]; - c_hi = s[2][0]; - c_lo = s[2][1]; - d_hi = s[3][0]; - d_lo = s[3][1]; - e_hi = s[4][0]; - e_lo = s[4][1]; - f_hi = s[5][0]; - f_lo = s[5][1]; - g_hi = s[6][0]; - g_lo = s[6][1]; - h_hi = s[7][0]; - h_lo = s[7][1]; - - // round function - for(i = 0; i < 80; ++i) { - // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e) - s1_hi = ( - ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14 - ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18 - ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9) - s1_lo = ( - ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14 - ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18 - ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9) - - // Ch(e, f, g) (optimized the same way as SHA-1) - ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0; - ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0; - - // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a) - s0_hi = ( - ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28 - ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2) - ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7) - s0_lo = ( - ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28 - ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2) - ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7) - - // Maj(a, b, c) (optimized the same way as SHA-1) - maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0; - maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0; - - // main algorithm - // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow) - lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]); - t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + - ((lo / 0x100000000) >>> 0)) >>> 0; - t1_lo = lo >>> 0; - - // t2 = s0 + maj modulo 2^64 (carry lo overflow) - lo = s0_lo + maj_lo; - t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - t2_lo = lo >>> 0; - - h_hi = g_hi; - h_lo = g_lo; - - g_hi = f_hi; - g_lo = f_lo; - - f_hi = e_hi; - f_lo = e_lo; - - // e = (d + t1) modulo 2^64 (carry lo overflow) - lo = d_lo + t1_lo; - e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - e_lo = lo >>> 0; - - d_hi = c_hi; - d_lo = c_lo; - - c_hi = b_hi; - c_lo = b_lo; - - b_hi = a_hi; - b_lo = a_lo; - - // a = (t1 + t2) modulo 2^64 (carry lo overflow) - lo = t1_lo + t2_lo; - a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - a_lo = lo >>> 0; - } - - // update hash state (additional modulo 2^64) - lo = s[0][1] + a_lo; - s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[0][1] = lo >>> 0; - - lo = s[1][1] + b_lo; - s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[1][1] = lo >>> 0; - - lo = s[2][1] + c_lo; - s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[2][1] = lo >>> 0; - - lo = s[3][1] + d_lo; - s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[3][1] = lo >>> 0; - - lo = s[4][1] + e_lo; - s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[4][1] = lo >>> 0; - - lo = s[5][1] + f_lo; - s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[5][1] = lo >>> 0; - - lo = s[6][1] + g_lo; - s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[6][1] = lo >>> 0; - - lo = s[7][1] + h_lo; - s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0; - s[7][1] = lo >>> 0; - - len -= 128; - } -} - -var asn1Validator$1 = {}; - -/** - * Copyright (c) 2019 Digital Bazaar, Inc. - */ - -var forge$7 = forge$F; - -var asn1$1 = forge$7.asn1; - -asn1Validator$1.privateKeyValidator = { - // PrivateKeyInfo - name: 'PrivateKeyInfo', - tagClass: asn1$1.Class.UNIVERSAL, - type: asn1$1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: 'PrivateKeyInfo.version', - tagClass: asn1$1.Class.UNIVERSAL, - type: asn1$1.Type.INTEGER, - constructed: false, - capture: 'privateKeyVersion' - }, { - // privateKeyAlgorithm - name: 'PrivateKeyInfo.privateKeyAlgorithm', - tagClass: asn1$1.Class.UNIVERSAL, - type: asn1$1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1$1.Class.UNIVERSAL, - type: asn1$1.Type.OID, - constructed: false, - capture: 'privateKeyOid' - }] - }, { - // PrivateKey - name: 'PrivateKeyInfo', - tagClass: asn1$1.Class.UNIVERSAL, - type: asn1$1.Type.OCTETSTRING, - constructed: false, - capture: 'privateKey' - }] -}; - -asn1Validator$1.publicKeyValidator = { - name: 'SubjectPublicKeyInfo', - tagClass: asn1$1.Class.UNIVERSAL, - type: asn1$1.Type.SEQUENCE, - constructed: true, - captureAsn1: 'subjectPublicKeyInfo', - value: [{ - name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', - tagClass: asn1$1.Class.UNIVERSAL, - type: asn1$1.Type.SEQUENCE, - constructed: true, - value: [{ - name: 'AlgorithmIdentifier.algorithm', - tagClass: asn1$1.Class.UNIVERSAL, - type: asn1$1.Type.OID, - constructed: false, - capture: 'publicKeyOid' - }] - }, - // capture group for ed25519PublicKey - { - tagClass: asn1$1.Class.UNIVERSAL, - type: asn1$1.Type.BITSTRING, - constructed: false, - composed: true, - captureBitStringValue: 'ed25519PublicKey' - } - // FIXME: this is capture group for rsaPublicKey, use it in this API or - // discard? - /* { - // subjectPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'rsaPublicKey' - }] - } */ - ] -}; - -/** - * JavaScript implementation of Ed25519. - * - * Copyright (c) 2017-2019 Digital Bazaar, Inc. - * - * This implementation is based on the most excellent TweetNaCl which is - * in the public domain. Many thanks to its contributors: - * - * https://github.com/dchest/tweetnacl-js - */ - -var forge$6 = forge$F; - - - - -var asn1Validator = asn1Validator$1; -var publicKeyValidator = asn1Validator.publicKeyValidator; -var privateKeyValidator = asn1Validator.privateKeyValidator; - -var ByteBuffer = forge$6.util.ByteBuffer; -var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer; - -/* - * Ed25519 algorithms, see RFC 8032: - * https://tools.ietf.org/html/rfc8032 - */ -forge$6.pki = forge$6.pki || {}; -forge$6.pki.ed25519 = forge$6.ed25519 = forge$6.ed25519 || {}; -var ed25519 = forge$6.ed25519; - -ed25519.constants = {}; -ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; -ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; -ed25519.constants.SEED_BYTE_LENGTH = 32; -ed25519.constants.SIGN_BYTE_LENGTH = 64; -ed25519.constants.HASH_BYTE_LENGTH = 64; - -ed25519.generateKeyPair = function(options) { - options = options || {}; - var seed = options.seed; - if(seed === undefined) { - // generate seed - seed = forge$6.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); - } else if(typeof seed === 'string') { - if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { - throw new TypeError( - '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + - ' bytes in length.'); - } - } else if(!(seed instanceof Uint8Array)) { - throw new TypeError( - '"seed" must be a node.js Buffer, Uint8Array, or a binary string.'); - } - - seed = messageToNativeBuffer({message: seed, encoding: 'binary'}); - - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - for(var i = 0; i < 32; ++i) { - sk[i] = seed[i]; - } - crypto_sign_keypair(pk, sk); - return {publicKey: pk, privateKey: sk}; -}; - -/** - * Converts a private key from a RFC8410 ASN.1 encoding. - * - * @param obj - The asn1 representation of a private key. - * - * @returns {Object} keyInfo - The key information. - * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes. - */ -ed25519.privateKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - var valid = forge$6.asn1.validate(obj, privateKeyValidator, capture, errors); - if(!valid) { - var error = new Error('Invalid Key.'); - error.errors = errors; - throw error; - } - var oid = forge$6.asn1.derToOid(capture.privateKeyOid); - var ed25519Oid = forge$6.oids.EdDSA25519; - if(oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + - ed25519Oid + '".'); - } - var privateKey = capture.privateKey; - // manually extract the private key bytes from nested octet string, see FIXME: - // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542 - var privateKeyBytes = messageToNativeBuffer({ - message: forge$6.asn1.fromDer(privateKey).value, - encoding: 'binary' - }); - // TODO: RFC8410 specifies a format for encoding the public key bytes along - // with the private key bytes. `publicKeyBytes` can be returned in the - // future. https://tools.ietf.org/html/rfc8410#section-10.3 - return {privateKeyBytes: privateKeyBytes}; -}; - -/** - * Converts a public key from a RFC8410 ASN.1 encoding. - * - * @param obj - The asn1 representation of a public key. - * - * @return {Buffer|Uint8Array} - 32 public key bytes. - */ -ed25519.publicKeyFromAsn1 = function(obj) { - // get SubjectPublicKeyInfo - var capture = {}; - var errors = []; - var valid = forge$6.asn1.validate(obj, publicKeyValidator, capture, errors); - if(!valid) { - var error = new Error('Invalid Key.'); - error.errors = errors; - throw error; - } - var oid = forge$6.asn1.derToOid(capture.publicKeyOid); - var ed25519Oid = forge$6.oids.EdDSA25519; - if(oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + - ed25519Oid + '".'); - } - var publicKeyBytes = capture.ed25519PublicKey; - if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new Error('Key length is invalid.'); - } - return messageToNativeBuffer({ - message: publicKeyBytes, - encoding: 'binary' - }); -}; - -ed25519.publicKeyFromPrivateKey = function(options) { - options = options || {}; - var privateKey = messageToNativeBuffer({ - message: options.privateKey, encoding: 'binary' - }); - if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + - ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - } - - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - for(var i = 0; i < pk.length; ++i) { - pk[i] = privateKey[32 + i]; - } - return pk; -}; - -ed25519.sign = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: 'binary' - }); - if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { - var keyPair = ed25519.generateKeyPair({seed: privateKey}); - privateKey = keyPair.privateKey; - } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + - ed25519.constants.SEED_BYTE_LENGTH + ' or ' + - ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - } - - var signedMsg = new NativeBuffer( - ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - crypto_sign(signedMsg, msg, msg.length, privateKey); - - var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); - for(var i = 0; i < sig.length; ++i) { - sig[i] = signedMsg[i]; - } - return sig; -}; - -ed25519.verify = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - if(options.signature === undefined) { - throw new TypeError( - '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' + - 'ByteBuffer, or a binary string.'); - } - var sig = messageToNativeBuffer({ - message: options.signature, - encoding: 'binary' - }); - if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { - throw new TypeError( - '"options.signature" must have a byte length of ' + - ed25519.constants.SIGN_BYTE_LENGTH); - } - var publicKey = messageToNativeBuffer({ - message: options.publicKey, - encoding: 'binary' - }); - if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.publicKey" must have a byte length of ' + - ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - } - - var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var i; - for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { - sm[i] = sig[i]; - } - for(i = 0; i < msg.length; ++i) { - sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; - } - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; - -function messageToNativeBuffer(options) { - var message = options.message; - if(message instanceof Uint8Array || message instanceof NativeBuffer) { - return message; - } - - var encoding = options.encoding; - if(message === undefined) { - if(options.md) { - // TODO: more rigorous validation that `md` is a MessageDigest - message = options.md.digest().getBytes(); - encoding = 'binary'; - } else { - throw new TypeError('"options.message" or "options.md" not specified.'); - } - } - - if(typeof message === 'string' && !encoding) { - throw new TypeError('"options.encoding" must be "binary" or "utf8".'); - } - - if(typeof message === 'string') { - if(typeof Buffer !== 'undefined') { - return Buffer.from(message, encoding); - } - message = new ByteBuffer(message, encoding); - } else if(!(message instanceof ByteBuffer)) { - throw new TypeError( - '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' + - 'ByteBuffer, or a string with "options.encoding" specifying its ' + - 'encoding.'); - } - - // convert to native buffer - var buffer = new NativeBuffer(message.length()); - for(var i = 0; i < buffer.length; ++i) { - buffer[i] = message.at(i); - } - return buffer; -} - -var gf0 = gf(); -var gf1 = gf([1]); -var D = gf([ - 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, - 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]); -var D2 = gf([ - 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, - 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]); -var X = gf([ - 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, - 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]); -var Y = gf([ - 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, - 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]); -var L = new Float64Array([ - 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, - 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); -var I = gf([ - 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, - 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - -// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`, -// whichever is available, to improve performance -function sha512(msg, msgLen) { - // Note: `out` and `msg` are NativeBuffer - var md = forge$6.md.sha512.create(); - var buffer = new ByteBuffer(msg); - md.update(buffer.getBytes(msgLen), 'binary'); - var hash = md.digest().getBytes(); - if(typeof Buffer !== 'undefined') { - return Buffer.from(hash, 'binary'); - } - var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); - for(var i = 0; i < 64; ++i) { - out[i] = hash.charCodeAt(i); - } - return out; -} - -function crypto_sign_keypair(pk, sk) { - var p = [gf(), gf(), gf(), gf()]; - var i; - - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for(i = 0; i < 32; ++i) { - sk[i + 32] = pk[i]; - } - return 0; -} - -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for(i = 0; i < n; ++i) { - sm[64 + i] = m[i]; - } - for(i = 0; i < 32; ++i) { - sm[32 + i] = d[32 + i]; - } - - var r = sha512(sm.subarray(32), n + 32); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for(i = 32; i < 64; ++i) { - sm[i] = sk[i]; - } - var h = sha512(sm, n + 64); - reduce(h); - - for(i = 32; i < 64; ++i) { - x[i] = 0; - } - for(i = 0; i < 32; ++i) { - x[i] = r[i]; - } - for(i = 0; i < 32; ++i) { - for(j = 0; j < 32; j++) { - x[i + j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new NativeBuffer(32); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - mlen = -1; - if(n < 64) { - return -1; - } - - if(unpackneg(q, pk)) { - return -1; - } - - for(i = 0; i < n; ++i) { - m[i] = sm[i]; - } - for(i = 0; i < 32; ++i) { - m[i + 32] = pk[i]; - } - var h = sha512(m, n); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if(crypto_verify_32(sm, 0, t, 0)) { - for(i = 0; i < n; ++i) { - m[i] = 0; - } - return -1; - } - - for(i = 0; i < n; ++i) { - m[i] = sm[i + 64]; - } - mlen = n; - return mlen; -} - -function modL(r, x) { - var carry, i, j, k; - for(i = 63; i >= 32; --i) { - carry = 0; - for(j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for(j = 0; j < 32; ++j) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for(j = 0; j < 32; ++j) { - x[j] -= carry * L[j]; - } - for(i = 0; i < 32; ++i) { - x[i + 1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64); - for(var i = 0; i < 64; ++i) { - x[i] = r[i]; - r[i] = 0; - } - modL(r, x); -} - -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} - -function cswap(p, q, b) { - for(var i = 0; i < 4; ++i) { - sel25519(p[i], q[i], b); - } -} - -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for(i = 0; i < 16; ++i) { - t[i] = n[i]; - } - car25519(t); - car25519(t); - car25519(t); - for(j = 0; j < 2; ++j) { - m[0] = t[0] - 0xffed; - for(i = 1; i < 15; ++i) { - m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); - b = (m[15] >> 16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1 - b); - } - for (i = 0; i < 16; i++) { - o[2 * i] = t[i] & 0xff; - o[2 * i + 1] = t[i] >> 8; - } -} - -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if(neq25519(chk, num)) { - M(r[0], r[0], I); - } - - S(chk, r[0]); - M(chk, chk, den); - if(neq25519(chk, num)) { - return -1; - } - - if(par25519(r[0]) === (p[31] >> 7)) { - Z(r[0], gf0, r[0]); - } - - M(r[3], r[0], r[1]); - return 0; -} - -function unpack25519(o, n) { - var i; - for(i = 0; i < 16; ++i) { - o[i] = n[2 * i] + (n[2 * i + 1] << 8); - } - o[15] &= 0x7fff; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for(a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for(a = 250; a >= 0; --a) { - S(c, c); - if(a !== 1) { - M(c, c, i); - } - } - for(a = 0; a < 16; ++a) { - o[a] = c[a]; - } -} - -function neq25519(a, b) { - var c = new NativeBuffer(32); - var d = new NativeBuffer(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} - -function crypto_verify_32(x, xi, y, yi) { - return vn(x, xi, y, yi, 32); -} - -function vn(x, xi, y, yi, n) { - var i, d = 0; - for(i = 0; i < n; ++i) { - d |= x[xi + i] ^ y[yi + i]; - } - return (1 & ((d - 1) >>> 8)) - 1; -} - -function par25519(a) { - var d = new NativeBuffer(32); - pack25519(d, a); - return d[0] & 1; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for(i = 255; i >= 0; --i) { - b = (s[(i / 8)|0] >> (i & 7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} - -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} - -function set25519(r, a) { - var i; - for(i = 0; i < 16; i++) { - r[i] = a[i] | 0; - } -} - -function inv25519(o, i) { - var c = gf(); - var a; - for(a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for(a = 253; a >= 0; --a) { - S(c, c); - if(a !== 2 && a !== 4) { - M(c, c, i); - } - } - for(a = 0; a < 16; ++a) { - o[a] = c[a]; - } -} - -function car25519(o) { - var i, v, c = 1; - for(i = 0; i < 16; ++i) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c - 1 + 37 * (c - 1); -} - -function sel25519(p, q, b) { - var t, c = ~(b - 1); - for(var i = 0; i < 16; ++i) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function gf(init) { - var i, r = new Float64Array(16); - if(init) { - for(i = 0; i < init.length; ++i) { - r[i] = init[i]; - } - } - return r; -} - -function A(o, a, b) { - for(var i = 0; i < 16; ++i) { - o[i] = a[i] + b[i]; - } -} - -function Z(o, a, b) { - for(var i = 0; i < 16; ++i) { - o[i] = a[i] - b[i]; - } -} - -function S(o, a) { - M(o, a, a); -} - -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; - - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is - - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} - -/** - * Javascript implementation of RSA-KEM. - * - * @author Lautaro Cozzani Rodriguez - * @author Dave Longley - * - * Copyright (c) 2014 Lautaro Cozzani - * Copyright (c) 2014 Digital Bazaar, Inc. - */ - -var forge$5 = forge$F; - - - - -forge$5.kem = forge$5.kem || {}; - -var BigInteger = forge$5.jsbn.BigInteger; - -/** - * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2. - */ -forge$5.kem.rsa = {}; - -/** - * Creates an RSA KEM API object for generating a secret asymmetric key. - * - * The symmetric key may be generated via a call to 'encrypt', which will - * produce a ciphertext to be transmitted to the recipient and a key to be - * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which - * will produce the same secret key for the recipient to use to decrypt a - * message that was encrypted with the secret key. - * - * @param kdf the KDF API to use (eg: new forge.kem.kdf1()). - * @param options the options to use. - * [prng] a custom crypto-secure pseudo-random number generator to use, - * that must define "getBytesSync". - */ -forge$5.kem.rsa.create = function(kdf, options) { - options = options || {}; - var prng = options.prng || forge$5.random; - - var kem = {}; - - /** - * Generates a secret key and its encapsulation. - * - * @param publicKey the RSA public key to encrypt with. - * @param keyLength the length, in bytes, of the secret key to generate. - * - * @return an object with: - * encapsulation: the ciphertext for generating the secret key, as a - * binary-encoded string of bytes. - * key: the secret key to use for encrypting a message. - */ - kem.encrypt = function(publicKey, keyLength) { - // generate a random r where 1 < r < n - var byteLength = Math.ceil(publicKey.n.bitLength() / 8); - var r; - do { - r = new BigInteger( - forge$5.util.bytesToHex(prng.getBytesSync(byteLength)), - 16).mod(publicKey.n); - } while(r.compareTo(BigInteger.ONE) <= 0); - - // prepend r with zeros - r = forge$5.util.hexToBytes(r.toString(16)); - var zeros = byteLength - r.length; - if(zeros > 0) { - r = forge$5.util.fillString(String.fromCharCode(0), zeros) + r; - } - - // encrypt the random - var encapsulation = publicKey.encrypt(r, 'NONE'); - - // generate the secret key - var key = kdf.generate(r, keyLength); - - return {encapsulation: encapsulation, key: key}; - }; - - /** - * Decrypts an encapsulated secret key. - * - * @param privateKey the RSA private key to decrypt with. - * @param encapsulation the ciphertext for generating the secret key, as - * a binary-encoded string of bytes. - * @param keyLength the length, in bytes, of the secret key to generate. - * - * @return the secret key as a binary-encoded string of bytes. - */ - kem.decrypt = function(privateKey, encapsulation, keyLength) { - // decrypt the encapsulation and generate the secret key - var r = privateKey.decrypt(encapsulation, 'NONE'); - return kdf.generate(r, keyLength); - }; - - return kem; -}; - -// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API? - -/** - * Creates a key derivation API object that implements KDF1 per ISO 18033-2. - * - * @param md the hash API to use. - * @param [digestLength] an optional digest length that must be positive and - * less than or equal to md.digestLength. - * - * @return a KDF1 API object. - */ -forge$5.kem.kdf1 = function(md, digestLength) { - _createKDF(this, md, 0, digestLength || md.digestLength); -}; - -/** - * Creates a key derivation API object that implements KDF2 per ISO 18033-2. - * - * @param md the hash API to use. - * @param [digestLength] an optional digest length that must be positive and - * less than or equal to md.digestLength. - * - * @return a KDF2 API object. - */ -forge$5.kem.kdf2 = function(md, digestLength) { - _createKDF(this, md, 1, digestLength || md.digestLength); -}; - -/** - * Creates a KDF1 or KDF2 API object. - * - * @param md the hash API to use. - * @param counterStart the starting index for the counter. - * @param digestLength the digest length to use. - * - * @return the KDF API object. - */ -function _createKDF(kdf, md, counterStart, digestLength) { - /** - * Generate a key of the specified length. - * - * @param x the binary-encoded byte string to generate a key from. - * @param length the number of bytes to generate (the size of the key). - * - * @return the key as a binary-encoded string. - */ - kdf.generate = function(x, length) { - var key = new forge$5.util.ByteBuffer(); - - // run counter from counterStart to ceil(length / Hash.len) - var k = Math.ceil(length / digestLength) + counterStart; - - var c = new forge$5.util.ByteBuffer(); - for(var i = counterStart; i < k; ++i) { - // I2OSP(i, 4): convert counter to an octet string of 4 octets - c.putInt32(i); - - // digest 'x' and the counter and add the result to the key - md.start(); - md.update(x + c.getBytes()); - var hash = md.digest(); - key.putBytes(hash.getBytes(digestLength)); - } - - // truncate to the correct key length - key.truncate(key.length() - length); - return key.getBytes(); - }; -} - -/** - * Cross-browser support for logging in a web application. - * - * @author David I. Lehn - * - * Copyright (c) 2008-2013 Digital Bazaar, Inc. - */ - -var forge$4 = forge$F; - - -/* LOG API */ -forge$4.log = forge$4.log || {}; - -/** - * Application logging system. - * - * Each logger level available as it's own function of the form: - * forge.log.level(category, args...) - * The category is an arbitrary string, and the args are the same as - * Firebug's console.log API. By default the call will be output as: - * 'LEVEL [category] , args[1], ...' - * This enables proper % formatting via the first argument. - * Each category is enabled by default but can be enabled or disabled with - * the setCategoryEnabled() function. - */ -// list of known levels -forge$4.log.levels = [ - 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max']; -// info on the levels indexed by name: -// index: level index -// name: uppercased display name -var sLevelInfo = {}; -// list of loggers -var sLoggers = []; -/** - * Standard console logger. If no console support is enabled this will - * remain null. Check before using. - */ -var sConsoleLogger = null; - -// logger flags -/** - * Lock the level at the current value. Used in cases where user config may - * set the level such that only critical messages are seen but more verbose - * messages are needed for debugging or other purposes. - */ -forge$4.log.LEVEL_LOCKED = (1 << 1); -/** - * Always call log function. By default, the logging system will check the - * message level against logger.level before calling the log function. This - * flag allows the function to do its own check. - */ -forge$4.log.NO_LEVEL_CHECK = (1 << 2); -/** - * Perform message interpolation with the passed arguments. "%" style - * fields in log messages will be replaced by arguments as needed. Some - * loggers, such as Firebug, may do this automatically. The original log - * message will be available as 'message' and the interpolated version will - * be available as 'fullMessage'. - */ -forge$4.log.INTERPOLATE = (1 << 3); - -// setup each log level -for(var i = 0; i < forge$4.log.levels.length; ++i) { - var level = forge$4.log.levels[i]; - sLevelInfo[level] = { - index: i, - name: level.toUpperCase() - }; -} - -/** - * Message logger. Will dispatch a message to registered loggers as needed. - * - * @param message message object - */ -forge$4.log.logMessage = function(message) { - var messageLevelIndex = sLevelInfo[message.level].index; - for(var i = 0; i < sLoggers.length; ++i) { - var logger = sLoggers[i]; - if(logger.flags & forge$4.log.NO_LEVEL_CHECK) { - logger.f(message); - } else { - // get logger level - var loggerLevelIndex = sLevelInfo[logger.level].index; - // check level - if(messageLevelIndex <= loggerLevelIndex) { - // message critical enough, call logger - logger.f(logger, message); - } - } - } -}; - -/** - * Sets the 'standard' key on a message object to: - * "LEVEL [category] " + message - * - * @param message a message log object - */ -forge$4.log.prepareStandard = function(message) { - if(!('standard' in message)) { - message.standard = - sLevelInfo[message.level].name + - //' ' + +message.timestamp + - ' [' + message.category + '] ' + - message.message; - } -}; - -/** - * Sets the 'full' key on a message object to the original message - * interpolated via % formatting with the message arguments. - * - * @param message a message log object. - */ -forge$4.log.prepareFull = function(message) { - if(!('full' in message)) { - // copy args and insert message at the front - var args = [message.message]; - args = args.concat([] || message['arguments']); - // format the message - message.full = forge$4.util.format.apply(this, args); - } -}; - -/** - * Applies both preparseStandard() and prepareFull() to a message object and - * store result in 'standardFull'. - * - * @param message a message log object. - */ -forge$4.log.prepareStandardFull = function(message) { - if(!('standardFull' in message)) { - // FIXME implement 'standardFull' logging - forge$4.log.prepareStandard(message); - message.standardFull = message.standard; - } -}; - -// create log level functions -{ - // levels for which we want functions - var levels = ['error', 'warning', 'info', 'debug', 'verbose']; - for(var i = 0; i < levels.length; ++i) { - // wrap in a function to ensure proper level var is passed - (function(level) { - // create function for this level - forge$4.log[level] = function(category, message/*, args...*/) { - // convert arguments to real array, remove category and message - var args = Array.prototype.slice.call(arguments).slice(2); - // create message object - // Note: interpolation and standard formatting is done lazily - var msg = { - timestamp: new Date(), - level: level, - category: category, - message: message, - 'arguments': args - /*standard*/ - /*full*/ - /*fullMessage*/ - }; - // process this message - forge$4.log.logMessage(msg); - }; - })(levels[i]); - } -} - -/** - * Creates a new logger with specified custom logging function. - * - * The logging function has a signature of: - * function(logger, message) - * logger: current logger - * message: object: - * level: level id - * category: category - * message: string message - * arguments: Array of extra arguments - * fullMessage: interpolated message and arguments if INTERPOLATE flag set - * - * @param logFunction a logging function which takes a log message object - * as a parameter. - * - * @return a logger object. - */ -forge$4.log.makeLogger = function(logFunction) { - var logger = { - flags: 0, - f: logFunction - }; - forge$4.log.setLevel(logger, 'none'); - return logger; -}; - -/** - * Sets the current log level on a logger. - * - * @param logger the target logger. - * @param level the new maximum log level as a string. - * - * @return true if set, false if not. - */ -forge$4.log.setLevel = function(logger, level) { - var rval = false; - if(logger && !(logger.flags & forge$4.log.LEVEL_LOCKED)) { - for(var i = 0; i < forge$4.log.levels.length; ++i) { - var aValidLevel = forge$4.log.levels[i]; - if(level == aValidLevel) { - // set level - logger.level = level; - rval = true; - break; - } - } - } - - return rval; -}; - -/** - * Locks the log level at its current value. - * - * @param logger the target logger. - * @param lock boolean lock value, default to true. - */ -forge$4.log.lock = function(logger, lock) { - if(typeof lock === 'undefined' || lock) { - logger.flags |= forge$4.log.LEVEL_LOCKED; - } else { - logger.flags &= ~forge$4.log.LEVEL_LOCKED; - } -}; - -/** - * Adds a logger. - * - * @param logger the logger object. - */ -forge$4.log.addLogger = function(logger) { - sLoggers.push(logger); -}; - -// setup the console logger if possible, else create fake console.log -if(typeof(console) !== 'undefined' && 'log' in console) { - var logger; - if(console.error && console.warn && console.info && console.debug) { - // looks like Firebug-style logging is available - // level handlers map - var levelHandlers = { - error: console.error, - warning: console.warn, - info: console.info, - debug: console.debug, - verbose: console.debug - }; - var f = function(logger, message) { - forge$4.log.prepareStandard(message); - var handler = levelHandlers[message.level]; - // prepend standard message and concat args - var args = [message.standard]; - args = args.concat(message['arguments'].slice()); - // apply to low-level console function - handler.apply(console, args); - }; - logger = forge$4.log.makeLogger(f); - } else { - // only appear to have basic console.log - var f = function(logger, message) { - forge$4.log.prepareStandardFull(message); - console.log(message.standardFull); - }; - logger = forge$4.log.makeLogger(f); - } - forge$4.log.setLevel(logger, 'debug'); - forge$4.log.addLogger(logger); - sConsoleLogger = logger; -} else { - // define fake console.log to avoid potential script errors on - // browsers that do not have console logging - console = { - log: function() {} - }; -} - -/* - * Check for logging control query vars. - * - * console.level= - * Set's the console log level by name. Useful to override defaults and - * allow more verbose logging before a user config is loaded. - * - * console.lock= - * Lock the console log level at whatever level it is set at. This is run - * after console.level is processed. Useful to force a level of verbosity - * that could otherwise be limited by a user config. - */ -if(sConsoleLogger !== null) { - var query = forge$4.util.getQueryVariables(); - if('console.level' in query) { - // set with last value - forge$4.log.setLevel( - sConsoleLogger, query['console.level'].slice(-1)[0]); - } - if('console.lock' in query) { - // set with last value - var lock = query['console.lock'].slice(-1)[0]; - if(lock == 'true') { - forge$4.log.lock(sConsoleLogger); - } - } -} - -// provide public access to console logger -forge$4.log.consoleLogger = sConsoleLogger; - -/** - * Javascript implementation of PKCS#7 v1.5. - * - * @author Stefan Siegl - * @author Dave Longley - * - * Copyright (c) 2012 Stefan Siegl - * Copyright (c) 2012-2015 Digital Bazaar, Inc. - * - * Currently this implementation only supports ContentType of EnvelopedData, - * EncryptedData, or SignedData at the root level. The top level elements may - * contain only a ContentInfo of ContentType Data, i.e. plain data. Further - * nesting is not (yet) supported. - * - * The Forge validators for PKCS #7's ASN.1 structures are available from - * a separate file pkcs7asn1.js, since those are referenced from other - * PKCS standards like PKCS #12. - */ - -var forge$3 = forge$F; - - - - - - - - - - -// shortcut for ASN.1 API -var asn1 = forge$3.asn1; - -// shortcut for PKCS#7 API -var p7 = forge$3.pkcs7 = forge$3.pkcs7 || {}; - -/** - * Converts a PKCS#7 message from PEM format. - * - * @param pem the PEM-formatted PKCS#7 message. - * - * @return the PKCS#7 message. - */ -p7.messageFromPem = function(pem) { - var msg = forge$3.pem.decode(pem)[0]; - - if(msg.type !== 'PKCS7') { - var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' + - 'header type is not "PKCS#7".'); - error.headerType = msg.type; - throw error; - } - if(msg.procType && msg.procType.type === 'ENCRYPTED') { - throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.'); - } - - // convert DER to ASN.1 object - var obj = asn1.fromDer(msg.body); - - return p7.messageFromAsn1(obj); -}; - -/** - * Converts a PKCS#7 message to PEM format. - * - * @param msg The PKCS#7 message object - * @param maxline The maximum characters per line, defaults to 64. - * - * @return The PEM-formatted PKCS#7 message. - */ -p7.messageToPem = function(msg, maxline) { - // convert to ASN.1, then DER, then PEM-encode - var pemObj = { - type: 'PKCS7', - body: asn1.toDer(msg.toAsn1()).getBytes() - }; - return forge$3.pem.encode(pemObj, {maxline: maxline}); -}; - -/** - * Converts a PKCS#7 message from an ASN.1 object. - * - * @param obj the ASN.1 representation of a ContentInfo. - * - * @return the PKCS#7 message. - */ -p7.messageFromAsn1 = function(obj) { - // validate root level ContentInfo and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#7 message. ' + - 'ASN.1 object is not an PKCS#7 ContentInfo.'); - error.errors = errors; - throw error; - } - - var contentType = asn1.derToOid(capture.contentType); - var msg; - - switch(contentType) { - case forge$3.pki.oids.envelopedData: - msg = p7.createEnvelopedData(); - break; - - case forge$3.pki.oids.encryptedData: - msg = p7.createEncryptedData(); - break; - - case forge$3.pki.oids.signedData: - msg = p7.createSignedData(); - break; - - default: - throw new Error('Cannot read PKCS#7 message. ContentType with OID ' + - contentType + ' is not (yet) supported.'); - } - - msg.fromAsn1(capture.content.value[0]); - return msg; -}; - -p7.createSignedData = function() { - var msg = null; - msg = { - type: forge$3.pki.oids.signedData, - version: 1, - certificates: [], - crls: [], - // TODO: add json-formatted signer stuff here? - signers: [], - // populated during sign() - digestAlgorithmIdentifiers: [], - contentInfo: null, - signerInfos: [], - - fromAsn1: function(obj) { - // validate SignedData content block and capture data. - _fromAsn1(msg, obj, p7.asn1.signedDataValidator); - msg.certificates = []; - msg.crls = []; - msg.digestAlgorithmIdentifiers = []; - msg.contentInfo = null; - msg.signerInfos = []; - - if(msg.rawCapture.certificates) { - var certs = msg.rawCapture.certificates.value; - for(var i = 0; i < certs.length; ++i) { - msg.certificates.push(forge$3.pki.certificateFromAsn1(certs[i])); - } - } - - // TODO: parse crls - }, - - toAsn1: function() { - // degenerate case with no content - if(!msg.contentInfo) { - msg.sign(); - } - - var certs = []; - for(var i = 0; i < msg.certificates.length; ++i) { - certs.push(forge$3.pki.certificateToAsn1(msg.certificates[i])); - } - - var crls = []; - // TODO: implement CRLs - - // [0] SignedData - var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(msg.version).getBytes()), - // DigestAlgorithmIdentifiers - asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SET, true, - msg.digestAlgorithmIdentifiers), - // ContentInfo - msg.contentInfo - ]) - ]); - if(certs.length > 0) { - // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs)); - } - if(crls.length > 0) { - // [1] IMPLICIT CertificateRevocationLists OPTIONAL - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls)); - } - // SignerInfos - signedData.value[0].value.push( - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, - msg.signerInfos)); - - // ContentInfo - return asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(msg.type).getBytes()), - // [0] SignedData - signedData - ]); - }, - - /** - * Add (another) entity to list of signers. - * - * Note: If authenticatedAttributes are provided, then, per RFC 2315, - * they must include at least two attributes: content type and - * message digest. The message digest attribute value will be - * auto-calculated during signing and will be ignored if provided. - * - * Here's an example of providing these two attributes: - * - * forge.pkcs7.createSignedData(); - * p7.addSigner({ - * issuer: cert.issuer.attributes, - * serialNumber: cert.serialNumber, - * key: privateKey, - * digestAlgorithm: forge.pki.oids.sha1, - * authenticatedAttributes: [{ - * type: forge.pki.oids.contentType, - * value: forge.pki.oids.data - * }, { - * type: forge.pki.oids.messageDigest - * }] - * }); - * - * TODO: Support [subjectKeyIdentifier] as signer's ID. - * - * @param signer the signer information: - * key the signer's private key. - * [certificate] a certificate containing the public key - * associated with the signer's private key; use this option as - * an alternative to specifying signer.issuer and - * signer.serialNumber. - * [issuer] the issuer attributes (eg: cert.issuer.attributes). - * [serialNumber] the signer's certificate's serial number in - * hexadecimal (eg: cert.serialNumber). - * [digestAlgorithm] the message digest OID, as a string, to use - * (eg: forge.pki.oids.sha1). - * [authenticatedAttributes] an optional array of attributes - * to also sign along with the content. - */ - addSigner: function(signer) { - var issuer = signer.issuer; - var serialNumber = signer.serialNumber; - if(signer.certificate) { - var cert = signer.certificate; - if(typeof cert === 'string') { - cert = forge$3.pki.certificateFromPem(cert); - } - issuer = cert.issuer.attributes; - serialNumber = cert.serialNumber; - } - var key = signer.key; - if(!key) { - throw new Error( - 'Could not add PKCS#7 signer; no private key specified.'); - } - if(typeof key === 'string') { - key = forge$3.pki.privateKeyFromPem(key); - } - - // ensure OID known for digest algorithm - var digestAlgorithm = signer.digestAlgorithm || forge$3.pki.oids.sha1; - switch(digestAlgorithm) { - case forge$3.pki.oids.sha1: - case forge$3.pki.oids.sha256: - case forge$3.pki.oids.sha384: - case forge$3.pki.oids.sha512: - case forge$3.pki.oids.md5: - break; - default: - throw new Error( - 'Could not add PKCS#7 signer; unknown message digest algorithm: ' + - digestAlgorithm); - } - - // if authenticatedAttributes is present, then the attributes - // must contain at least PKCS #9 content-type and message-digest - var authenticatedAttributes = signer.authenticatedAttributes || []; - if(authenticatedAttributes.length > 0) { - var contentType = false; - var messageDigest = false; - for(var i = 0; i < authenticatedAttributes.length; ++i) { - var attr = authenticatedAttributes[i]; - if(!contentType && attr.type === forge$3.pki.oids.contentType) { - contentType = true; - if(messageDigest) { - break; - } - continue; - } - if(!messageDigest && attr.type === forge$3.pki.oids.messageDigest) { - messageDigest = true; - if(contentType) { - break; - } - continue; - } - } - - if(!contentType || !messageDigest) { - throw new Error('Invalid signer.authenticatedAttributes. If ' + - 'signer.authenticatedAttributes is specified, then it must ' + - 'contain at least two attributes, PKCS #9 content-type and ' + - 'PKCS #9 message-digest.'); - } - } - - msg.signers.push({ - key: key, - version: 1, - issuer: issuer, - serialNumber: serialNumber, - digestAlgorithm: digestAlgorithm, - signatureAlgorithm: forge$3.pki.oids.rsaEncryption, - signature: null, - authenticatedAttributes: authenticatedAttributes, - unauthenticatedAttributes: [] - }); - }, - - /** - * Signs the content. - * @param options Options to apply when signing: - * [detached] boolean. If signing should be done in detached mode. Defaults to false. - */ - sign: function(options) { - options = options || {}; - // auto-generate content info - if(typeof msg.content !== 'object' || msg.contentInfo === null) { - // use Data ContentInfo - msg.contentInfo = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(forge$3.pki.oids.data).getBytes()) - ]); - - // add actual content, if present - if('content' in msg) { - var content; - if(msg.content instanceof forge$3.util.ByteBuffer) { - content = msg.content.bytes(); - } else if(typeof msg.content === 'string') { - content = forge$3.util.encodeUtf8(msg.content); - } - - if (options.detached) { - msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); - } else { - msg.contentInfo.value.push( - // [0] EXPLICIT content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - content) - ])); - } - } - } - - // no signers, return early (degenerate case for certificate container) - if(msg.signers.length === 0) { - return; - } - - // generate digest algorithm identifiers - var mds = addDigestAlgorithmIds(); - - // generate signerInfos - addSignerInfos(mds); - }, - - verify: function() { - throw new Error('PKCS#7 signature verification not yet implemented.'); - }, - - /** - * Add a certificate. - * - * @param cert the certificate to add. - */ - addCertificate: function(cert) { - // convert from PEM - if(typeof cert === 'string') { - cert = forge$3.pki.certificateFromPem(cert); - } - msg.certificates.push(cert); - }, - - /** - * Add a certificate revokation list. - * - * @param crl the certificate revokation list to add. - */ - addCertificateRevokationList: function(crl) { - throw new Error('PKCS#7 CRL support not yet implemented.'); - } - }; - return msg; - - function addDigestAlgorithmIds() { - var mds = {}; - - for(var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - var oid = signer.digestAlgorithm; - if(!(oid in mds)) { - // content digest - mds[oid] = forge$3.md[forge$3.pki.oids[oid]].create(); - } - if(signer.authenticatedAttributes.length === 0) { - // no custom attributes to digest; use content message digest - signer.md = mds[oid]; - } else { - // custom attributes to be digested; use own message digest - // TODO: optimize to just copy message digest state if that - // feature is ever supported with message digests - signer.md = forge$3.md[forge$3.pki.oids[oid]].create(); - } - } - - // add unique digest algorithm identifiers - msg.digestAlgorithmIdentifiers = []; - for(var oid in mds) { - msg.digestAlgorithmIdentifiers.push( - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(oid).getBytes()), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ])); - } - - return mds; - } - - function addSignerInfos(mds) { - var content; - - if (msg.detachedContent) { - // Signature has been made in detached mode. - content = msg.detachedContent; - } else { - // Note: ContentInfo is a SEQUENCE with 2 values, second value is - // the content field and is optional for a ContentInfo but required here - // since signers are present - // get ContentInfo content - content = msg.contentInfo.value[1]; - // skip [0] EXPLICIT content wrapper - content = content.value[0]; - } - - if(!content) { - throw new Error( - 'Could not sign PKCS#7 message; there is no content to sign.'); - } - - // get ContentInfo content type - var contentType = asn1.derToOid(msg.contentInfo.value[0].value); - - // serialize content - var bytes = asn1.toDer(content); - - // skip identifier and length per RFC 2315 9.3 - // skip identifier (1 byte) - bytes.getByte(); - // read and discard length bytes - asn1.getBerValueLength(bytes); - bytes = bytes.getBytes(); - - // digest content DER value bytes - for(var oid in mds) { - mds[oid].start().update(bytes); - } - - // sign content - var signingTime = new Date(); - for(var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - - if(signer.authenticatedAttributes.length === 0) { - // if ContentInfo content type is not "Data", then - // authenticatedAttributes must be present per RFC 2315 - if(contentType !== forge$3.pki.oids.data) { - throw new Error( - 'Invalid signer; authenticatedAttributes must be present ' + - 'when the ContentInfo content type is not PKCS#7 Data.'); - } - } else { - // process authenticated attributes - // [0] IMPLICIT - signer.authenticatedAttributesAsn1 = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, 0, true, []); - - // per RFC 2315, attributes are to be digested using a SET container - // not the above [0] IMPLICIT container - var attrsAsn1 = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.SET, true, []); - - for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { - var attr = signer.authenticatedAttributes[ai]; - if(attr.type === forge$3.pki.oids.messageDigest) { - // use content message digest as value - attr.value = mds[signer.digestAlgorithm].digest(); - } else if(attr.type === forge$3.pki.oids.signingTime) { - // auto-populate signing time if not already set - if(!attr.value) { - attr.value = signingTime; - } - } - - // convert to ASN.1 and push onto Attributes SET (for signing) and - // onto authenticatedAttributesAsn1 to complete SignedData ASN.1 - // TODO: optimize away duplication - attrsAsn1.value.push(_attributeToAsn1(attr)); - signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); - } - - // DER-serialize and digest SET OF attributes only - bytes = asn1.toDer(attrsAsn1).getBytes(); - signer.md.start().update(bytes); - } - - // sign digest - signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5'); - } - - // add signer info - msg.signerInfos = _signersToAsn1(msg.signers); - } -}; - -/** - * Creates an empty PKCS#7 message of type EncryptedData. - * - * @return the message. - */ -p7.createEncryptedData = function() { - var msg = null; - msg = { - type: forge$3.pki.oids.encryptedData, - version: 0, - encryptedContent: { - algorithm: forge$3.pki.oids['aes256-CBC'] - }, - - /** - * Reads an EncryptedData content block (in ASN.1 format) - * - * @param obj The ASN.1 representation of the EncryptedData content block - */ - fromAsn1: function(obj) { - // Validate EncryptedData content block and capture data. - _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); - }, - - /** - * Decrypt encrypted content - * - * @param key The (symmetric) key as a byte buffer - */ - decrypt: function(key) { - if(key !== undefined) { - msg.encryptedContent.key = key; - } - _decryptContent(msg); - } - }; - return msg; -}; - -/** - * Creates an empty PKCS#7 message of type EnvelopedData. - * - * @return the message. - */ -p7.createEnvelopedData = function() { - var msg = null; - msg = { - type: forge$3.pki.oids.envelopedData, - version: 0, - recipients: [], - encryptedContent: { - algorithm: forge$3.pki.oids['aes256-CBC'] - }, - - /** - * Reads an EnvelopedData content block (in ASN.1 format) - * - * @param obj the ASN.1 representation of the EnvelopedData content block. - */ - fromAsn1: function(obj) { - // validate EnvelopedData content block and capture data - var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); - msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); - }, - - toAsn1: function() { - // ContentInfo - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(msg.type).getBytes()), - // [0] EnvelopedData - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(msg.version).getBytes()), - // RecipientInfos - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, - _recipientsToAsn1(msg.recipients)), - // EncryptedContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, - _encryptedContentToAsn1(msg.encryptedContent)) - ]) - ]) - ]); - }, - - /** - * Find recipient by X.509 certificate's issuer. - * - * @param cert the certificate with the issuer to look for. - * - * @return the recipient object. - */ - findRecipient: function(cert) { - var sAttr = cert.issuer.attributes; - - for(var i = 0; i < msg.recipients.length; ++i) { - var r = msg.recipients[i]; - var rAttr = r.issuer; - - if(r.serialNumber !== cert.serialNumber) { - continue; - } - - if(rAttr.length !== sAttr.length) { - continue; - } - - var match = true; - for(var j = 0; j < sAttr.length; ++j) { - if(rAttr[j].type !== sAttr[j].type || - rAttr[j].value !== sAttr[j].value) { - match = false; - break; - } - } - - if(match) { - return r; - } - } - - return null; - }, - - /** - * Decrypt enveloped content - * - * @param recipient The recipient object related to the private key - * @param privKey The (RSA) private key object - */ - decrypt: function(recipient, privKey) { - if(msg.encryptedContent.key === undefined && recipient !== undefined && - privKey !== undefined) { - switch(recipient.encryptedContent.algorithm) { - case forge$3.pki.oids.rsaEncryption: - case forge$3.pki.oids.desCBC: - var key = privKey.decrypt(recipient.encryptedContent.content); - msg.encryptedContent.key = forge$3.util.createBuffer(key); - break; - - default: - throw new Error('Unsupported asymmetric cipher, ' + - 'OID ' + recipient.encryptedContent.algorithm); - } - } - - _decryptContent(msg); - }, - - /** - * Add (another) entity to list of recipients. - * - * @param cert The certificate of the entity to add. - */ - addRecipient: function(cert) { - msg.recipients.push({ - version: 0, - issuer: cert.issuer.attributes, - serialNumber: cert.serialNumber, - encryptedContent: { - // We simply assume rsaEncryption here, since forge.pki only - // supports RSA so far. If the PKI module supports other - // ciphers one day, we need to modify this one as well. - algorithm: forge$3.pki.oids.rsaEncryption, - key: cert.publicKey - } - }); - }, - - /** - * Encrypt enveloped content. - * - * This function supports two optional arguments, cipher and key, which - * can be used to influence symmetric encryption. Unless cipher is - * provided, the cipher specified in encryptedContent.algorithm is used - * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key - * is (re-)used. If that one's not set, a random key will be generated - * automatically. - * - * @param [key] The key to be used for symmetric encryption. - * @param [cipher] The OID of the symmetric cipher to use. - */ - encrypt: function(key, cipher) { - // Part 1: Symmetric encryption - if(msg.encryptedContent.content === undefined) { - cipher = cipher || msg.encryptedContent.algorithm; - key = key || msg.encryptedContent.key; - - var keyLen, ivLen, ciphFn; - switch(cipher) { - case forge$3.pki.oids['aes128-CBC']: - keyLen = 16; - ivLen = 16; - ciphFn = forge$3.aes.createEncryptionCipher; - break; - - case forge$3.pki.oids['aes192-CBC']: - keyLen = 24; - ivLen = 16; - ciphFn = forge$3.aes.createEncryptionCipher; - break; - - case forge$3.pki.oids['aes256-CBC']: - keyLen = 32; - ivLen = 16; - ciphFn = forge$3.aes.createEncryptionCipher; - break; - - case forge$3.pki.oids['des-EDE3-CBC']: - keyLen = 24; - ivLen = 8; - ciphFn = forge$3.des.createEncryptionCipher; - break; - - default: - throw new Error('Unsupported symmetric cipher, OID ' + cipher); - } - - if(key === undefined) { - key = forge$3.util.createBuffer(forge$3.random.getBytes(keyLen)); - } else if(key.length() != keyLen) { - throw new Error('Symmetric key has wrong length; ' + - 'got ' + key.length() + ' bytes, expected ' + keyLen + '.'); - } - - // Keep a copy of the key & IV in the object, so the caller can - // use it for whatever reason. - msg.encryptedContent.algorithm = cipher; - msg.encryptedContent.key = key; - msg.encryptedContent.parameter = forge$3.util.createBuffer( - forge$3.random.getBytes(ivLen)); - - var ciph = ciphFn(key); - ciph.start(msg.encryptedContent.parameter.copy()); - ciph.update(msg.content); - - // The finish function does PKCS#7 padding by default, therefore - // no action required by us. - if(!ciph.finish()) { - throw new Error('Symmetric encryption failed.'); - } - - msg.encryptedContent.content = ciph.output; - } - - // Part 2: asymmetric encryption for each recipient - for(var i = 0; i < msg.recipients.length; ++i) { - var recipient = msg.recipients[i]; - - // Nothing to do, encryption already done. - if(recipient.encryptedContent.content !== undefined) { - continue; - } - - switch(recipient.encryptedContent.algorithm) { - case forge$3.pki.oids.rsaEncryption: - recipient.encryptedContent.content = - recipient.encryptedContent.key.encrypt( - msg.encryptedContent.key.data); - break; - - default: - throw new Error('Unsupported asymmetric cipher, OID ' + - recipient.encryptedContent.algorithm); - } - } - } - }; - return msg; -}; - -/** - * Converts a single recipient from an ASN.1 object. - * - * @param obj the ASN.1 RecipientInfo. - * - * @return the recipient object. - */ -function _recipientFromAsn1(obj) { - // validate EnvelopedData content block and capture data - var capture = {}; - var errors = []; - if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { - var error = new Error('Cannot read PKCS#7 RecipientInfo. ' + - 'ASN.1 object is not an PKCS#7 RecipientInfo.'); - error.errors = errors; - throw error; - } - - return { - version: capture.version.charCodeAt(0), - issuer: forge$3.pki.RDNAttributesAsArray(capture.issuer), - serialNumber: forge$3.util.createBuffer(capture.serial).toHex(), - encryptedContent: { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: capture.encParameter.value, - content: capture.encKey - } - }; -} - -/** - * Converts a single recipient object to an ASN.1 object. - * - * @param obj the recipient object. - * - * @return the ASN.1 RecipientInfo. - */ -function _recipientToAsn1(obj) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(obj.version).getBytes()), - // IssuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Name - forge$3.pki.distinguishedNameToAsn1({attributes: obj.issuer}), - // Serial - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - forge$3.util.hexToBytes(obj.serialNumber)) - ]), - // KeyEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()), - // Parameter, force NULL, only RSA supported for now. - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]), - // EncryptedKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - obj.encryptedContent.content) - ]); -} - -/** - * Map a set of RecipientInfo ASN.1 objects to recipient objects. - * - * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF). - * - * @return an array of recipient objects. - */ -function _recipientsFromAsn1(infos) { - var ret = []; - for(var i = 0; i < infos.length; ++i) { - ret.push(_recipientFromAsn1(infos[i])); - } - return ret; -} - -/** - * Map an array of recipient objects to ASN.1 RecipientInfo objects. - * - * @param recipients an array of recipientInfo objects. - * - * @return an array of ASN.1 RecipientInfos. - */ -function _recipientsToAsn1(recipients) { - var ret = []; - for(var i = 0; i < recipients.length; ++i) { - ret.push(_recipientToAsn1(recipients[i])); - } - return ret; -} - -/** - * Converts a single signerInfo object to an ASN.1 object. - * - * @param obj the signerInfo object. - * - * @return the ASN.1 representation of a SignerInfo. - */ -function _signerToAsn1(obj) { - // SignerInfo - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - asn1.integerToDer(obj.version).getBytes()), - // issuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // name - forge$3.pki.distinguishedNameToAsn1({attributes: obj.issuer}), - // serial - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, - forge$3.util.hexToBytes(obj.serialNumber)) - ]), - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(obj.digestAlgorithm).getBytes()), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ]) - ]); - - // authenticatedAttributes (OPTIONAL) - if(obj.authenticatedAttributesAsn1) { - // add ASN.1 previously generated during signing - rval.value.push(obj.authenticatedAttributesAsn1); - } - - // digestEncryptionAlgorithm - rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(obj.signatureAlgorithm).getBytes()), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') - ])); - - // encryptedDigest - rval.value.push(asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature)); - - // unauthenticatedAttributes (OPTIONAL) - if(obj.unauthenticatedAttributes.length > 0) { - // [1] IMPLICIT - var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); - for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { - var attr = obj.unauthenticatedAttributes[i]; - attrsAsn1.values.push(_attributeToAsn1(attr)); - } - rval.value.push(attrsAsn1); - } - - return rval; -} - -/** - * Map an array of signer objects to ASN.1 objects. - * - * @param signers an array of signer objects. - * - * @return an array of ASN.1 SignerInfos. - */ -function _signersToAsn1(signers) { - var ret = []; - for(var i = 0; i < signers.length; ++i) { - ret.push(_signerToAsn1(signers[i])); - } - return ret; -} - -/** - * Convert an attribute object to an ASN.1 Attribute. - * - * @param attr the attribute object. - * - * @return the ASN.1 Attribute. - */ -function _attributeToAsn1(attr) { - var value; - - // TODO: generalize to support more attributes - if(attr.type === forge$3.pki.oids.contentType) { - value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(attr.value).getBytes()); - } else if(attr.type === forge$3.pki.oids.messageDigest) { - value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - attr.value.bytes()); - } else if(attr.type === forge$3.pki.oids.signingTime) { - /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049 - (inclusive) MUST be encoded as UTCTime. Any dates with year values - before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,] - UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST - include seconds (i.e., times are YYMMDDHHMMSSZ), even where the - number of seconds is zero. Midnight (GMT) must be represented as - "YYMMDD000000Z". */ - // TODO: make these module-level constants - var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); - var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); - var date = attr.value; - if(typeof date === 'string') { - // try to parse date - var timestamp = Date.parse(date); - if(!isNaN(timestamp)) { - date = new Date(timestamp); - } else if(date.length === 13) { - // YYMMDDHHMMSSZ (13 chars for UTCTime) - date = asn1.utcTimeToDate(date); - } else { - // assume generalized time - date = asn1.generalizedTimeToDate(date); - } - } - - if(date >= jan_1_1950 && date < jan_1_2050) { - value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, - asn1.dateToUtcTime(date)); - } else { - value = asn1.create( - asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, - asn1.dateToGeneralizedTime(date)); - } - } - - // TODO: expose as common API call - // create a RelativeDistinguishedName set - // each value in the set is an AttributeTypeAndValue first - // containing the type (an OID) and second the value - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(attr.type).getBytes()), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - value - ]) - ]); -} - -/** - * Map messages encrypted content to ASN.1 objects. - * - * @param ec The encryptedContent object of the message. - * - * @return ASN.1 representation of the encryptedContent object (SEQUENCE). - */ -function _encryptedContentToAsn1(ec) { - return [ - // ContentType, always Data for the moment - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(forge$3.pki.oids.data).getBytes()), - // ContentEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, - asn1.oidToDer(ec.algorithm).getBytes()), - // Parameters (IV) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - ec.parameter.getBytes()) - ]), - // [0] EncryptedContent - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, - ec.content.getBytes()) - ]) - ]; -} - -/** - * Reads the "common part" of an PKCS#7 content block (in ASN.1 format) - * - * This function reads the "common part" of the PKCS#7 content blocks - * EncryptedData and EnvelopedData, i.e. version number and symmetrically - * encrypted content block. - * - * The result of the ASN.1 validate and capture process is returned - * to allow the caller to extract further data, e.g. the list of recipients - * in case of a EnvelopedData object. - * - * @param msg the PKCS#7 object to read the data to. - * @param obj the ASN.1 representation of the content block. - * @param validator the ASN.1 structure validator object to use. - * - * @return the value map captured by validator object. - */ -function _fromAsn1(msg, obj, validator) { - var capture = {}; - var errors = []; - if(!asn1.validate(obj, validator, capture, errors)) { - var error = new Error('Cannot read PKCS#7 message. ' + - 'ASN.1 object is not a supported PKCS#7 message.'); - error.errors = error; - throw error; - } - - // Check contentType, so far we only support (raw) Data. - var contentType = asn1.derToOid(capture.contentType); - if(contentType !== forge$3.pki.oids.data) { - throw new Error('Unsupported PKCS#7 message. ' + - 'Only wrapped ContentType Data supported.'); - } - - if(capture.encryptedContent) { - var content = ''; - if(forge$3.util.isArray(capture.encryptedContent)) { - for(var i = 0; i < capture.encryptedContent.length; ++i) { - if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { - throw new Error('Malformed PKCS#7 message, expecting encrypted ' + - 'content constructed of only OCTET STRING objects.'); - } - content += capture.encryptedContent[i].value; - } - } else { - content = capture.encryptedContent; - } - msg.encryptedContent = { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: forge$3.util.createBuffer(capture.encParameter.value), - content: forge$3.util.createBuffer(content) - }; - } - - if(capture.content) { - var content = ''; - if(forge$3.util.isArray(capture.content)) { - for(var i = 0; i < capture.content.length; ++i) { - if(capture.content[i].type !== asn1.Type.OCTETSTRING) { - throw new Error('Malformed PKCS#7 message, expecting ' + - 'content constructed of only OCTET STRING objects.'); - } - content += capture.content[i].value; - } - } else { - content = capture.content; - } - msg.content = forge$3.util.createBuffer(content); - } - - msg.version = capture.version.charCodeAt(0); - msg.rawCapture = capture; - - return capture; -} - -/** - * Decrypt the symmetrically encrypted content block of the PKCS#7 message. - * - * Decryption is skipped in case the PKCS#7 message object already has a - * (decrypted) content attribute. The algorithm, key and cipher parameters - * (probably the iv) are taken from the encryptedContent attribute of the - * message object. - * - * @param The PKCS#7 message object. - */ -function _decryptContent(msg) { - if(msg.encryptedContent.key === undefined) { - throw new Error('Symmetric key not available.'); - } - - if(msg.content === undefined) { - var ciph; - - switch(msg.encryptedContent.algorithm) { - case forge$3.pki.oids['aes128-CBC']: - case forge$3.pki.oids['aes192-CBC']: - case forge$3.pki.oids['aes256-CBC']: - ciph = forge$3.aes.createDecryptionCipher(msg.encryptedContent.key); - break; - - case forge$3.pki.oids['desCBC']: - case forge$3.pki.oids['des-EDE3-CBC']: - ciph = forge$3.des.createDecryptionCipher(msg.encryptedContent.key); - break; - - default: - throw new Error('Unsupported symmetric cipher, OID ' + - msg.encryptedContent.algorithm); - } - ciph.start(msg.encryptedContent.parameter); - ciph.update(msg.encryptedContent.content); - - if(!ciph.finish()) { - throw new Error('Symmetric decryption failed.'); - } - - msg.content = ciph.output; - } -} - -/** - * Functions to output keys in SSH-friendly formats. - * - * This is part of the Forge project which may be used under the terms of - * either the BSD License or the GNU General Public License (GPL) Version 2. - * - * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE - * - * @author https://github.com/shellac - */ - -var forge$2 = forge$F; - - - - - - -var ssh = forge$2.ssh = forge$2.ssh || {}; - -/** - * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file. - * - * @param privateKey the key. - * @param passphrase a passphrase to protect the key (falsy for no encryption). - * @param comment a comment to include in the key file. - * - * @return the PPK file as a string. - */ -ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { - comment = comment || ''; - passphrase = passphrase || ''; - var algorithm = 'ssh-rsa'; - var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc'; - - var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n'; - ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n'; - ppk += 'Comment: ' + comment + '\r\n'; - - // public key into buffer for ppk - var pubbuffer = forge$2.util.createBuffer(); - _addStringToBuffer(pubbuffer, algorithm); - _addBigIntegerToBuffer(pubbuffer, privateKey.e); - _addBigIntegerToBuffer(pubbuffer, privateKey.n); - - // write public key - var pub = forge$2.util.encode64(pubbuffer.bytes(), 64); - var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \r\n - ppk += 'Public-Lines: ' + length + '\r\n'; - ppk += pub; - - // private key into a buffer - var privbuffer = forge$2.util.createBuffer(); - _addBigIntegerToBuffer(privbuffer, privateKey.d); - _addBigIntegerToBuffer(privbuffer, privateKey.p); - _addBigIntegerToBuffer(privbuffer, privateKey.q); - _addBigIntegerToBuffer(privbuffer, privateKey.qInv); - - // optionally encrypt the private key - var priv; - if(!passphrase) { - // use the unencrypted buffer - priv = forge$2.util.encode64(privbuffer.bytes(), 64); - } else { - // encrypt RSA key using passphrase - var encLen = privbuffer.length() + 16 - 1; - encLen -= encLen % 16; - - // pad private key with sha1-d data -- needs to be a multiple of 16 - var padding = _sha1(privbuffer.bytes()); - - padding.truncate(padding.length() - encLen + privbuffer.length()); - privbuffer.putBuffer(padding); - - var aeskey = forge$2.util.createBuffer(); - aeskey.putBuffer(_sha1('\x00\x00\x00\x00', passphrase)); - aeskey.putBuffer(_sha1('\x00\x00\x00\x01', passphrase)); - - // encrypt some bytes using CBC mode - // key is 40 bytes, so truncate *by* 8 bytes - var cipher = forge$2.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC'); - cipher.start(forge$2.util.createBuffer().fillWithByte(0, 16)); - cipher.update(privbuffer.copy()); - cipher.finish(); - var encrypted = cipher.output; - - // Note: this appears to differ from Putty -- is forge wrong, or putty? - // due to padding we finish as an exact multiple of 16 - encrypted.truncate(16); // all padding - - priv = forge$2.util.encode64(encrypted.bytes(), 64); - } - - // output private key - length = Math.floor(priv.length / 66) + 1; // 64 + \r\n - ppk += '\r\nPrivate-Lines: ' + length + '\r\n'; - ppk += priv; - - // MAC - var mackey = _sha1('putty-private-key-file-mac-key', passphrase); - - var macbuffer = forge$2.util.createBuffer(); - _addStringToBuffer(macbuffer, algorithm); - _addStringToBuffer(macbuffer, encryptionAlgorithm); - _addStringToBuffer(macbuffer, comment); - macbuffer.putInt32(pubbuffer.length()); - macbuffer.putBuffer(pubbuffer); - macbuffer.putInt32(privbuffer.length()); - macbuffer.putBuffer(privbuffer); - - var hmac = forge$2.hmac.create(); - hmac.start('sha1', mackey); - hmac.update(macbuffer.bytes()); - - ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n'; - - return ppk; -}; - -/** - * Encodes a public RSA key as an OpenSSH file. - * - * @param key the key. - * @param comment a comment. - * - * @return the public key in OpenSSH format. - */ -ssh.publicKeyToOpenSSH = function(key, comment) { - var type = 'ssh-rsa'; - comment = comment || ''; - - var buffer = forge$2.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - - return type + ' ' + forge$2.util.encode64(buffer.bytes()) + ' ' + comment; -}; - -/** - * Encodes a private RSA key as an OpenSSH file. - * - * @param key the key. - * @param passphrase a passphrase to protect the key (falsy for no encryption). - * - * @return the public key in OpenSSH format. - */ -ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { - if(!passphrase) { - return forge$2.pki.privateKeyToPem(privateKey); - } - // OpenSSH private key is just a legacy format, it seems - return forge$2.pki.encryptRsaPrivateKey(privateKey, passphrase, - {legacy: true, algorithm: 'aes128'}); -}; - -/** - * Gets the SSH fingerprint for the given public key. - * - * @param options the options to use. - * [md] the message digest object to use (defaults to forge.md.md5). - * [encoding] an alternative output encoding, such as 'hex' - * (defaults to none, outputs a byte buffer). - * [delimiter] the delimiter to use between bytes for 'hex' encoded - * output, eg: ':' (defaults to none). - * - * @return the fingerprint as a byte buffer or other encoding based on options. - */ -ssh.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge$2.md.md5.create(); - - var type = 'ssh-rsa'; - var buffer = forge$2.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - - // hash public key bytes - md.start(); - md.update(buffer.getBytes()); - var digest = md.digest(); - if(options.encoding === 'hex') { - var hex = digest.toHex(); - if(options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if(options.encoding === 'binary') { - return digest.getBytes(); - } else if(options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); - } - return digest; -}; - -/** - * Adds len(val) then val to a buffer. - * - * @param buffer the buffer to add to. - * @param val a big integer. - */ -function _addBigIntegerToBuffer(buffer, val) { - var hexVal = val.toString(16); - // ensure 2s complement +ve - if(hexVal[0] >= '8') { - hexVal = '00' + hexVal; - } - var bytes = forge$2.util.hexToBytes(hexVal); - buffer.putInt32(bytes.length); - buffer.putBytes(bytes); -} - -/** - * Adds len(val) then val to a buffer. - * - * @param buffer the buffer to add to. - * @param val a string. - */ -function _addStringToBuffer(buffer, val) { - buffer.putInt32(val.length); - buffer.putString(val); -} - -/** - * Hashes the arguments into one value using SHA-1. - * - * @return the sha1 hash of the provided arguments. - */ -function _sha1() { - var sha = forge$2.md.sha1.create(); - var num = arguments.length; - for (var i = 0; i < num; ++i) { - sha.update(arguments[i]); - } - return sha.digest(); -} - -/** - * Support for concurrent task management and synchronization in web - * applications. - * - * @author Dave Longley - * @author David I. Lehn - * - * Copyright (c) 2009-2013 Digital Bazaar, Inc. - */ - -var forge$1 = forge$F; - - - - -// logging category -var cat = 'forge.task'; - -// track tasks for debugging -var sTasks = {}; -var sNextTaskId = 0; -// debug access -forge$1.debug.set(cat, 'tasks', sTasks); - -// a map of task type to task queue -var sTaskQueues = {}; -// debug access -forge$1.debug.set(cat, 'queues', sTaskQueues); - -// name for unnamed tasks -var sNoTaskName = '?'; - -// maximum number of doNext() recursions before a context swap occurs -// FIXME: might need to tweak this based on the browser -var sMaxRecursions = 30; - -// time slice for doing tasks before a context swap occurs -// FIXME: might need to tweak this based on the browser -var sTimeSlice = 20; - -/** - * Task states. - * - * READY: ready to start processing - * RUNNING: task or a subtask is running - * BLOCKED: task is waiting to acquire N permits to continue - * SLEEPING: task is sleeping for a period of time - * DONE: task is done - * ERROR: task has an error - */ -var READY = 'ready'; -var RUNNING = 'running'; -var BLOCKED = 'blocked'; -var SLEEPING = 'sleeping'; -var DONE = 'done'; -var ERROR = 'error'; - -/** - * Task actions. Used to control state transitions. - * - * STOP: stop processing - * START: start processing tasks - * BLOCK: block task from continuing until 1 or more permits are released - * UNBLOCK: release one or more permits - * SLEEP: sleep for a period of time - * WAKEUP: wakeup early from SLEEPING state - * CANCEL: cancel further tasks - * FAIL: a failure occured - */ -var STOP = 'stop'; -var START = 'start'; -var BLOCK = 'block'; -var UNBLOCK = 'unblock'; -var SLEEP = 'sleep'; -var WAKEUP = 'wakeup'; -var CANCEL = 'cancel'; -var FAIL = 'fail'; - -/** - * State transition table. - * - * nextState = sStateTable[currentState][action] - */ -var sStateTable = {}; - -sStateTable[READY] = {}; -sStateTable[READY][STOP] = READY; -sStateTable[READY][START] = RUNNING; -sStateTable[READY][CANCEL] = DONE; -sStateTable[READY][FAIL] = ERROR; - -sStateTable[RUNNING] = {}; -sStateTable[RUNNING][STOP] = READY; -sStateTable[RUNNING][START] = RUNNING; -sStateTable[RUNNING][BLOCK] = BLOCKED; -sStateTable[RUNNING][UNBLOCK] = RUNNING; -sStateTable[RUNNING][SLEEP] = SLEEPING; -sStateTable[RUNNING][WAKEUP] = RUNNING; -sStateTable[RUNNING][CANCEL] = DONE; -sStateTable[RUNNING][FAIL] = ERROR; - -sStateTable[BLOCKED] = {}; -sStateTable[BLOCKED][STOP] = BLOCKED; -sStateTable[BLOCKED][START] = BLOCKED; -sStateTable[BLOCKED][BLOCK] = BLOCKED; -sStateTable[BLOCKED][UNBLOCK] = BLOCKED; -sStateTable[BLOCKED][SLEEP] = BLOCKED; -sStateTable[BLOCKED][WAKEUP] = BLOCKED; -sStateTable[BLOCKED][CANCEL] = DONE; -sStateTable[BLOCKED][FAIL] = ERROR; - -sStateTable[SLEEPING] = {}; -sStateTable[SLEEPING][STOP] = SLEEPING; -sStateTable[SLEEPING][START] = SLEEPING; -sStateTable[SLEEPING][BLOCK] = SLEEPING; -sStateTable[SLEEPING][UNBLOCK] = SLEEPING; -sStateTable[SLEEPING][SLEEP] = SLEEPING; -sStateTable[SLEEPING][WAKEUP] = SLEEPING; -sStateTable[SLEEPING][CANCEL] = DONE; -sStateTable[SLEEPING][FAIL] = ERROR; - -sStateTable[DONE] = {}; -sStateTable[DONE][STOP] = DONE; -sStateTable[DONE][START] = DONE; -sStateTable[DONE][BLOCK] = DONE; -sStateTable[DONE][UNBLOCK] = DONE; -sStateTable[DONE][SLEEP] = DONE; -sStateTable[DONE][WAKEUP] = DONE; -sStateTable[DONE][CANCEL] = DONE; -sStateTable[DONE][FAIL] = ERROR; - -sStateTable[ERROR] = {}; -sStateTable[ERROR][STOP] = ERROR; -sStateTable[ERROR][START] = ERROR; -sStateTable[ERROR][BLOCK] = ERROR; -sStateTable[ERROR][UNBLOCK] = ERROR; -sStateTable[ERROR][SLEEP] = ERROR; -sStateTable[ERROR][WAKEUP] = ERROR; -sStateTable[ERROR][CANCEL] = ERROR; -sStateTable[ERROR][FAIL] = ERROR; - -/** - * Creates a new task. - * - * @param options options for this task - * run: the run function for the task (required) - * name: the run function for the task (optional) - * parent: parent of this task (optional) - * - * @return the empty task. - */ -var Task = function(options) { - // task id - this.id = -1; - - // task name - this.name = options.name || sNoTaskName; - - // task has no parent - this.parent = options.parent || null; - - // save run function - this.run = options.run; - - // create a queue of subtasks to run - this.subtasks = []; - - // error flag - this.error = false; - - // state of the task - this.state = READY; - - // number of times the task has been blocked (also the number - // of permits needed to be released to continue running) - this.blocks = 0; - - // timeout id when sleeping - this.timeoutId = null; - - // no swap time yet - this.swapTime = null; - - // no user data - this.userData = null; - - // initialize task - // FIXME: deal with overflow - this.id = sNextTaskId++; - sTasks[this.id] = this; -}; - -/** - * Logs debug information on this task and the system state. - */ -Task.prototype.debug = function(msg) { - msg = msg || ''; - forge$1.log.debug(cat, msg, - '[%s][%s] task:', this.id, this.name, this, - 'subtasks:', this.subtasks.length, - 'queue:', sTaskQueues); -}; - -/** - * Adds a subtask to run after task.doNext() or task.fail() is called. - * - * @param name human readable name for this task (optional). - * @param subrun a function to run that takes the current task as - * its first parameter. - * - * @return the current task (useful for chaining next() calls). - */ -Task.prototype.next = function(name, subrun) { - // juggle parameters if it looks like no name is given - if(typeof(name) === 'function') { - subrun = name; - - // inherit parent's name - name = this.name; - } - // create subtask, set parent to this task, propagate callbacks - var subtask = new Task({ - run: subrun, - name: name, - parent: this - }); - // start subtasks running - subtask.state = RUNNING; - subtask.type = this.type; - subtask.successCallback = this.successCallback || null; - subtask.failureCallback = this.failureCallback || null; - - // queue a new subtask - this.subtasks.push(subtask); - - return this; -}; - -/** - * Adds subtasks to run in parallel after task.doNext() or task.fail() - * is called. - * - * @param name human readable name for this task (optional). - * @param subrun functions to run that take the current task as - * their first parameter. - * - * @return the current task (useful for chaining next() calls). - */ -Task.prototype.parallel = function(name, subrun) { - // juggle parameters if it looks like no name is given - if(forge$1.util.isArray(name)) { - subrun = name; - - // inherit parent's name - name = this.name; - } - // Wrap parallel tasks in a regular task so they are started at the - // proper time. - return this.next(name, function(task) { - // block waiting for subtasks - var ptask = task; - ptask.block(subrun.length); - - // we pass the iterator from the loop below as a parameter - // to a function because it is otherwise included in the - // closure and changes as the loop changes -- causing i - // to always be set to its highest value - var startParallelTask = function(pname, pi) { - forge$1.task.start({ - type: pname, - run: function(task) { - subrun[pi](task); - }, - success: function(task) { - ptask.unblock(); - }, - failure: function(task) { - ptask.unblock(); - } - }); - }; - - for(var i = 0; i < subrun.length; i++) { - // Type must be unique so task starts in parallel: - // name + private string + task id + sub-task index - // start tasks in parallel and unblock when the finish - var pname = name + '__parallel-' + task.id + '-' + i; - var pi = i; - startParallelTask(pname, pi); - } - }); -}; - -/** - * Stops a running task. - */ -Task.prototype.stop = function() { - this.state = sStateTable[this.state][STOP]; -}; - -/** - * Starts running a task. - */ -Task.prototype.start = function() { - this.error = false; - this.state = sStateTable[this.state][START]; - - // try to restart - if(this.state === RUNNING) { - this.start = new Date(); - this.run(this); - runNext(this, 0); - } -}; - -/** - * Blocks a task until it one or more permits have been released. The - * task will not resume until the requested number of permits have - * been released with call(s) to unblock(). - * - * @param n number of permits to wait for(default: 1). - */ -Task.prototype.block = function(n) { - n = typeof(n) === 'undefined' ? 1 : n; - this.blocks += n; - if(this.blocks > 0) { - this.state = sStateTable[this.state][BLOCK]; - } -}; - -/** - * Releases a permit to unblock a task. If a task was blocked by - * requesting N permits via block(), then it will only continue - * running once enough permits have been released via unblock() calls. - * - * If multiple processes need to synchronize with a single task then - * use a condition variable (see forge.task.createCondition). It is - * an error to unblock a task more times than it has been blocked. - * - * @param n number of permits to release (default: 1). - * - * @return the current block count (task is unblocked when count is 0) - */ -Task.prototype.unblock = function(n) { - n = typeof(n) === 'undefined' ? 1 : n; - this.blocks -= n; - if(this.blocks === 0 && this.state !== DONE) { - this.state = RUNNING; - runNext(this, 0); - } - return this.blocks; -}; - -/** - * Sleep for a period of time before resuming tasks. - * - * @param n number of milliseconds to sleep (default: 0). - */ -Task.prototype.sleep = function(n) { - n = typeof(n) === 'undefined' ? 0 : n; - this.state = sStateTable[this.state][SLEEP]; - var self = this; - this.timeoutId = setTimeout(function() { - self.timeoutId = null; - self.state = RUNNING; - runNext(self, 0); - }, n); -}; - -/** - * Waits on a condition variable until notified. The next task will - * not be scheduled until notification. A condition variable can be - * created with forge.task.createCondition(). - * - * Once cond.notify() is called, the task will continue. - * - * @param cond the condition variable to wait on. - */ -Task.prototype.wait = function(cond) { - cond.wait(this); -}; - -/** - * If sleeping, wakeup and continue running tasks. - */ -Task.prototype.wakeup = function() { - if(this.state === SLEEPING) { - cancelTimeout(this.timeoutId); - this.timeoutId = null; - this.state = RUNNING; - runNext(this, 0); - } -}; - -/** - * Cancel all remaining subtasks of this task. - */ -Task.prototype.cancel = function() { - this.state = sStateTable[this.state][CANCEL]; - // remove permits needed - this.permitsNeeded = 0; - // cancel timeouts - if(this.timeoutId !== null) { - cancelTimeout(this.timeoutId); - this.timeoutId = null; - } - // remove subtasks - this.subtasks = []; -}; - -/** - * Finishes this task with failure and sets error flag. The entire - * task will be aborted unless the next task that should execute - * is passed as a parameter. This allows levels of subtasks to be - * skipped. For instance, to abort only this tasks's subtasks, then - * call fail(task.parent). To abort this task's subtasks and its - * parent's subtasks, call fail(task.parent.parent). To abort - * all tasks and simply call the task callback, call fail() or - * fail(null). - * - * The task callback (success or failure) will always, eventually, be - * called. - * - * @param next the task to continue at, or null to abort entirely. - */ -Task.prototype.fail = function(next) { - // set error flag - this.error = true; - - // finish task - finish(this, true); - - if(next) { - // propagate task info - next.error = this.error; - next.swapTime = this.swapTime; - next.userData = this.userData; - - // do next task as specified - runNext(next, 0); - } else { - if(this.parent !== null) { - // finish root task (ensures it is removed from task queue) - var parent = this.parent; - while(parent.parent !== null) { - // propagate task info - parent.error = this.error; - parent.swapTime = this.swapTime; - parent.userData = this.userData; - parent = parent.parent; - } - finish(parent, true); - } - - // call failure callback if one exists - if(this.failureCallback) { - this.failureCallback(this); - } - } -}; - -/** - * Asynchronously start a task. - * - * @param task the task to start. - */ -var start = function(task) { - task.error = false; - task.state = sStateTable[task.state][START]; - setTimeout(function() { - if(task.state === RUNNING) { - task.swapTime = +new Date(); - task.run(task); - runNext(task, 0); - } - }, 0); -}; - -/** - * Run the next subtask or finish this task. - * - * @param task the task to process. - * @param recurse the recursion count. - */ -var runNext = function(task, recurse) { - // get time since last context swap (ms), if enough time has passed set - // swap to true to indicate that doNext was performed asynchronously - // also, if recurse is too high do asynchronously - var swap = - (recurse > sMaxRecursions) || - (+new Date() - task.swapTime) > sTimeSlice; - - var doNext = function(recurse) { - recurse++; - if(task.state === RUNNING) { - if(swap) { - // update swap time - task.swapTime = +new Date(); - } - - if(task.subtasks.length > 0) { - // run next subtask - var subtask = task.subtasks.shift(); - subtask.error = task.error; - subtask.swapTime = task.swapTime; - subtask.userData = task.userData; - subtask.run(subtask); - if(!subtask.error) { - runNext(subtask, recurse); - } - } else { - finish(task); - - if(!task.error) { - // chain back up and run parent - if(task.parent !== null) { - // propagate task info - task.parent.error = task.error; - task.parent.swapTime = task.swapTime; - task.parent.userData = task.userData; - - // no subtasks left, call run next subtask on parent - runNext(task.parent, recurse); - } - } - } - } - }; - - if(swap) { - // we're swapping, so run asynchronously - setTimeout(doNext, 0); - } else { - // not swapping, so run synchronously - doNext(recurse); - } -}; - -/** - * Finishes a task and looks for the next task in the queue to start. - * - * @param task the task to finish. - * @param suppressCallbacks true to suppress callbacks. - */ -var finish = function(task, suppressCallbacks) { - // subtask is now done - task.state = DONE; - - delete sTasks[task.id]; - - // only do queue processing for root tasks - if(task.parent === null) { - // report error if queue is missing - if(!(task.type in sTaskQueues)) { - forge$1.log.error(cat, - '[%s][%s] task queue missing [%s]', - task.id, task.name, task.type); - } else if(sTaskQueues[task.type].length === 0) { - // report error if queue is empty - forge$1.log.error(cat, - '[%s][%s] task queue empty [%s]', - task.id, task.name, task.type); - } else if(sTaskQueues[task.type][0] !== task) { - // report error if this task isn't the first in the queue - forge$1.log.error(cat, - '[%s][%s] task not first in queue [%s]', - task.id, task.name, task.type); - } else { - // remove ourselves from the queue - sTaskQueues[task.type].shift(); - // clean up queue if it is empty - if(sTaskQueues[task.type].length === 0) { - /* Note: Only a task can delete a queue of its own type. This - is used as a way to synchronize tasks. If a queue for a certain - task type exists, then a task of that type is running. - */ - delete sTaskQueues[task.type]; - } else { - sTaskQueues[task.type][0].start(); - } - } - - if(!suppressCallbacks) { - // call final callback if one exists - if(task.error && task.failureCallback) { - task.failureCallback(task); - } else if(!task.error && task.successCallback) { - task.successCallback(task); - } - } - } -}; - -/* Tasks API */ -forge$1.task = forge$1.task || {}; - -/** - * Starts a new task that will run the passed function asynchronously. - * - * In order to finish the task, either task.doNext() or task.fail() - * *must* be called. - * - * The task must have a type (a string identifier) that can be used to - * synchronize it with other tasks of the same type. That type can also - * be used to cancel tasks that haven't started yet. - * - * To start a task, the following object must be provided as a parameter - * (each function takes a task object as its first parameter): - * - * { - * type: the type of task. - * run: the function to run to execute the task. - * success: a callback to call when the task succeeds (optional). - * failure: a callback to call when the task fails (optional). - * } - * - * @param options the object as described above. - */ -forge$1.task.start = function(options) { - // create a new task - var task = new Task({ - run: options.run, - name: options.name || sNoTaskName - }); - task.type = options.type; - task.successCallback = options.success || null; - task.failureCallback = options.failure || null; - - // append the task onto the appropriate queue - if(!(task.type in sTaskQueues)) { - // create the queue with the new task - sTaskQueues[task.type] = [task]; - start(task); - } else { - // push the task onto the queue, it will be run after a task - // with the same type completes - sTaskQueues[options.type].push(task); - } -}; - -/** - * Cancels all tasks of the given type that haven't started yet. - * - * @param type the type of task to cancel. - */ -forge$1.task.cancel = function(type) { - // find the task queue - if(type in sTaskQueues) { - // empty all but the current task from the queue - sTaskQueues[type] = [sTaskQueues[type][0]]; - } -}; - -/** - * Creates a condition variable to synchronize tasks. To make a task wait - * on the condition variable, call task.wait(condition). To notify all - * tasks that are waiting, call condition.notify(). - * - * @return the condition variable. - */ -forge$1.task.createCondition = function() { - var cond = { - // all tasks that are blocked - tasks: {} - }; - - /** - * Causes the given task to block until notify is called. If the task - * is already waiting on this condition then this is a no-op. - * - * @param task the task to cause to wait. - */ - cond.wait = function(task) { - // only block once - if(!(task.id in cond.tasks)) { - task.block(); - cond.tasks[task.id] = task; - } - }; - - /** - * Notifies all waiting tasks to wake up. - */ - cond.notify = function() { - // since unblock() will run the next task from here, make sure to - // clear the condition's blocked task list before unblocking - var tmp = cond.tasks; - cond.tasks = {}; - for(var id in tmp) { - tmp[id].unblock(); - } - }; - - return cond; -}; - -/** - * Node.js module for Forge. - * - * @author Dave Longley - * - * Copyright 2011-2016 Digital Bazaar, Inc. - */ - -var lib = forge$F; - -var forge = lib; - -// a hexString is considered negative if it's most significant bit is 1 -// because serial numbers use ones' complement notation -// this RFC in section 4.1.2.2 requires serial numbers to be positive -// http://www.ietf.org/rfc/rfc5280.txt -function toPositiveHex(hexString){ - var mostSiginficativeHexAsInt = parseInt(hexString[0], 16); - if (mostSiginficativeHexAsInt < 8){ - return hexString; - } - - mostSiginficativeHexAsInt -= 8; - return mostSiginficativeHexAsInt.toString() + hexString.substring(1); -} - -function getAlgorithm(key) { - switch (key) { - case 'sha256': - return forge.md.sha256.create(); - default: - return forge.md.sha1.create(); - } -} - -/** - * - * @param {forge.pki.CertificateField[]} attrs Attributes used for subject and issuer. - * @param {object} options - * @param {number} [options.days=365] the number of days before expiration - * @param {number} [options.keySize=1024] the size for the private key in bits - * @param {object} [options.extensions] additional extensions for the certificate - * @param {string} [options.algorithm="sha1"] The signature algorithm sha256 or sha1 - * @param {boolean} [options.pkcs7=false] include PKCS#7 as part of the output - * @param {boolean} [options.clientCertificate=false] generate client cert signed by the original key - * @param {string} [options.clientCertificateCN="John Doe jdoe123"] client certificate's common name - * @param {function} [done] Optional callback, if not provided the generation is synchronous - * @returns - */ -var generate = selfsigned.generate = function generate(attrs, options, done) { - if (typeof attrs === 'function') { - done = attrs; - attrs = undefined; - } else if (typeof options === 'function') { - done = options; - options = {}; - } - - options = options || {}; - - var generatePem = function (keyPair) { - var cert = forge.pki.createCertificate(); - - cert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); // the serial number can be decimal or hex (if preceded by 0x) - - cert.validity.notBefore = new Date(); - cert.validity.notAfter = new Date(); - cert.validity.notAfter.setDate(cert.validity.notBefore.getDate() + (options.days || 365)); - - attrs = attrs || [{ - name: 'commonName', - value: 'example.org' - }, { - name: 'countryName', - value: 'US' - }, { - shortName: 'ST', - value: 'Virginia' - }, { - name: 'localityName', - value: 'Blacksburg' - }, { - name: 'organizationName', - value: 'Test' - }, { - shortName: 'OU', - value: 'Test' - }]; - - cert.setSubject(attrs); - cert.setIssuer(attrs); - - cert.publicKey = keyPair.publicKey; - - cert.setExtensions(options.extensions || [{ - name: 'basicConstraints', - cA: true - }, { - name: 'keyUsage', - keyCertSign: true, - digitalSignature: true, - nonRepudiation: true, - keyEncipherment: true, - dataEncipherment: true - }, { - name: 'subjectAltName', - altNames: [{ - type: 6, // URI - value: 'http://example.org/webid#me' - }] - }]); - - cert.sign(keyPair.privateKey, getAlgorithm(options && options.algorithm)); - - const fingerprint = forge.md.sha1 - .create() - .update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes()) - .digest() - .toHex() - .match(/.{2}/g) - .join(':'); - - var pem = { - private: forge.pki.privateKeyToPem(keyPair.privateKey), - public: forge.pki.publicKeyToPem(keyPair.publicKey), - cert: forge.pki.certificateToPem(cert), - fingerprint: fingerprint, - }; - - if (options && options.pkcs7) { - var p7 = forge.pkcs7.createSignedData(); - p7.addCertificate(cert); - pem.pkcs7 = forge.pkcs7.messageToPem(p7); - } - - if (options && options.clientCertificate) { - var clientkeys = forge.pki.rsa.generateKeyPair(1024); - var clientcert = forge.pki.createCertificate(); - clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); - clientcert.validity.notBefore = new Date(); - clientcert.validity.notAfter = new Date(); - clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1); - - var clientAttrs = JSON.parse(JSON.stringify(attrs)); - - for(var i = 0; i < clientAttrs.length; i++) { - if(clientAttrs[i].name === 'commonName') { - if( options.clientCertificateCN ) - clientAttrs[i] = { name: 'commonName', value: options.clientCertificateCN }; - else - clientAttrs[i] = { name: 'commonName', value: 'John Doe jdoe123' }; - } - } - - clientcert.setSubject(clientAttrs); - - // Set the issuer to the parent key - clientcert.setIssuer(attrs); - - clientcert.publicKey = clientkeys.publicKey; - - // Sign client cert with root cert - clientcert.sign(keyPair.privateKey); - - pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey); - pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey); - pem.clientcert = forge.pki.certificateToPem(clientcert); - - if (options.pkcs7) { - var clientp7 = forge.pkcs7.createSignedData(); - clientp7.addCertificate(clientcert); - pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7); - } - } - - var caStore = forge.pki.createCaStore(); - caStore.addCertificate(cert); - - try { - forge.pki.verifyCertificateChain(caStore, [cert], - function (vfd, depth, chain) { - if (vfd !== true) { - throw new Error('Certificate could not be verified.'); - } - return true; - }); - } - catch(ex) { - throw new Error(ex); - } - - return pem; - }; - - var keySize = options.keySize || 1024; - - if (done) { // async scenario - return forge.pki.rsa.generateKeyPair({ bits: keySize }, function (err, keyPair) { - if (err) { return done(err); } - - try { - return done(null, generatePem(keyPair)); - } catch (ex) { - return done(ex); - } - }); - } - - var keyPair = options.keyPair ? { - privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey), - publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey) - } : forge.pki.rsa.generateKeyPair(keySize); - - return generatePem(keyPair); -}; - -var index = /*#__PURE__*/_mergeNamespaces({ - __proto__: null, - 'default': selfsigned, - generate: generate -}, [selfsigned]); - -exports.index = index; -//# sourceMappingURL=dep-34d2edc0.js.map diff --git a/packages/astro/vendor/vite/dist/node/chunks/dep-34d2edc0.js.map b/packages/astro/vendor/vite/dist/node/chunks/dep-34d2edc0.js.map deleted file mode 100755 index 647181bb10d9..000000000000 --- a/packages/astro/vendor/vite/dist/node/chunks/dep-34d2edc0.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dep-34d2edc0.js","sources":["../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/forge.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/baseN.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/util.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/cipher.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/cipherModes.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/aes.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/oids.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/asn1.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/md.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/hmac.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/md5.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/pem.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/des.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/pbkdf2.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/sha256.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/prng.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/random.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/rc2.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/jsbn.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/sha1.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/pkcs1.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/prime.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/rsa.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/pbe.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/pkcs7asn1.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/mgf1.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/mgf.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/pss.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/x509.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/pkcs12.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/pki.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/tls.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/aesCipherSuites.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/debug.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/sha512.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/asn1-validator.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/ed25519.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/kem.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/log.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/pkcs7.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/ssh.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/task.js","../../../../../node_modules/.pnpm/node-forge@0.10.0/node_modules/node-forge/lib/index.js","../../../../../node_modules/.pnpm/selfsigned@1.10.11/node_modules/selfsigned/index.js"],"sourcesContent":["/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = {\n // default options\n options: {\n usePureJavaScript: false\n }\n};\n","/**\n * Base-N/Base-X encoding/decoding functions.\n *\n * Original implementation from base-x:\n * https://github.com/cryptocoinjs/base-x\n *\n * Which is MIT licensed:\n *\n * The MIT License (MIT)\n *\n * Copyright base-x contributors (c) 2016\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nvar api = {};\nmodule.exports = api;\n\n// baseN alphabet indexes\nvar _reverseAlphabets = {};\n\n/**\n * BaseN-encodes a Uint8Array using the given alphabet.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the baseN-encoded output string.\n */\napi.encode = function(input, alphabet, maxline) {\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n if(maxline !== undefined && typeof maxline !== 'number') {\n throw new TypeError('\"maxline\" must be a number.');\n }\n\n var output = '';\n\n if(!(input instanceof Uint8Array)) {\n // assume forge byte buffer\n output = _encodeWithByteBuffer(input, alphabet);\n } else {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length; ++i) {\n for(var j = 0, carry = input[i]; j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n // deal with leading zeros\n for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n }\n\n if(maxline) {\n var regex = new RegExp('.{1,' + maxline + '}', 'g');\n output = output.match(regex).join('\\r\\n');\n }\n\n return output;\n};\n\n/**\n * Decodes a baseN-encoded (using the given alphabet) string to a\n * Uint8Array.\n *\n * @param input the baseN-encoded input string.\n *\n * @return the Uint8Array.\n */\napi.decode = function(input, alphabet) {\n if(typeof input !== 'string') {\n throw new TypeError('\"input\" must be a string.');\n }\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n\n var table = _reverseAlphabets[alphabet];\n if(!table) {\n // compute reverse alphabet\n table = _reverseAlphabets[alphabet] = [];\n for(var i = 0; i < alphabet.length; ++i) {\n table[alphabet.charCodeAt(i)] = i;\n }\n }\n\n // remove whitespace characters\n input = input.replace(/\\s/g, '');\n\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var bytes = [0];\n for(var i = 0; i < input.length; i++) {\n var value = table[input.charCodeAt(i)];\n if(value === undefined) {\n return;\n }\n\n for(var j = 0, carry = value; j < bytes.length; ++j) {\n carry += bytes[j] * base;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while(carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // deal with leading zeros\n for(var k = 0; input[k] === first && k < input.length - 1; ++k) {\n bytes.push(0);\n }\n\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(bytes.reverse());\n }\n\n return new Uint8Array(bytes.reverse());\n};\n\nfunction _encodeWithByteBuffer(input, alphabet) {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length(); ++i) {\n for(var j = 0, carry = input.at(i); j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n var output = '';\n\n // deal with leading zeros\n for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n\n return output;\n}\n","/**\n * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nvar baseN = require('./baseN');\n\n/* Utilities API */\nvar util = module.exports = forge.util = forge.util || {};\n\n// define setImmediate and nextTick\n(function() {\n // use native nextTick (unless we're in webpack)\n // webpack (or better node-libs-browser polyfill) sets process.browser.\n // this way we can detect webpack properly\n if(typeof process !== 'undefined' && process.nextTick && !process.browser) {\n util.nextTick = process.nextTick;\n if(typeof setImmediate === 'function') {\n util.setImmediate = setImmediate;\n } else {\n // polyfill setImmediate with nextTick, older versions of node\n // (those w/o setImmediate) won't totally starve IO\n util.setImmediate = util.nextTick;\n }\n return;\n }\n\n // polyfill nextTick with native setImmediate\n if(typeof setImmediate === 'function') {\n util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };\n util.nextTick = function(callback) {\n return setImmediate(callback);\n };\n return;\n }\n\n /* Note: A polyfill upgrade pattern is used here to allow combining\n polyfills. For example, MutationObserver is fast, but blocks UI updates,\n so it needs to allow UI updates periodically, so it falls back on\n postMessage or setTimeout. */\n\n // polyfill with setTimeout\n util.setImmediate = function(callback) {\n setTimeout(callback, 0);\n };\n\n // upgrade polyfill to use postMessage\n if(typeof window !== 'undefined' &&\n typeof window.postMessage === 'function') {\n var msg = 'forge.setImmediate';\n var callbacks = [];\n util.setImmediate = function(callback) {\n callbacks.push(callback);\n // only send message when one hasn't been sent in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n window.postMessage(msg, '*');\n }\n };\n function handler(event) {\n if(event.source === window && event.data === msg) {\n event.stopPropagation();\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }\n }\n window.addEventListener('message', handler, true);\n }\n\n // upgrade polyfill to use MutationObserver\n if(typeof MutationObserver !== 'undefined') {\n // polyfill with MutationObserver\n var now = Date.now();\n var attr = true;\n var div = document.createElement('div');\n var callbacks = [];\n new MutationObserver(function() {\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }).observe(div, {attributes: true});\n var oldSetImmediate = util.setImmediate;\n util.setImmediate = function(callback) {\n if(Date.now() - now > 15) {\n now = Date.now();\n oldSetImmediate(callback);\n } else {\n callbacks.push(callback);\n // only trigger observer when it hasn't been triggered in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n div.setAttribute('a', attr = !attr);\n }\n }\n };\n }\n\n util.nextTick = util.setImmediate;\n})();\n\n// check if running under Node.js\nutil.isNodejs =\n typeof process !== 'undefined' && process.versions && process.versions.node;\n\n\n// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while\n// it will point to `window` in the main thread.\n// To remain compatible with older browsers, we fall back to 'window' if 'self'\n// is not available.\nutil.globalScope = (function() {\n if(util.isNodejs) {\n return global;\n }\n\n return typeof self === 'undefined' ? window : self;\n})();\n\n// define isArray\nutil.isArray = Array.isArray || function(x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n};\n\n// define isArrayBuffer\nutil.isArrayBuffer = function(x) {\n return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;\n};\n\n// define isArrayBufferView\nutil.isArrayBufferView = function(x) {\n return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;\n};\n\n/**\n * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for\n * algorithms where bit manipulation, JavaScript limitations, and/or algorithm\n * design only allow for byte operations of a limited size.\n *\n * @param n number of bits.\n *\n * Throw Error if n invalid.\n */\nfunction _checkBitsParam(n) {\n if(!(n === 8 || n === 16 || n === 24 || n === 32)) {\n throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);\n }\n}\n\n// TODO: set ByteBuffer to best available backing\nutil.ByteBuffer = ByteStringBuffer;\n\n/** Buffer w/BinaryString backing */\n\n/**\n * Constructor for a binary string backed byte buffer.\n *\n * @param [b] the bytes to wrap (either encoded as string, one byte per\n * character, or as an ArrayBuffer or Typed Array).\n */\nfunction ByteStringBuffer(b) {\n // TODO: update to match DataBuffer API\n\n // the data in this buffer\n this.data = '';\n // the pointer for reading from this buffer\n this.read = 0;\n\n if(typeof b === 'string') {\n this.data = b;\n } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {\n if(typeof Buffer !== 'undefined' && b instanceof Buffer) {\n this.data = b.toString('binary');\n } else {\n // convert native buffer to forge buffer\n // FIXME: support native buffers internally instead\n var arr = new Uint8Array(b);\n try {\n this.data = String.fromCharCode.apply(null, arr);\n } catch(e) {\n for(var i = 0; i < arr.length; ++i) {\n this.putByte(arr[i]);\n }\n }\n }\n } else if(b instanceof ByteStringBuffer ||\n (typeof b === 'object' && typeof b.data === 'string' &&\n typeof b.read === 'number')) {\n // copy existing buffer\n this.data = b.data;\n this.read = b.read;\n }\n\n // used for v8 optimization\n this._constructedStringLength = 0;\n}\nutil.ByteStringBuffer = ByteStringBuffer;\n\n/* Note: This is an optimization for V8-based browsers. When V8 concatenates\n a string, the strings are only joined logically using a \"cons string\" or\n \"constructed/concatenated string\". These containers keep references to one\n another and can result in very large memory usage. For example, if a 2MB\n string is constructed by concatenating 4 bytes together at a time, the\n memory usage will be ~44MB; so ~22x increase. The strings are only joined\n together when an operation requiring their joining takes place, such as\n substr(). This function is called when adding data to this buffer to ensure\n these types of strings are periodically joined to reduce the memory\n footprint. */\nvar _MAX_CONSTRUCTED_STRING_LENGTH = 4096;\nutil.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {\n this._constructedStringLength += x;\n if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {\n // this substr() should cause the constructed string to join\n this.data.substr(0, 1);\n this._constructedStringLength = 0;\n }\n};\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.ByteStringBuffer.prototype.length = function() {\n return this.data.length - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.ByteStringBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putByte = function(b) {\n return this.putBytes(String.fromCharCode(b));\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.fillWithByte = function(b, n) {\n b = String.fromCharCode(b);\n var d = this.data;\n while(n > 0) {\n if(n & 1) {\n d += b;\n }\n n >>>= 1;\n if(n > 0) {\n b += b;\n }\n }\n this.data = d;\n this._optimizeConstructedString(n);\n return this;\n};\n\n/**\n * Puts bytes in this buffer.\n *\n * @param bytes the bytes (as a binary encoded string) to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBytes = function(bytes) {\n this.data += bytes;\n this._optimizeConstructedString(bytes.length);\n return this;\n};\n\n/**\n * Puts a UTF-16 encoded string into this buffer.\n *\n * @param str the string to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putString = function(str) {\n return this.putBytes(util.encodeUtf8(str));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 24 & 0xFF));\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n var bytes = '';\n do {\n n -= 8;\n bytes += String.fromCharCode((i >> n) & 0xFF);\n } while(n > 0);\n return this.putBytes(bytes);\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putSignedInt = function(i, n) {\n // putInt checks n\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBuffer = function(buffer) {\n return this.putBytes(buffer.getBytes());\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.getByte = function() {\n return this.data.charCodeAt(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 8 ^\n this.data.charCodeAt(this.read + 1));\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 16 ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 24 ^\n this.data.charCodeAt(this.read + 1) << 16 ^\n this.data.charCodeAt(this.read + 2) << 8 ^\n this.data.charCodeAt(this.read + 3));\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16 ^\n this.data.charCodeAt(this.read + 3) << 24);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by ceil(n/8).\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.charCodeAt(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer. Note that the resulting string is binary encoded (in node.js this\n * encoding is referred to as `binary`, it is *not* `utf8`).\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.ByteStringBuffer.prototype.getBytes = function(count) {\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.ByteStringBuffer.prototype.bytes = function(count) {\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.at = function(i) {\n return this.data.charCodeAt(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.setAt = function(i, b) {\n this.data = this.data.substr(0, this.read + i) +\n String.fromCharCode(b) +\n this.data.substr(this.read + i + 1);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.ByteStringBuffer.prototype.last = function() {\n return this.data.charCodeAt(this.data.length - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.ByteStringBuffer.prototype.copy = function() {\n var c = util.createBuffer(this.data);\n c.read = this.read;\n return c;\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.compact = function() {\n if(this.read > 0) {\n this.data = this.data.slice(this.read);\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.clear = function() {\n this.data = '';\n this.read = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.truncate = function(count) {\n var len = Math.max(0, this.length() - count);\n this.data = this.data.substr(this.read, len);\n this.read = 0;\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.ByteStringBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.length; ++i) {\n var b = this.data.charCodeAt(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a UTF-16 string (standard JavaScript string).\n *\n * @return a UTF-16 string.\n */\nutil.ByteStringBuffer.prototype.toString = function() {\n return util.decodeUtf8(this.bytes());\n};\n\n/** End Buffer w/BinaryString backing */\n\n/** Buffer w/UInt8Array backing */\n\n/**\n * FIXME: Experimental. Do not use yet.\n *\n * Constructor for an ArrayBuffer-backed byte buffer.\n *\n * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a\n * TypedArray.\n *\n * If a string is given, its encoding should be provided as an option,\n * otherwise it will default to 'binary'. A 'binary' string is encoded such\n * that each character is one byte in length and size.\n *\n * If an ArrayBuffer, DataView, or TypedArray is given, it will be used\n * *directly* without any copying. Note that, if a write to the buffer requires\n * more space, the buffer will allocate a new backing ArrayBuffer to\n * accommodate. The starting read and write offsets for the buffer may be\n * given as options.\n *\n * @param [b] the initial bytes for this buffer.\n * @param options the options to use:\n * [readOffset] the starting read offset to use (default: 0).\n * [writeOffset] the starting write offset to use (default: the\n * length of the first parameter).\n * [growSize] the minimum amount, in bytes, to grow the buffer by to\n * accommodate writes (default: 1024).\n * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the\n * first parameter, if it is a string (default: 'binary').\n */\nfunction DataBuffer(b, options) {\n // default options\n options = options || {};\n\n // pointers for read from/write to buffer\n this.read = options.readOffset || 0;\n this.growSize = options.growSize || 1024;\n\n var isArrayBuffer = util.isArrayBuffer(b);\n var isArrayBufferView = util.isArrayBufferView(b);\n if(isArrayBuffer || isArrayBufferView) {\n // use ArrayBuffer directly\n if(isArrayBuffer) {\n this.data = new DataView(b);\n } else {\n // TODO: adjust read/write offset based on the type of view\n // or specify that this must be done in the options ... that the\n // offsets are byte-based\n this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);\n }\n this.write = ('writeOffset' in options ?\n options.writeOffset : this.data.byteLength);\n return;\n }\n\n // initialize to empty array buffer and add any given bytes using putBytes\n this.data = new DataView(new ArrayBuffer(0));\n this.write = 0;\n\n if(b !== null && b !== undefined) {\n this.putBytes(b);\n }\n\n if('writeOffset' in options) {\n this.write = options.writeOffset;\n }\n}\nutil.DataBuffer = DataBuffer;\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.DataBuffer.prototype.length = function() {\n return this.write - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.DataBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Ensures this buffer has enough empty space to accommodate the given number\n * of bytes. An optional parameter may be given that indicates a minimum\n * amount to grow the buffer if necessary. If the parameter is not given,\n * the buffer will be grown by some previously-specified default amount\n * or heuristic.\n *\n * @param amount the number of bytes to accommodate.\n * @param [growSize] the minimum amount, in bytes, to grow the buffer by if\n * necessary.\n */\nutil.DataBuffer.prototype.accommodate = function(amount, growSize) {\n if(this.length() >= amount) {\n return this;\n }\n growSize = Math.max(growSize || this.growSize, amount);\n\n // grow buffer\n var src = new Uint8Array(\n this.data.buffer, this.data.byteOffset, this.data.byteLength);\n var dst = new Uint8Array(this.length() + growSize);\n dst.set(src);\n this.data = new DataView(dst.buffer);\n\n return this;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putByte = function(b) {\n this.accommodate(1);\n this.data.setUint8(this.write++, b);\n return this;\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.fillWithByte = function(b, n) {\n this.accommodate(n);\n for(var i = 0; i < n; ++i) {\n this.data.setUint8(b);\n }\n return this;\n};\n\n/**\n * Puts bytes in this buffer. The bytes may be given as a string, an\n * ArrayBuffer, a DataView, or a TypedArray.\n *\n * @param bytes the bytes to put.\n * @param [encoding] the encoding for the first parameter ('binary', 'utf8',\n * 'utf16', 'hex'), if it is a string (default: 'binary').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBytes = function(bytes, encoding) {\n if(util.isArrayBufferView(bytes)) {\n var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n var len = src.byteLength - src.byteOffset;\n this.accommodate(len);\n var dst = new Uint8Array(this.data.buffer, this.write);\n dst.set(src);\n this.write += len;\n return this;\n }\n\n if(util.isArrayBuffer(bytes)) {\n var src = new Uint8Array(bytes);\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(this.data.buffer);\n dst.set(src, this.write);\n this.write += src.byteLength;\n return this;\n }\n\n // bytes is a util.DataBuffer or equivalent\n if(bytes instanceof util.DataBuffer ||\n (typeof bytes === 'object' &&\n typeof bytes.read === 'number' && typeof bytes.write === 'number' &&\n util.isArrayBufferView(bytes.data))) {\n var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(bytes.data.byteLength, this.write);\n dst.set(src);\n this.write += src.byteLength;\n return this;\n }\n\n if(bytes instanceof util.ByteStringBuffer) {\n // copy binary string and process as the same as a string parameter below\n bytes = bytes.data;\n encoding = 'binary';\n }\n\n // string conversion\n encoding = encoding || 'binary';\n if(typeof bytes === 'string') {\n var view;\n\n // decode from string\n if(encoding === 'hex') {\n this.accommodate(Math.ceil(bytes.length / 2));\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.hex.decode(bytes, view, this.write);\n return this;\n }\n if(encoding === 'base64') {\n this.accommodate(Math.ceil(bytes.length / 4) * 3);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.base64.decode(bytes, view, this.write);\n return this;\n }\n\n // encode text as UTF-8 bytes\n if(encoding === 'utf8') {\n // encode as UTF-8 then decode string as raw binary\n bytes = util.encodeUtf8(bytes);\n encoding = 'binary';\n }\n\n // decode string as raw binary\n if(encoding === 'binary' || encoding === 'raw') {\n // one byte per character\n this.accommodate(bytes.length);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.raw.decode(view);\n return this;\n }\n\n // encode text as UTF-16 bytes\n if(encoding === 'utf16') {\n // two bytes per character\n this.accommodate(bytes.length * 2);\n view = new Uint16Array(this.data.buffer, this.write);\n this.write += util.text.utf16.encode(view);\n return this;\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n }\n\n throw Error('Invalid parameter: ' + bytes);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBuffer = function(buffer) {\n this.putBytes(buffer);\n buffer.clear();\n return this;\n};\n\n/**\n * Puts a string into this buffer.\n *\n * @param str the string to put.\n * @param [encoding] the encoding for the string (default: 'utf16').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putString = function(str) {\n return this.putBytes(str, 'utf16');\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16 = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24 = function(i) {\n this.accommodate(3);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32 = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16Le = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i, true);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24Le = function(i) {\n this.accommodate(3);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32Le = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i, true);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n do {\n n -= 8;\n this.data.setInt8(this.write++, (i >> n) & 0xFF);\n } while(n > 0);\n return this;\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putSignedInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.getByte = function() {\n return this.data.getInt8(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16 = function() {\n var rval = this.data.getInt16(this.read);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.getInt16(this.read) << 8 ^\n this.data.getInt8(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32 = function() {\n var rval = this.data.getInt32(this.read);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16Le = function() {\n var rval = this.data.getInt16(this.read, true);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.getInt8(this.read) ^\n this.data.getInt16(this.read + 1, true) << 8);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32Le = function() {\n var rval = this.data.getInt32(this.read, true);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.getInt8(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer.\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.DataBuffer.prototype.getBytes = function(count) {\n // TODO: deprecate this method, it is poorly named and\n // this.toString('binary') replaces it\n // add a toTypedArray()/toArrayBuffer() function\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.DataBuffer.prototype.bytes = function(count) {\n // TODO: deprecate this method, it is poorly named, add \"getString()\"\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.at = function(i) {\n return this.data.getUint8(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.setAt = function(i, b) {\n this.data.setUint8(i, b);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.DataBuffer.prototype.last = function() {\n return this.data.getUint8(this.write - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.DataBuffer.prototype.copy = function() {\n return new util.DataBuffer(this);\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.compact = function() {\n if(this.read > 0) {\n var src = new Uint8Array(this.data.buffer, this.read);\n var dst = new Uint8Array(src.byteLength);\n dst.set(src);\n this.data = new DataView(dst);\n this.write -= this.read;\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.clear = function() {\n this.data = new DataView(new ArrayBuffer(0));\n this.read = this.write = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.truncate = function(count) {\n this.write = Math.max(0, this.length() - count);\n this.read = Math.min(this.read, this.write);\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.DataBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.byteLength; ++i) {\n var b = this.data.getUint8(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a string, using the given encoding. If no\n * encoding is given, 'utf8' (UTF-8) is used.\n *\n * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',\n * 'base64' (default: 'utf8').\n *\n * @return a string representation of the bytes in this buffer.\n */\nutil.DataBuffer.prototype.toString = function(encoding) {\n var view = new Uint8Array(this.data, this.read, this.length());\n encoding = encoding || 'utf8';\n\n // encode to string\n if(encoding === 'binary' || encoding === 'raw') {\n return util.binary.raw.encode(view);\n }\n if(encoding === 'hex') {\n return util.binary.hex.encode(view);\n }\n if(encoding === 'base64') {\n return util.binary.base64.encode(view);\n }\n\n // decode to text\n if(encoding === 'utf8') {\n return util.text.utf8.decode(view);\n }\n if(encoding === 'utf16') {\n return util.text.utf16.decode(view);\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n};\n\n/** End Buffer w/UInt8Array backing */\n\n/**\n * Creates a buffer that stores bytes. A value may be given to populate the\n * buffer with data. This value can either be string of encoded bytes or a\n * regular string of characters. When passing a string of binary encoded\n * bytes, the encoding `raw` should be given. This is also the default. When\n * passing a string of characters, the encoding `utf8` should be given.\n *\n * @param [input] a string with encoded bytes to store in the buffer.\n * @param [encoding] (default: 'raw', other: 'utf8').\n */\nutil.createBuffer = function(input, encoding) {\n // TODO: deprecate, use new ByteBuffer() instead\n encoding = encoding || 'raw';\n if(input !== undefined && encoding === 'utf8') {\n input = util.encodeUtf8(input);\n }\n return new util.ByteBuffer(input);\n};\n\n/**\n * Fills a string with a particular value. If you want the string to be a byte\n * string, pass in String.fromCharCode(theByte).\n *\n * @param c the character to fill the string with, use String.fromCharCode\n * to fill the string with a byte value.\n * @param n the number of characters of value c to fill with.\n *\n * @return the filled string.\n */\nutil.fillString = function(c, n) {\n var s = '';\n while(n > 0) {\n if(n & 1) {\n s += c;\n }\n n >>>= 1;\n if(n > 0) {\n c += c;\n }\n }\n return s;\n};\n\n/**\n * Performs a per byte XOR between two byte strings and returns the result as a\n * string of bytes.\n *\n * @param s1 first string of bytes.\n * @param s2 second string of bytes.\n * @param n the number of bytes to XOR.\n *\n * @return the XOR'd result.\n */\nutil.xorBytes = function(s1, s2, n) {\n var s3 = '';\n var b = '';\n var t = '';\n var i = 0;\n var c = 0;\n for(; n > 0; --n, ++i) {\n b = s1.charCodeAt(i) ^ s2.charCodeAt(i);\n if(c >= 10) {\n s3 += t;\n t = '';\n c = 0;\n }\n t += String.fromCharCode(b);\n ++c;\n }\n s3 += t;\n return s3;\n};\n\n/**\n * Converts a hex string into a 'binary' encoded string of bytes.\n *\n * @param hex the hexadecimal string to convert.\n *\n * @return the binary-encoded string of bytes.\n */\nutil.hexToBytes = function(hex) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.decode instead.\"\n var rval = '';\n var i = 0;\n if(hex.length & 1 == 1) {\n // odd number of characters, convert first character alone\n i = 1;\n rval += String.fromCharCode(parseInt(hex[0], 16));\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n }\n return rval;\n};\n\n/**\n * Converts a 'binary' encoded string of bytes to hex.\n *\n * @param bytes the byte string to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.bytesToHex = function(bytes) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.encode instead.\"\n return util.createBuffer(bytes).toHex();\n};\n\n/**\n * Converts an 32-bit integer to 4-big-endian byte string.\n *\n * @param i the integer.\n *\n * @return the byte string.\n */\nutil.int32ToBytes = function(i) {\n return (\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n// base64 characters, reverse mapping\nvar _base64 =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nvar _base64Idx = [\n/*43 -43 = 0*/\n/*'+', 1, 2, 3,'/' */\n 62, -1, -1, -1, 63,\n\n/*'0','1','2','3','4','5','6','7','8','9' */\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n\n/*15, 16, 17,'=', 19, 20, 21 */\n -1, -1, -1, 64, -1, -1, -1,\n\n/*65 - 43 = 22*/\n/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n\n/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n\n/*91 - 43 = 48 */\n/*48, 49, 50, 51, 52, 53 */\n -1, -1, -1, -1, -1, -1,\n\n/*97 - 43 = 54*/\n/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n\n/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n];\n\n// base58 characters (Bitcoin alphabet)\nvar _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Base64 encodes a 'binary' encoded string of bytes.\n *\n * @param input the binary encoded string of bytes to base64-encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output.\n */\nutil.encode64 = function(input, maxline) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.encode instead.\"\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Base64 decodes a string into a 'binary' encoded string of bytes.\n *\n * @param input the base64-encoded input.\n *\n * @return the binary encoded string.\n */\nutil.decode64 = function(input) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.decode instead.\"\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n var output = '';\n var enc1, enc2, enc3, enc4;\n var i = 0;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));\n if(enc4 !== 64) {\n // decoded 3 bytes\n output += String.fromCharCode(((enc3 & 3) << 6) | enc4);\n }\n }\n }\n\n return output;\n};\n\n/**\n * Encodes the given string of characters (a standard JavaScript\n * string) as a binary encoded string where the bytes represent\n * a UTF-8 encoded string of characters. Non-ASCII characters will be\n * encoded as multiple bytes according to UTF-8.\n *\n * @param str a standard string of characters to encode.\n *\n * @return the binary encoded string.\n */\nutil.encodeUtf8 = function(str) {\n return unescape(encodeURIComponent(str));\n};\n\n/**\n * Decodes a binary encoded string that contains bytes that\n * represent a UTF-8 encoded string of characters -- into a\n * string of characters (a standard JavaScript string).\n *\n * @param str the binary encoded string to decode.\n *\n * @return the resulting standard string of characters.\n */\nutil.decodeUtf8 = function(str) {\n return decodeURIComponent(escape(str));\n};\n\n// binary encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.binary = {\n raw: {},\n hex: {},\n base64: {},\n base58: {},\n baseN : {\n encode: baseN.encode,\n decode: baseN.decode\n }\n};\n\n/**\n * Encodes a Uint8Array as a binary-encoded string. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param bytes the Uint8Array to encode.\n *\n * @return the binary-encoded string.\n */\nutil.binary.raw.encode = function(bytes) {\n return String.fromCharCode.apply(null, bytes);\n};\n\n/**\n * Decodes a binary-encoded string to a Uint8Array. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param str the binary-encoded string to decode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.raw.decode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or\n * ByteBuffer as a string of hexadecimal characters.\n *\n * @param bytes the bytes to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.binary.hex.encode = util.bytesToHex;\n\n/**\n * Decodes a hex-encoded string to a Uint8Array.\n *\n * @param hex the hexadecimal string to convert.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.hex.decode = function(hex, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(hex.length / 2));\n }\n offset = offset || 0;\n var i = 0, j = offset;\n if(hex.length & 1) {\n // odd number of characters, convert first character alone\n i = 1;\n out[j++] = parseInt(hex[0], 16);\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n out[j++] = parseInt(hex.substr(i, 2), 16);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Base64-encodes a Uint8Array.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output string.\n */\nutil.binary.base64.encode = function(input, maxline) {\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.byteLength) {\n chr1 = input[i++];\n chr2 = input[i++];\n chr3 = input[i++];\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Decodes a base64-encoded string to a Uint8Array.\n *\n * @param input the base64-encoded input string.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.base64.decode = function(input, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(input.length / 4) * 3);\n }\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n offset = offset || 0;\n var enc1, enc2, enc3, enc4;\n var i = 0, j = offset;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n out[j++] = (enc1 << 2) | (enc2 >> 4);\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);\n if(enc4 !== 64) {\n // decoded 3 bytes\n out[j++] = ((enc3 & 3) << 6) | enc4;\n }\n }\n }\n\n // make sure result is the exact decoded length\n return output ? (j - offset) : out.subarray(0, j);\n};\n\n// add support for base58 encoding/decoding with Bitcoin alphabet\nutil.binary.base58.encode = function(input, maxline) {\n return util.binary.baseN.encode(input, _base58, maxline);\n};\nutil.binary.base58.decode = function(input, maxline) {\n return util.binary.baseN.decode(input, _base58, maxline);\n};\n\n// text encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.text = {\n utf8: {},\n utf16: {}\n};\n\n/**\n * Encodes the given string as UTF-8 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf8.encode = function(str, output, offset) {\n str = util.encodeUtf8(str);\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-8 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf8.decode = function(bytes) {\n return util.decodeUtf8(String.fromCharCode.apply(null, bytes));\n};\n\n/**\n * Encodes the given string as UTF-16 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf16.encode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length * 2);\n }\n var view = new Uint16Array(out.buffer);\n offset = offset || 0;\n var j = offset;\n var k = offset;\n for(var i = 0; i < str.length; ++i) {\n view[k++] = str.charCodeAt(i);\n j += 2;\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-16 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf16.decode = function(bytes) {\n return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));\n};\n\n/**\n * Deflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true to return only raw deflate data, false to include zlib\n * header and trailer.\n *\n * @return the deflated data as a string.\n */\nutil.deflate = function(api, bytes, raw) {\n bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);\n\n // strip zlib header and trailer if necessary\n if(raw) {\n // zlib header is 2 bytes (CMF,FLG) where FLG indicates that\n // there is a 4-byte DICT (alder-32) block before the data if\n // its 5th bit is set\n var start = 2;\n var flg = bytes.charCodeAt(1);\n if(flg & 0x20) {\n start = 6;\n }\n // zlib trailer is 4 bytes of adler-32\n bytes = bytes.substring(start, bytes.length - 4);\n }\n\n return bytes;\n};\n\n/**\n * Inflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true if the incoming data has no zlib header or trailer and is\n * raw DEFLATE data.\n *\n * @return the inflated data as a string, null on error.\n */\nutil.inflate = function(api, bytes, raw) {\n // TODO: add zlib header and trailer if necessary/possible\n var rval = api.inflate(util.encode64(bytes)).rval;\n return (rval === null) ? null : util.decode64(rval);\n};\n\n/**\n * Sets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param obj the storage object, null to remove.\n */\nvar _setStorageObject = function(api, id, obj) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n var rval;\n if(obj === null) {\n rval = api.removeItem(id);\n } else {\n // json-encode and base64-encode object\n obj = util.encode64(JSON.stringify(obj));\n rval = api.setItem(id, obj);\n }\n\n // handle potential flash error\n if(typeof(rval) !== 'undefined' && rval.rval !== true) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n};\n\n/**\n * Gets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n *\n * @return the storage object entry or null if none exists.\n */\nvar _getStorageObject = function(api, id) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n // get the existing entry\n var rval = api.getItem(id);\n\n /* Note: We check api.init because we can't do (api == localStorage)\n on IE because of \"Class doesn't support Automation\" exception. Only\n the flash api has an init method so this works too, but we need a\n better solution in the future. */\n\n // flash returns item wrapped in an object, handle special case\n if(api.init) {\n if(rval.rval === null) {\n if(rval.error) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n // no error, but also no item\n rval = null;\n } else {\n rval = rval.rval;\n }\n }\n\n // handle decoding\n if(rval !== null) {\n // base64-decode and json-decode data\n rval = JSON.parse(util.decode64(rval));\n }\n\n return rval;\n};\n\n/**\n * Stores an item in local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n */\nvar _setItem = function(api, id, key, data) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj === null) {\n // create a new storage object\n obj = {};\n }\n // update key\n obj[key] = data;\n\n // set storage object\n _setStorageObject(api, id, obj);\n};\n\n/**\n * Gets an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n *\n * @return the item.\n */\nvar _getItem = function(api, id, key) {\n // get storage object\n var rval = _getStorageObject(api, id);\n if(rval !== null) {\n // return data at key\n rval = (key in rval) ? rval[key] : null;\n }\n\n return rval;\n};\n\n/**\n * Removes an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n */\nvar _removeItem = function(api, id, key) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj !== null && key in obj) {\n // remove key\n delete obj[key];\n\n // see if entry has no keys remaining\n var empty = true;\n for(var prop in obj) {\n empty = false;\n break;\n }\n if(empty) {\n // remove entry entirely if no keys are left\n obj = null;\n }\n\n // set storage object\n _setStorageObject(api, id, obj);\n }\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n */\nvar _clearItems = function(api, id) {\n _setStorageObject(api, id, null);\n};\n\n/**\n * Calls a storage function.\n *\n * @param func the function to call.\n * @param args the arguments for the function.\n * @param location the location argument.\n *\n * @return the return value from the function.\n */\nvar _callStorageFunction = function(func, args, location) {\n var rval = null;\n\n // default storage types\n if(typeof(location) === 'undefined') {\n location = ['web', 'flash'];\n }\n\n // apply storage types in order of preference\n var type;\n var done = false;\n var exception = null;\n for(var idx in location) {\n type = location[idx];\n try {\n if(type === 'flash' || type === 'both') {\n if(args[0] === null) {\n throw new Error('Flash local storage not available.');\n }\n rval = func.apply(this, args);\n done = (type === 'flash');\n }\n if(type === 'web' || type === 'both') {\n args[0] = localStorage;\n rval = func.apply(this, args);\n done = true;\n }\n } catch(ex) {\n exception = ex;\n }\n if(done) {\n break;\n }\n }\n\n if(!done) {\n throw exception;\n }\n\n return rval;\n};\n\n/**\n * Stores an item on local disk.\n *\n * The available types of local storage include 'flash', 'web', and 'both'.\n *\n * The type 'flash' refers to flash local storage (SharedObject). In order\n * to use flash local storage, the 'api' parameter must be valid. The type\n * 'web' refers to WebStorage, if supported by the browser. The type 'both'\n * refers to storing using both 'flash' and 'web', not just one or the\n * other.\n *\n * The location array should list the storage types to use in order of\n * preference:\n *\n * ['flash']: flash only storage\n * ['web']: web only storage\n * ['both']: try to store in both\n * ['flash','web']: store in flash first, but if not available, 'web'\n * ['web','flash']: store in web first, but if not available, 'flash'\n *\n * The location array defaults to: ['web', 'flash']\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n * @param location an array with the preferred types of storage to use.\n */\nutil.setItem = function(api, id, key, data, location) {\n _callStorageFunction(_setItem, arguments, location);\n};\n\n/**\n * Gets an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n *\n * @return the item.\n */\nutil.getItem = function(api, id, key, location) {\n return _callStorageFunction(_getItem, arguments, location);\n};\n\n/**\n * Removes an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n */\nutil.removeItem = function(api, id, key, location) {\n _callStorageFunction(_removeItem, arguments, location);\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface if flash is available.\n * @param id the storage ID to use.\n * @param location an array with the preferred types of storage to use.\n */\nutil.clearItems = function(api, id, location) {\n _callStorageFunction(_clearItems, arguments, location);\n};\n\n/**\n * Parses the scheme, host, and port from an http(s) url.\n *\n * @param str the url string.\n *\n * @return the parsed url object or null if the url is invalid.\n */\nutil.parseUrl = function(str) {\n // FIXME: this regex looks a bit broken\n var regex = /^(https?):\\/\\/([^:&^\\/]*):?(\\d*)(.*)$/g;\n regex.lastIndex = 0;\n var m = regex.exec(str);\n var url = (m === null) ? null : {\n full: str,\n scheme: m[1],\n host: m[2],\n port: m[3],\n path: m[4]\n };\n if(url) {\n url.fullHost = url.host;\n if(url.port) {\n if(url.port !== 80 && url.scheme === 'http') {\n url.fullHost += ':' + url.port;\n } else if(url.port !== 443 && url.scheme === 'https') {\n url.fullHost += ':' + url.port;\n }\n } else if(url.scheme === 'http') {\n url.port = 80;\n } else if(url.scheme === 'https') {\n url.port = 443;\n }\n url.full = url.scheme + '://' + url.fullHost;\n }\n return url;\n};\n\n/* Storage for query variables */\nvar _queryVariables = null;\n\n/**\n * Returns the window location query variables. Query is parsed on the first\n * call and the same object is returned on subsequent calls. The mapping\n * is from keys to an array of values. Parameters without values will have\n * an object key set but no value added to the value array. Values are\n * unescaped.\n *\n * ...?k1=v1&k2=v2:\n * {\n * \"k1\": [\"v1\"],\n * \"k2\": [\"v2\"]\n * }\n *\n * ...?k1=v1&k1=v2:\n * {\n * \"k1\": [\"v1\", \"v2\"]\n * }\n *\n * ...?k1=v1&k2:\n * {\n * \"k1\": [\"v1\"],\n * \"k2\": []\n * }\n *\n * ...?k1=v1&k1:\n * {\n * \"k1\": [\"v1\"]\n * }\n *\n * ...?k1&k1:\n * {\n * \"k1\": []\n * }\n *\n * @param query the query string to parse (optional, default to cached\n * results from parsing window location search query).\n *\n * @return object mapping keys to variables.\n */\nutil.getQueryVariables = function(query) {\n var parse = function(q) {\n var rval = {};\n var kvpairs = q.split('&');\n for(var i = 0; i < kvpairs.length; i++) {\n var pos = kvpairs[i].indexOf('=');\n var key;\n var val;\n if(pos > 0) {\n key = kvpairs[i].substring(0, pos);\n val = kvpairs[i].substring(pos + 1);\n } else {\n key = kvpairs[i];\n val = null;\n }\n if(!(key in rval)) {\n rval[key] = [];\n }\n // disallow overriding object prototype keys\n if(!(key in Object.prototype) && val !== null) {\n rval[key].push(unescape(val));\n }\n }\n return rval;\n };\n\n var rval;\n if(typeof(query) === 'undefined') {\n // set cached variables if needed\n if(_queryVariables === null) {\n if(typeof(window) !== 'undefined' && window.location && window.location.search) {\n // parse window search query\n _queryVariables = parse(window.location.search.substring(1));\n } else {\n // no query variables available\n _queryVariables = {};\n }\n }\n rval = _queryVariables;\n } else {\n // parse given query\n rval = parse(query);\n }\n return rval;\n};\n\n/**\n * Parses a fragment into a path and query. This method will take a URI\n * fragment and break it up as if it were the main URI. For example:\n * /bar/baz?a=1&b=2\n * results in:\n * {\n * path: [\"bar\", \"baz\"],\n * query: {\"k1\": [\"v1\"], \"k2\": [\"v2\"]}\n * }\n *\n * @return object with a path array and query object.\n */\nutil.parseFragment = function(fragment) {\n // default to whole fragment\n var fp = fragment;\n var fq = '';\n // split into path and query if possible at the first '?'\n var pos = fragment.indexOf('?');\n if(pos > 0) {\n fp = fragment.substring(0, pos);\n fq = fragment.substring(pos + 1);\n }\n // split path based on '/' and ignore first element if empty\n var path = fp.split('/');\n if(path.length > 0 && path[0] === '') {\n path.shift();\n }\n // convert query into object\n var query = (fq === '') ? {} : util.getQueryVariables(fq);\n\n return {\n pathString: fp,\n queryString: fq,\n path: path,\n query: query\n };\n};\n\n/**\n * Makes a request out of a URI-like request string. This is intended to\n * be used where a fragment id (after a URI '#') is parsed as a URI with\n * path and query parts. The string should have a path beginning and\n * delimited by '/' and optional query parameters following a '?'. The\n * query should be a standard URL set of key value pairs delimited by\n * '&'. For backwards compatibility the initial '/' on the path is not\n * required. The request object has the following API, (fully described\n * in the method code):\n * {\n * path: .\n * query: ,\n * getPath(i): get part or all of the split path array,\n * getQuery(k, i): get part or all of a query key array,\n * getQueryLast(k, _default): get last element of a query key array.\n * }\n *\n * @return object with request parameters.\n */\nutil.makeRequest = function(reqString) {\n var frag = util.parseFragment(reqString);\n var req = {\n // full path string\n path: frag.pathString,\n // full query string\n query: frag.queryString,\n /**\n * Get path or element in path.\n *\n * @param i optional path index.\n *\n * @return path or part of path if i provided.\n */\n getPath: function(i) {\n return (typeof(i) === 'undefined') ? frag.path : frag.path[i];\n },\n /**\n * Get query, values for a key, or value for a key index.\n *\n * @param k optional query key.\n * @param i optional query key index.\n *\n * @return query, values for a key, or value for a key index.\n */\n getQuery: function(k, i) {\n var rval;\n if(typeof(k) === 'undefined') {\n rval = frag.query;\n } else {\n rval = frag.query[k];\n if(rval && typeof(i) !== 'undefined') {\n rval = rval[i];\n }\n }\n return rval;\n },\n getQueryLast: function(k, _default) {\n var rval;\n var vals = req.getQuery(k);\n if(vals) {\n rval = vals[vals.length - 1];\n } else {\n rval = _default;\n }\n return rval;\n }\n };\n return req;\n};\n\n/**\n * Makes a URI out of a path, an object with query parameters, and a\n * fragment. Uses jQuery.param() internally for query string creation.\n * If the path is an array, it will be joined with '/'.\n *\n * @param path string path or array of strings.\n * @param query object with query parameters. (optional)\n * @param fragment fragment string. (optional)\n *\n * @return string object with request parameters.\n */\nutil.makeLink = function(path, query, fragment) {\n // join path parts if needed\n path = jQuery.isArray(path) ? path.join('/') : path;\n\n var qstr = jQuery.param(query || {});\n fragment = fragment || '';\n return path +\n ((qstr.length > 0) ? ('?' + qstr) : '') +\n ((fragment.length > 0) ? ('#' + fragment) : '');\n};\n\n/**\n * Check if an object is empty.\n *\n * Taken from:\n * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937\n *\n * @param object the object to check.\n */\nutil.isEmpty = function(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Format with simple printf-style interpolation.\n *\n * %%: literal '%'\n * %s,%o: convert next argument into a string.\n *\n * @param format the string to format.\n * @param ... arguments to interpolate into the format string.\n */\nutil.format = function(format) {\n var re = /%./g;\n // current match\n var match;\n // current part\n var part;\n // current arg index\n var argi = 0;\n // collected parts to recombine later\n var parts = [];\n // last index found\n var last = 0;\n // loop while matches remain\n while((match = re.exec(format))) {\n part = format.substring(last, re.lastIndex - 2);\n // don't add empty strings (ie, parts between %s%s)\n if(part.length > 0) {\n parts.push(part);\n }\n last = re.lastIndex;\n // switch on % code\n var code = match[0][1];\n switch(code) {\n case 's':\n case 'o':\n // check if enough arguments were given\n if(argi < arguments.length) {\n parts.push(arguments[argi++ + 1]);\n } else {\n parts.push('');\n }\n break;\n // FIXME: do proper formating for numbers, etc\n //case 'f':\n //case 'd':\n case '%':\n parts.push('%');\n break;\n default:\n parts.push('<%' + code + '?>');\n }\n }\n // add trailing part of format string\n parts.push(format.substring(last));\n return parts.join('');\n};\n\n/**\n * Formats a number.\n *\n * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/\n */\nutil.formatNumber = function(number, decimals, dec_point, thousands_sep) {\n // http://kevin.vanzonneveld.net\n // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n // + bugfix by: Michael White (http://crestidg.com)\n // + bugfix by: Benjamin Lupton\n // + bugfix by: Allan Jensen (http://www.winternet.no)\n // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // * example 1: number_format(1234.5678, 2, '.', '');\n // * returns 1: 1234.57\n\n var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;\n var d = dec_point === undefined ? ',' : dec_point;\n var t = thousands_sep === undefined ?\n '.' : thousands_sep, s = n < 0 ? '-' : '';\n var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';\n var j = (i.length > 3) ? i.length % 3 : 0;\n return s + (j ? i.substr(0, j) + t : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + t) +\n (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n};\n\n/**\n * Formats a byte size.\n *\n * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/\n */\nutil.formatSize = function(size) {\n if(size >= 1073741824) {\n size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';\n } else if(size >= 1048576) {\n size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';\n } else if(size >= 1024) {\n size = util.formatNumber(size / 1024, 0) + ' KiB';\n } else {\n size = util.formatNumber(size, 0) + ' bytes';\n }\n return size;\n};\n\n/**\n * Converts an IPv4 or IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv4 or IPv6 address to convert.\n *\n * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't\n * be parsed.\n */\nutil.bytesFromIP = function(ip) {\n if(ip.indexOf('.') !== -1) {\n return util.bytesFromIPv4(ip);\n }\n if(ip.indexOf(':') !== -1) {\n return util.bytesFromIPv6(ip);\n }\n return null;\n};\n\n/**\n * Converts an IPv4 string representation into bytes (in network order).\n *\n * @param ip the IPv4 address to convert.\n *\n * @return the 4-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv4 = function(ip) {\n ip = ip.split('.');\n if(ip.length !== 4) {\n return null;\n }\n var b = util.createBuffer();\n for(var i = 0; i < ip.length; ++i) {\n var num = parseInt(ip[i], 10);\n if(isNaN(num)) {\n return null;\n }\n b.putByte(num);\n }\n return b.getBytes();\n};\n\n/**\n * Converts an IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv6 address to convert.\n *\n * @return the 16-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv6 = function(ip) {\n var blanks = 0;\n ip = ip.split(':').filter(function(e) {\n if(e.length === 0) ++blanks;\n return true;\n });\n var zeros = (8 - ip.length + blanks) * 2;\n var b = util.createBuffer();\n for(var i = 0; i < 8; ++i) {\n if(!ip[i] || ip[i].length === 0) {\n b.fillWithByte(0, zeros);\n zeros = 0;\n continue;\n }\n var bytes = util.hexToBytes(ip[i]);\n if(bytes.length < 2) {\n b.putByte(0);\n }\n b.putBytes(bytes);\n }\n return b.getBytes();\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation or 16-bytes into\n * an IPv6 string representation. The bytes must be in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,\n * respectively, are given, otherwise null.\n */\nutil.bytesToIP = function(bytes) {\n if(bytes.length === 4) {\n return util.bytesToIPv4(bytes);\n }\n if(bytes.length === 16) {\n return util.bytesToIPv6(bytes);\n }\n return null;\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv4 = function(bytes) {\n if(bytes.length !== 4) {\n return null;\n }\n var ip = [];\n for(var i = 0; i < bytes.length; ++i) {\n ip.push(bytes.charCodeAt(i));\n }\n return ip.join('.');\n};\n\n/**\n * Converts 16-bytes into an IPv16 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv16 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv6 = function(bytes) {\n if(bytes.length !== 16) {\n return null;\n }\n var ip = [];\n var zeroGroups = [];\n var zeroMaxGroup = 0;\n for(var i = 0; i < bytes.length; i += 2) {\n var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);\n // canonicalize zero representation\n while(hex[0] === '0' && hex !== '0') {\n hex = hex.substr(1);\n }\n if(hex === '0') {\n var last = zeroGroups[zeroGroups.length - 1];\n var idx = ip.length;\n if(!last || idx !== last.end + 1) {\n zeroGroups.push({start: idx, end: idx});\n } else {\n last.end = idx;\n if((last.end - last.start) >\n (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {\n zeroMaxGroup = zeroGroups.length - 1;\n }\n }\n }\n ip.push(hex);\n }\n if(zeroGroups.length > 0) {\n var group = zeroGroups[zeroMaxGroup];\n // only shorten group of length > 0\n if(group.end - group.start > 0) {\n ip.splice(group.start, group.end - group.start + 1, '');\n if(group.start === 0) {\n ip.unshift('');\n }\n if(group.end === 7) {\n ip.push('');\n }\n }\n }\n return ip.join(':');\n};\n\n/**\n * Estimates the number of processes that can be run concurrently. If\n * creating Web Workers, keep in mind that the main JavaScript process needs\n * its own core.\n *\n * @param options the options to use:\n * update true to force an update (not use the cached value).\n * @param callback(err, max) called once the operation completes.\n */\nutil.estimateCores = function(options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n if('cores' in util && !options.update) {\n return callback(null, util.cores);\n }\n if(typeof navigator !== 'undefined' &&\n 'hardwareConcurrency' in navigator &&\n navigator.hardwareConcurrency > 0) {\n util.cores = navigator.hardwareConcurrency;\n return callback(null, util.cores);\n }\n if(typeof Worker === 'undefined') {\n // workers not available\n util.cores = 1;\n return callback(null, util.cores);\n }\n if(typeof Blob === 'undefined') {\n // can't estimate, default to 2\n util.cores = 2;\n return callback(null, util.cores);\n }\n\n // create worker concurrency estimation code as blob\n var blobUrl = URL.createObjectURL(new Blob(['(',\n function() {\n self.addEventListener('message', function(e) {\n // run worker for 4 ms\n var st = Date.now();\n var et = st + 4;\n while(Date.now() < et);\n self.postMessage({st: st, et: et});\n });\n }.toString(),\n ')()'], {type: 'application/javascript'}));\n\n // take 5 samples using 16 workers\n sample([], 5, 16);\n\n function sample(max, samples, numWorkers) {\n if(samples === 0) {\n // get overlap average\n var avg = Math.floor(max.reduce(function(avg, x) {\n return avg + x;\n }, 0) / max.length);\n util.cores = Math.max(1, avg);\n URL.revokeObjectURL(blobUrl);\n return callback(null, util.cores);\n }\n map(numWorkers, function(err, results) {\n max.push(reduce(numWorkers, results));\n sample(max, samples - 1, numWorkers);\n });\n }\n\n function map(numWorkers, callback) {\n var workers = [];\n var results = [];\n for(var i = 0; i < numWorkers; ++i) {\n var worker = new Worker(blobUrl);\n worker.addEventListener('message', function(e) {\n results.push(e.data);\n if(results.length === numWorkers) {\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].terminate();\n }\n callback(null, results);\n }\n });\n workers.push(worker);\n }\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].postMessage(i);\n }\n }\n\n function reduce(numWorkers, results) {\n // find overlapping time windows\n var overlaps = [];\n for(var n = 0; n < numWorkers; ++n) {\n var r1 = results[n];\n var overlap = overlaps[n] = [];\n for(var i = 0; i < numWorkers; ++i) {\n if(n === i) {\n continue;\n }\n var r2 = results[i];\n if((r1.st > r2.st && r1.st < r2.et) ||\n (r2.st > r1.st && r2.st < r1.et)) {\n overlap.push(i);\n }\n }\n }\n // get maximum overlaps ... don't include overlapping worker itself\n // as the main JS process was also being scheduled during the work and\n // would have to be subtracted from the estimate anyway\n return overlaps.reduce(function(max, overlap) {\n return Math.max(max, overlap.length);\n }, 0);\n }\n};\n","/**\n * Cipher base API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nmodule.exports = forge.cipher = forge.cipher || {};\n\n// registered algorithms\nforge.cipher.algorithms = forge.cipher.algorithms || {};\n\n/**\n * Creates a cipher object that can be used to encrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createCipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: false\n });\n};\n\n/**\n * Creates a decipher object that can be used to decrypt data using the given\n * algorithm and key. The algorithm may be provided as a string value for a\n * previously registered algorithm or it may be given as a cipher algorithm\n * API object.\n *\n * @param algorithm the algorithm to use, either a string or an algorithm API\n * object.\n * @param key the key to use, as a binary-encoded string of bytes or a\n * byte buffer.\n *\n * @return the cipher.\n */\nforge.cipher.createDecipher = function(algorithm, key) {\n var api = algorithm;\n if(typeof api === 'string') {\n api = forge.cipher.getAlgorithm(api);\n if(api) {\n api = api();\n }\n }\n if(!api) {\n throw new Error('Unsupported algorithm: ' + algorithm);\n }\n\n // assume block cipher\n return new forge.cipher.BlockCipher({\n algorithm: api,\n key: key,\n decrypt: true\n });\n};\n\n/**\n * Registers an algorithm by name. If the name was already registered, the\n * algorithm API object will be overwritten.\n *\n * @param name the name of the algorithm.\n * @param algorithm the algorithm API object.\n */\nforge.cipher.registerAlgorithm = function(name, algorithm) {\n name = name.toUpperCase();\n forge.cipher.algorithms[name] = algorithm;\n};\n\n/**\n * Gets a registered algorithm by name.\n *\n * @param name the name of the algorithm.\n *\n * @return the algorithm, if found, null if not.\n */\nforge.cipher.getAlgorithm = function(name) {\n name = name.toUpperCase();\n if(name in forge.cipher.algorithms) {\n return forge.cipher.algorithms[name];\n }\n return null;\n};\n\nvar BlockCipher = forge.cipher.BlockCipher = function(options) {\n this.algorithm = options.algorithm;\n this.mode = this.algorithm.mode;\n this.blockSize = this.mode.blockSize;\n this._finish = false;\n this._input = null;\n this.output = null;\n this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;\n this._decrypt = options.decrypt;\n this.algorithm.initialize(options);\n};\n\n/**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array\n * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in\n * bytes, then it must be Nb (16) bytes in length. If the IV is given in as\n * 32-bit integers, then it must be 4 integers long.\n *\n * Note: an IV is not required or used in ECB mode.\n *\n * For GCM-mode, the IV must be given as a binary-encoded string of bytes or\n * a byte buffer. The number of bytes should be 12 (96 bits) as recommended\n * by NIST SP-800-38D but another length may be given.\n *\n * @param options the options to use:\n * iv the initialization vector to use as a binary-encoded string of\n * bytes, null to reuse the last ciphered block from a previous\n * update() (this \"residue\" method is for legacy support only).\n * additionalData additional authentication data as a binary-encoded\n * string of bytes, for 'GCM' mode, (default: none).\n * tagLength desired length of authentication tag, in bits, for\n * 'GCM' mode (0-128, default: 128).\n * tag the authentication tag to check if decrypting, as a\n * binary-encoded string of bytes.\n * output the output the buffer to write to, null to create one.\n */\nBlockCipher.prototype.start = function(options) {\n options = options || {};\n var opts = {};\n for(var key in options) {\n opts[key] = options[key];\n }\n opts.decrypt = this._decrypt;\n this._finish = false;\n this._input = forge.util.createBuffer();\n this.output = options.output || forge.util.createBuffer();\n this.mode.start(opts);\n};\n\n/**\n * Updates the next block according to the cipher mode.\n *\n * @param input the buffer to read from.\n */\nBlockCipher.prototype.update = function(input) {\n if(input) {\n // input given, so empty it into the input buffer\n this._input.putBuffer(input);\n }\n\n // do cipher operation until it needs more input and not finished\n while(!this._op.call(this.mode, this._input, this.output, this._finish) &&\n !this._finish) {}\n\n // free consumed memory from input buffer\n this._input.compact();\n};\n\n/**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use in CBC mode, null for default,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\nBlockCipher.prototype.finish = function(pad) {\n // backwards-compatibility w/deprecated padding API\n // Note: will overwrite padding functions even after another start() call\n if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {\n this.mode.pad = function(input) {\n return pad(this.blockSize, input, false);\n };\n this.mode.unpad = function(output) {\n return pad(this.blockSize, output, true);\n };\n }\n\n // build options for padding and afterFinish functions\n var options = {};\n options.decrypt = this._decrypt;\n\n // get # of bytes that won't fill a block\n options.overflow = this._input.length() % this.blockSize;\n\n if(!this._decrypt && this.mode.pad) {\n if(!this.mode.pad(this._input, options)) {\n return false;\n }\n }\n\n // do final update\n this._finish = true;\n this.update();\n\n if(this._decrypt && this.mode.unpad) {\n if(!this.mode.unpad(this.output, options)) {\n return false;\n }\n }\n\n if(this.mode.afterFinish) {\n if(!this.mode.afterFinish(this.output, options)) {\n return false;\n }\n }\n\n return true;\n};\n","/**\n * Supported cipher modes.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.cipher = forge.cipher || {};\n\n// supported cipher modes\nvar modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};\n\n/** Electronic codebook (ECB) (Don't use this; it's not secure) **/\n\nmodes.ecb = function(options) {\n options = options || {};\n this.name = 'ECB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.ecb.prototype.start = function(options) {};\n\nmodes.ecb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n};\n\nmodes.ecb.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.ecb.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher-block Chaining (CBC) **/\n\nmodes.cbc = function(options) {\n options = options || {};\n this.name = 'CBC';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n};\n\nmodes.cbc.prototype.start = function(options) {\n // Note: legacy support for using IV residue (has security flaws)\n // if IV is null, reuse block from previous processing\n if(options.iv === null) {\n // must have a previous block\n if(!this._prev) {\n throw new Error('Invalid IV parameter.');\n }\n this._iv = this._prev.slice(0);\n } else if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n } else {\n // save IV as \"previous\" block\n this._iv = transformIV(options.iv, this.blockSize);\n this._prev = this._iv.slice(0);\n }\n};\n\nmodes.cbc.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n // CBC XOR's IV (or previous block) with plaintext\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._prev[i] ^ input.getInt32();\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // write output, save previous block\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i]);\n }\n this._prev = this._outBlock;\n};\n\nmodes.cbc.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n if(input.length() < this.blockSize && !(finish && input.length() > 0)) {\n return true;\n }\n\n // get next block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n }\n\n // decrypt block\n this.cipher.decrypt(this._inBlock, this._outBlock);\n\n // write output, save previous ciphered block\n // CBC XOR's IV (or previous block) with ciphertext\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._prev[i] ^ this._outBlock[i]);\n }\n this._prev = this._inBlock.slice(0);\n};\n\nmodes.cbc.prototype.pad = function(input, options) {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (input.length() === this.blockSize ?\n this.blockSize : (this.blockSize - input.length()));\n input.fillWithByte(padding, padding);\n return true;\n};\n\nmodes.cbc.prototype.unpad = function(output, options) {\n // check for error: input data not a multiple of blockSize\n if(options.overflow > 0) {\n return false;\n }\n\n // ensure padding byte count is valid\n var len = output.length();\n var count = output.at(len - 1);\n if(count > (this.blockSize << 2)) {\n return false;\n }\n\n // trim off padding bytes\n output.truncate(count);\n return true;\n};\n\n/** Cipher feedback (CFB) **/\n\nmodes.cfb = function(options) {\n options = options || {};\n this.name = 'CFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32() ^ this._outBlock[i];\n output.putInt32(this._inBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];\n this._partialOutput.putInt32(this._partialBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.cfb.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output, write input as output\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = input.getInt32();\n output.putInt32(this._inBlock[i] ^ this._outBlock[i]);\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output, write input as partial output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialBlock[i] = input.getInt32();\n this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._partialBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\n/** Output feedback (OFB) **/\n\nmodes.ofb = function(options) {\n options = options || {};\n this.name = 'OFB';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(input.length() === 0) {\n return true;\n }\n\n // encrypt block (OFB always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output and update next input\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n this._inBlock[i] = this._outBlock[i];\n }\n return;\n }\n\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n } else {\n // block complete, update input block\n for(var i = 0; i < this._ints; ++i) {\n this._inBlock[i] = this._outBlock[i];\n }\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n};\n\nmodes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;\n\n/** Counter (CTR) **/\n\nmodes.ctr = function(options) {\n options = options || {};\n this.name = 'CTR';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = null;\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // use IV as first input\n this._iv = transformIV(options.iv, this.blockSize);\n this._inBlock = this._iv.slice(0);\n this._partialBytes = 0;\n};\n\nmodes.ctr.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block (CTR always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes > 0) {\n // block still incomplete, restore input buffer\n input.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // block complete, increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;\n\n/** Galois/Counter Mode (GCM) **/\n\nmodes.gcm = function(options) {\n options = options || {};\n this.name = 'GCM';\n this.cipher = options.cipher;\n this.blockSize = options.blockSize || 16;\n this._ints = this.blockSize / 4;\n this._inBlock = new Array(this._ints);\n this._outBlock = new Array(this._ints);\n this._partialOutput = forge.util.createBuffer();\n this._partialBytes = 0;\n\n // R is actually this value concatenated with 120 more zero bits, but\n // we only XOR against R so the other zeros have no effect -- we just\n // apply this value to the first integer in a block\n this._R = 0xE1000000;\n};\n\nmodes.gcm.prototype.start = function(options) {\n if(!('iv' in options)) {\n throw new Error('Invalid IV parameter.');\n }\n // ensure IV is a byte buffer\n var iv = forge.util.createBuffer(options.iv);\n\n // no ciphered data processed yet\n this._cipherLength = 0;\n\n // default additional data is none\n var additionalData;\n if('additionalData' in options) {\n additionalData = forge.util.createBuffer(options.additionalData);\n } else {\n additionalData = forge.util.createBuffer();\n }\n\n // default tag length is 128 bits\n if('tagLength' in options) {\n this._tagLength = options.tagLength;\n } else {\n this._tagLength = 128;\n }\n\n // if tag is given, ensure tag matches tag length\n this._tag = null;\n if(options.decrypt) {\n // save tag to check later\n this._tag = forge.util.createBuffer(options.tag).getBytes();\n if(this._tag.length !== (this._tagLength / 8)) {\n throw new Error('Authentication tag does not match tag length.');\n }\n }\n\n // create tmp storage for hash calculation\n this._hashBlock = new Array(this._ints);\n\n // no tag generated yet\n this.tag = null;\n\n // generate hash subkey\n // (apply block cipher to \"zero\" block)\n this._hashSubkey = new Array(this._ints);\n this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);\n\n // generate table M\n // use 4-bit tables (32 component decomposition of a 16 byte value)\n // 8-bit tables take more space and are known to have security\n // vulnerabilities (in native implementations)\n this.componentBits = 4;\n this._m = this.generateHashTable(this._hashSubkey, this.componentBits);\n\n // Note: support IV length different from 96 bits? (only supporting\n // 96 bits is recommended by NIST SP-800-38D)\n // generate J_0\n var ivLength = iv.length();\n if(ivLength === 12) {\n // 96-bit IV\n this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];\n } else {\n // IV is NOT 96-bits\n this._j0 = [0, 0, 0, 0];\n while(iv.length() > 0) {\n this._j0 = this.ghash(\n this._hashSubkey, this._j0,\n [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);\n }\n this._j0 = this.ghash(\n this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));\n }\n\n // generate ICB (initial counter block)\n this._inBlock = this._j0.slice(0);\n inc32(this._inBlock);\n this._partialBytes = 0;\n\n // consume authentication data\n additionalData = forge.util.createBuffer(additionalData);\n // save additional data length as a BE 64-bit number\n this._aDataLength = from64To32(additionalData.length() * 8);\n // pad additional data to 128 bit (16 byte) block size\n var overflow = additionalData.length() % this.blockSize;\n if(overflow) {\n additionalData.fillWithByte(0, this.blockSize - overflow);\n }\n this._s = [0, 0, 0, 0];\n while(additionalData.length() > 0) {\n this._s = this.ghash(this._hashSubkey, this._s, [\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32(),\n additionalData.getInt32()\n ]);\n }\n};\n\nmodes.gcm.prototype.encrypt = function(input, output, finish) {\n // not enough input to encrypt\n var inputLength = input.length();\n if(inputLength === 0) {\n return true;\n }\n\n // encrypt block\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // handle full block\n if(this._partialBytes === 0 && inputLength >= this.blockSize) {\n // XOR input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^= input.getInt32());\n }\n this._cipherLength += this.blockSize;\n } else {\n // handle partial block\n var partialBytes = (this.blockSize - inputLength) % this.blockSize;\n if(partialBytes > 0) {\n partialBytes = this.blockSize - partialBytes;\n }\n\n // XOR input with output\n this._partialOutput.clear();\n for(var i = 0; i < this._ints; ++i) {\n this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);\n }\n\n if(partialBytes <= 0 || finish) {\n // handle overflow prior to hashing\n if(finish) {\n // get block overflow\n var overflow = inputLength % this.blockSize;\n this._cipherLength += overflow;\n // truncate for hash function\n this._partialOutput.truncate(this.blockSize - overflow);\n } else {\n this._cipherLength += this.blockSize;\n }\n\n // get output block for hashing\n for(var i = 0; i < this._ints; ++i) {\n this._outBlock[i] = this._partialOutput.getInt32();\n }\n this._partialOutput.read -= this.blockSize;\n }\n\n // skip any previous partial bytes\n if(this._partialBytes > 0) {\n this._partialOutput.getBytes(this._partialBytes);\n }\n\n if(partialBytes > 0 && !finish) {\n // block still incomplete, restore input buffer, get partial output,\n // and return early\n input.read -= this.blockSize;\n output.putBytes(this._partialOutput.getBytes(\n partialBytes - this._partialBytes));\n this._partialBytes = partialBytes;\n return true;\n }\n\n output.putBytes(this._partialOutput.getBytes(\n inputLength - this._partialBytes));\n this._partialBytes = 0;\n }\n\n // update hash block S\n this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n};\n\nmodes.gcm.prototype.decrypt = function(input, output, finish) {\n // not enough input to decrypt\n var inputLength = input.length();\n if(inputLength < this.blockSize && !(finish && inputLength > 0)) {\n return true;\n }\n\n // encrypt block (GCM always uses encryption mode)\n this.cipher.encrypt(this._inBlock, this._outBlock);\n\n // increment counter (input block)\n inc32(this._inBlock);\n\n // update hash block S\n this._hashBlock[0] = input.getInt32();\n this._hashBlock[1] = input.getInt32();\n this._hashBlock[2] = input.getInt32();\n this._hashBlock[3] = input.getInt32();\n this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);\n\n // XOR hash input with output\n for(var i = 0; i < this._ints; ++i) {\n output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);\n }\n\n // increment cipher data length\n if(inputLength < this.blockSize) {\n this._cipherLength += inputLength % this.blockSize;\n } else {\n this._cipherLength += this.blockSize;\n }\n};\n\nmodes.gcm.prototype.afterFinish = function(output, options) {\n var rval = true;\n\n // handle overflow\n if(options.decrypt && options.overflow) {\n output.truncate(this.blockSize - options.overflow);\n }\n\n // handle authentication tag\n this.tag = forge.util.createBuffer();\n\n // concatenate additional data length with cipher length\n var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));\n\n // include lengths in hash\n this._s = this.ghash(this._hashSubkey, this._s, lengths);\n\n // do GCTR(J_0, S)\n var tag = [];\n this.cipher.encrypt(this._j0, tag);\n for(var i = 0; i < this._ints; ++i) {\n this.tag.putInt32(this._s[i] ^ tag[i]);\n }\n\n // trim tag to length\n this.tag.truncate(this.tag.length() % (this._tagLength / 8));\n\n // check authentication tag\n if(options.decrypt && this.tag.bytes() !== this._tag) {\n rval = false;\n }\n\n return rval;\n};\n\n/**\n * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois\n * field multiplication. The field, GF(2^128), is defined by the polynomial:\n *\n * x^128 + x^7 + x^2 + x + 1\n *\n * Which is represented in little-endian binary form as: 11100001 (0xe1). When\n * the value of a coefficient is 1, a bit is set. The value R, is the\n * concatenation of this value and 120 zero bits, yielding a 128-bit value\n * which matches the block size.\n *\n * This function will multiply two elements (vectors of bytes), X and Y, in\n * the field GF(2^128). The result is initialized to zero. For each bit of\n * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)\n * by the current value of Y. For each bit, the value of Y will be raised by\n * a power of x (multiplied by the polynomial x). This can be achieved by\n * shifting Y once to the right. If the current value of Y, prior to being\n * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.\n * Otherwise, we must divide by R after shifting to find the remainder.\n *\n * @param x the first block to multiply by the second.\n * @param y the second block to multiply by the first.\n *\n * @return the block result of the multiplication.\n */\nmodes.gcm.prototype.multiply = function(x, y) {\n var z_i = [0, 0, 0, 0];\n var v_i = y.slice(0);\n\n // calculate Z_128 (block has 128 bits)\n for(var i = 0; i < 128; ++i) {\n // if x_i is 0, Z_{i+1} = Z_i (unchanged)\n // else Z_{i+1} = Z_i ^ V_i\n // get x_i by finding 32-bit int position, then left shift 1 by remainder\n var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));\n if(x_i) {\n z_i[0] ^= v_i[0];\n z_i[1] ^= v_i[1];\n z_i[2] ^= v_i[2];\n z_i[3] ^= v_i[3];\n }\n\n // if LSB(V_i) is 1, V_i = V_i >> 1\n // else V_i = (V_i >> 1) ^ R\n this.pow(v_i, v_i);\n }\n\n return z_i;\n};\n\nmodes.gcm.prototype.pow = function(x, out) {\n // if LSB(x) is 1, x = x >>> 1\n // else x = (x >>> 1) ^ R\n var lsb = x[3] & 1;\n\n // always do x >>> 1:\n // starting with the rightmost integer, shift each integer to the right\n // one bit, pulling in the bit from the integer to the left as its top\n // most bit (do this for the last 3 integers)\n for(var i = 3; i > 0; --i) {\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);\n }\n // shift the first integer normally\n out[0] = x[0] >>> 1;\n\n // if lsb was not set, then polynomial had a degree of 127 and doesn't\n // need to divided; otherwise, XOR with R to find the remainder; we only\n // need to XOR the first integer since R technically ends w/120 zero bits\n if(lsb) {\n out[0] ^= this._R;\n }\n};\n\nmodes.gcm.prototype.tableMultiply = function(x) {\n // assumes 4-bit tables are used\n var z = [0, 0, 0, 0];\n for(var i = 0; i < 32; ++i) {\n var idx = (i / 8) | 0;\n var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;\n var ah = this._m[i][x_i];\n z[0] ^= ah[0];\n z[1] ^= ah[1];\n z[2] ^= ah[2];\n z[3] ^= ah[3];\n }\n return z;\n};\n\n/**\n * A continuing version of the GHASH algorithm that operates on a single\n * block. The hash block, last hash value (Ym) and the new block to hash\n * are given.\n *\n * @param h the hash block.\n * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.\n * @param x the block to hash.\n *\n * @return the hashed value (Ym).\n */\nmodes.gcm.prototype.ghash = function(h, y, x) {\n y[0] ^= x[0];\n y[1] ^= x[1];\n y[2] ^= x[2];\n y[3] ^= x[3];\n return this.tableMultiply(y);\n //return this.multiply(y, h);\n};\n\n/**\n * Precomputes a table for multiplying against the hash subkey. This\n * mechanism provides a substantial speed increase over multiplication\n * performed without a table. The table-based multiplication this table is\n * for solves X * H by multiplying each component of X by H and then\n * composing the results together using XOR.\n *\n * This function can be used to generate tables with different bit sizes\n * for the components, however, this implementation assumes there are\n * 32 components of X (which is a 16 byte vector), therefore each component\n * takes 4-bits (so the table is constructed with bits=4).\n *\n * @param h the hash subkey.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateHashTable = function(h, bits) {\n // TODO: There are further optimizations that would use only the\n // first table M_0 (or some variant) along with a remainder table;\n // this can be explored in the future\n var multiplier = 8 / bits;\n var perInt = 4 * multiplier;\n var size = 16 * multiplier;\n var m = new Array(size);\n for(var i = 0; i < size; ++i) {\n var tmp = [0, 0, 0, 0];\n var idx = (i / perInt) | 0;\n var shft = ((perInt - 1 - (i % perInt)) * bits);\n tmp[idx] = (1 << (bits - 1)) << shft;\n m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);\n }\n return m;\n};\n\n/**\n * Generates a table for multiplying against the hash subkey for one\n * particular component (out of all possible component values).\n *\n * @param mid the pre-multiplied value for the middle key of the table.\n * @param bits the bit size for a component.\n */\nmodes.gcm.prototype.generateSubHashTable = function(mid, bits) {\n // compute the table quickly by minimizing the number of\n // POW operations -- they only need to be performed for powers of 2,\n // all other entries can be composed from those powers using XOR\n var size = 1 << bits;\n var half = size >>> 1;\n var m = new Array(size);\n m[half] = mid.slice(0);\n var i = half >>> 1;\n while(i > 0) {\n // raise m0[2 * i] and store in m0[i]\n this.pow(m[2 * i], m[i] = []);\n i >>= 1;\n }\n i = 2;\n while(i < half) {\n for(var j = 1; j < i; ++j) {\n var m_i = m[i];\n var m_j = m[j];\n m[i + j] = [\n m_i[0] ^ m_j[0],\n m_i[1] ^ m_j[1],\n m_i[2] ^ m_j[2],\n m_i[3] ^ m_j[3]\n ];\n }\n i *= 2;\n }\n m[0] = [0, 0, 0, 0];\n /* Note: We could avoid storing these by doing composition during multiply\n calculate top half using composition by speed is preferred. */\n for(i = half + 1; i < size; ++i) {\n var c = m[i ^ half];\n m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];\n }\n return m;\n};\n\n/** Utility functions */\n\nfunction transformIV(iv, blockSize) {\n if(typeof iv === 'string') {\n // convert iv string into byte buffer\n iv = forge.util.createBuffer(iv);\n }\n\n if(forge.util.isArray(iv) && iv.length > 4) {\n // convert iv byte array into byte buffer\n var tmp = iv;\n iv = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n iv.putByte(tmp[i]);\n }\n }\n\n if(iv.length() < blockSize) {\n throw new Error(\n 'Invalid IV length; got ' + iv.length() +\n ' bytes and expected ' + blockSize + ' bytes.');\n }\n\n if(!forge.util.isArray(iv)) {\n // convert iv byte buffer into 32-bit integer array\n var ints = [];\n var blocks = blockSize / 4;\n for(var i = 0; i < blocks; ++i) {\n ints.push(iv.getInt32());\n }\n iv = ints;\n }\n\n return iv;\n}\n\nfunction inc32(block) {\n // increment last 32 bits of block only\n block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;\n}\n\nfunction from64To32(num) {\n // convert 64-bit number to two BE Int32s\n return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];\n}\n","/**\n * Advanced Encryption Standard (AES) implementation.\n *\n * This implementation is based on the public domain library 'jscrypto' which\n * was written by:\n *\n * Emily Stark (estark@stanford.edu)\n * Mike Hamburg (mhamburg@stanford.edu)\n * Dan Boneh (dabo@cs.stanford.edu)\n *\n * Parts of this code are based on the OpenSSL implementation of AES:\n * http://www.openssl.org\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* AES API */\nmodule.exports = forge.aes = forge.aes || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('AES-', key);\n *\n * Creates an AES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as a string of bytes, an array of bytes,\n * a byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('AES-', key);\n *\n * Creates an AES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param key the symmetric key to use.\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.aes.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new AES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the AES algorithm object.\n */\nforge.aes.Algorithm = function(name, mode) {\n if(!init) {\n initialize();\n }\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 16,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._w, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this AES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.aes.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = options.key;\n var tmp;\n\n /* Note: The key may be a string of bytes, an array of bytes, a byte\n buffer, or an array of 32-bit integers. If the key is in bytes, then\n it must be 16, 24, or 32 bytes in length. If it is in 32-bit\n integers, it must be 4, 6, or 8 integers long. */\n\n if(typeof key === 'string' &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key) &&\n (key.length === 16 || key.length === 24 || key.length === 32)) {\n // convert key integer array into byte buffer\n tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // convert key byte buffer into 32-bit integer array\n if(!forge.util.isArray(key)) {\n tmp = key;\n key = [];\n\n // key lengths of 16, 24, 32 bytes allowed\n var len = tmp.length();\n if(len === 16 || len === 24 || len === 32) {\n len = len >>> 2;\n for(var i = 0; i < len; ++i) {\n key.push(tmp.getInt32());\n }\n }\n }\n\n // key must be an array of 32-bit integers by now\n if(!forge.util.isArray(key) ||\n !(key.length === 4 || key.length === 6 || key.length === 8)) {\n throw new Error('Invalid key parameter.');\n }\n\n // encryption operation is always used for these modes\n var mode = this.mode.name;\n var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);\n\n // do key expansion\n this._w = _expandKey(key, options.decrypt && !encryptOp);\n this._init = true;\n};\n\n/**\n * Expands a key. Typically only used for testing.\n *\n * @param key the symmetric key to expand, as an array of 32-bit words.\n * @param decrypt true to expand for decryption, false for encryption.\n *\n * @return the expanded key.\n */\nforge.aes._expandKey = function(key, decrypt) {\n if(!init) {\n initialize();\n }\n return _expandKey(key, decrypt);\n};\n\n/**\n * Updates a single block. Typically only used for testing.\n *\n * @param w the expanded key to use.\n * @param input an array of block-size 32-bit words.\n * @param output an array of block-size 32-bit words.\n * @param decrypt true to decrypt, false to encrypt.\n */\nforge.aes._updateBlock = _updateBlock;\n\n/** Register AES algorithms **/\n\nregisterAlgorithm('AES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('AES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('AES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('AES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('AES-CTR', forge.cipher.modes.ctr);\nregisterAlgorithm('AES-GCM', forge.cipher.modes.gcm);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.aes.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** AES implementation **/\n\nvar init = false; // not yet initialized\nvar Nb = 4; // number of words comprising the state (AES = 4)\nvar sbox; // non-linear substitution table used in key expansion\nvar isbox; // inversion of sbox\nvar rcon; // round constant word array\nvar mix; // mix-columns table\nvar imix; // inverse mix-columns table\n\n/**\n * Performs initialization, ie: precomputes tables to optimize for speed.\n *\n * One way to understand how AES works is to imagine that 'addition' and\n * 'multiplication' are interfaces that require certain mathematical\n * properties to hold true (ie: they are associative) but they might have\n * different implementations and produce different kinds of results ...\n * provided that their mathematical properties remain true. AES defines\n * its own methods of addition and multiplication but keeps some important\n * properties the same, ie: associativity and distributivity. The\n * explanation below tries to shed some light on how AES defines addition\n * and multiplication of bytes and 32-bit words in order to perform its\n * encryption and decryption algorithms.\n *\n * The basics:\n *\n * The AES algorithm views bytes as binary representations of polynomials\n * that have either 1 or 0 as the coefficients. It defines the addition\n * or subtraction of two bytes as the XOR operation. It also defines the\n * multiplication of two bytes as a finite field referred to as GF(2^8)\n * (Note: 'GF' means \"Galois Field\" which is a field that contains a finite\n * number of elements so GF(2^8) has 256 elements).\n *\n * This means that any two bytes can be represented as binary polynomials;\n * when they multiplied together and modularly reduced by an irreducible\n * polynomial of the 8th degree, the results are the field GF(2^8). The\n * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.\n * This multiplication is associative with 0x01 as the identity:\n *\n * (b * 0x01 = GF(b, 0x01) = b).\n *\n * The operation GF(b, 0x02) can be performed at the byte level by left\n * shifting b once and then XOR'ing it (to perform the modular reduction)\n * with 0x11b if b is >= 128. Repeated application of the multiplication\n * of 0x02 can be used to implement the multiplication of any two bytes.\n *\n * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can\n * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these\n * factors can each be multiplied by 0x57 and then added together. To do\n * the multiplication, values for 0x57 multiplied by each of these 3 factors\n * can be precomputed and stored in a table. To add them, the values from\n * the table are XOR'd together.\n *\n * AES also defines addition and multiplication of words, that is 4-byte\n * numbers represented as polynomials of 3 degrees where the coefficients\n * are the values of the bytes.\n *\n * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.\n *\n * Addition is performed by XOR'ing like powers of x. Multiplication\n * is performed in two steps, the first is an algebriac expansion as\n * you would do normally (where addition is XOR). But the result is\n * a polynomial larger than 3 degrees and thus it cannot fit in a word. So\n * next the result is modularly reduced by an AES-specific polynomial of\n * degree 4 which will always produce a polynomial of less than 4 degrees\n * such that it will fit in a word. In AES, this polynomial is x^4 + 1.\n *\n * The modular product of two polynomials 'a' and 'b' is thus:\n *\n * d(x) = d3x^3 + d2x^2 + d1x + d0\n * with\n * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)\n * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)\n * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)\n * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)\n *\n * As a matrix:\n *\n * [d0] = [a0 a3 a2 a1][b0]\n * [d1] [a1 a0 a3 a2][b1]\n * [d2] [a2 a1 a0 a3][b2]\n * [d3] [a3 a2 a1 a0][b3]\n *\n * Special polynomials defined by AES (0x02 == {02}):\n * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}\n * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.\n *\n * These polynomials are used in the MixColumns() and InverseMixColumns()\n * operations, respectively, to cause each element in the state to affect\n * the output (referred to as diffusing).\n *\n * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the\n * polynomial x3.\n *\n * The ShiftRows() method modifies the last 3 rows in the state (where\n * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.\n * The 1st byte in the second row is moved to the end of the row. The 1st\n * and 2nd bytes in the third row are moved to the end of the row. The 1st,\n * 2nd, and 3rd bytes are moved in the fourth row.\n *\n * More details on how AES arithmetic works:\n *\n * In the polynomial representation of binary numbers, XOR performs addition\n * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)\n * corresponds with the multiplication of polynomials modulo an irreducible\n * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply\n * polynomial 'a' with polynomial 'b' and then do a modular reduction by\n * an AES-specific irreducible polynomial of degree 8.\n *\n * A polynomial is irreducible if its only divisors are one and itself. For\n * the AES algorithm, this irreducible polynomial is:\n *\n * m(x) = x^8 + x^4 + x^3 + x + 1,\n *\n * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:\n * 100011011 = 283 = 0x11b.\n *\n * For example, GF(0x57, 0x83) = 0xc1 because\n *\n * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1\n * 0x85 = 131 = 10000101 = x^7 + x + 1\n *\n * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)\n * = x^13 + x^11 + x^9 + x^8 + x^7 +\n * x^7 + x^5 + x^3 + x^2 + x +\n * x^6 + x^4 + x^2 + x + 1\n * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y\n * y modulo (x^8 + x^4 + x^3 + x + 1)\n * = x^7 + x^6 + 1.\n *\n * The modular reduction by m(x) guarantees the result will be a binary\n * polynomial of less than degree 8, so that it can fit in a byte.\n *\n * The operation to multiply a binary polynomial b with x (the polynomial\n * x in binary representation is 00000010) is:\n *\n * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1\n *\n * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the\n * most significant bit is 0 in b) then the result is already reduced. If\n * it is 1, then we can reduce it by subtracting m(x) via an XOR.\n *\n * It follows that multiplication by x (00000010 or 0x02) can be implemented\n * by performing a left shift followed by a conditional bitwise XOR with\n * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by\n * higher powers of x can be implemented by repeated application of xtime().\n *\n * By adding intermediate results, multiplication by any constant can be\n * implemented. For instance:\n *\n * GF(0x57, 0x13) = 0xfe because:\n *\n * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)\n *\n * Note: We XOR with 0x11b instead of 0x1b because in javascript our\n * datatype for b can be larger than 1 byte, so a left shift will not\n * automatically eliminate bits that overflow a byte ... by XOR'ing the\n * overflow bit with 1 (the extra one from 0x11b) we zero it out.\n *\n * GF(0x57, 0x02) = xtime(0x57) = 0xae\n * GF(0x57, 0x04) = xtime(0xae) = 0x47\n * GF(0x57, 0x08) = xtime(0x47) = 0x8e\n * GF(0x57, 0x10) = xtime(0x8e) = 0x07\n *\n * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))\n *\n * And by the distributive property (since XOR is addition and GF() is\n * multiplication):\n *\n * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)\n * = 0x57 ^ 0xae ^ 0x07\n * = 0xfe.\n */\nfunction initialize() {\n init = true;\n\n /* Populate the Rcon table. These are the values given by\n [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)\n in the field of GF(2^8), where i starts at 1.\n\n rcon[0] = [0x00, 0x00, 0x00, 0x00]\n rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1\n rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2\n ...\n rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B\n rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36\n\n We only store the first byte because it is the only one used.\n */\n rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];\n\n // compute xtime table which maps i onto GF(i, 0x02)\n var xtime = new Array(256);\n for(var i = 0; i < 128; ++i) {\n xtime[i] = i << 1;\n xtime[i + 128] = (i + 128) << 1 ^ 0x11B;\n }\n\n // compute all other tables\n sbox = new Array(256);\n isbox = new Array(256);\n mix = new Array(4);\n imix = new Array(4);\n for(var i = 0; i < 4; ++i) {\n mix[i] = new Array(256);\n imix[i] = new Array(256);\n }\n var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;\n for(var i = 0; i < 256; ++i) {\n /* We need to generate the SubBytes() sbox and isbox tables so that\n we can perform byte substitutions. This requires us to traverse\n all of the elements in GF, find their multiplicative inverses,\n and apply to each the following affine transformation:\n\n bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^\n b(i + 7) mod 8 ^ ci\n for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the\n ith bit of a byte c with the value {63} or {01100011}.\n\n It is possible to traverse every possible value in a Galois field\n using what is referred to as a 'generator'. There are many\n generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully\n traverse GF we iterate 255 times, multiplying by our generator\n each time.\n\n On each iteration we can determine the multiplicative inverse for\n the current element.\n\n Suppose there is an element in GF 'e'. For a given generator 'g',\n e = g^x. The multiplicative inverse of e is g^(255 - x). It turns\n out that if use the inverse of a generator as another generator\n it will produce all of the corresponding multiplicative inverses\n at the same time. For this reason, we choose 5 as our inverse\n generator because it only requires 2 multiplies and 1 add and its\n inverse, 82, requires relatively few operations as well.\n\n In order to apply the affine transformation, the multiplicative\n inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a\n bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and\n 'x'. Then 's' is left shifted and the high bit of 's' is made the\n low bit. The resulting value is stored in 's'. Then 'x' is XOR'd\n with 's' and stored in 'x'. On each subsequent iteration the same\n operation is performed. When 4 iterations are complete, 'x' is\n XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.\n For example:\n\n s = 01000001\n x = 01000001\n\n iteration 1: s = 10000010, x ^= s\n iteration 2: s = 00000101, x ^= s\n iteration 3: s = 00001010, x ^= s\n iteration 4: s = 00010100, x ^= s\n x ^= 0x63\n\n This can be done with a loop where s = (s << 1) | (s >> 7). However,\n it can also be done by using a single 16-bit (in this case 32-bit)\n number 'sx'. Since XOR is an associative operation, we can set 'sx'\n to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.\n The most significant bits will flow into the high 8 bit positions\n and be correctly XOR'd with one another. All that remains will be\n to cycle the high 8 bits by XOR'ing them all with the lower 8 bits\n afterwards.\n\n At the same time we're populating sbox and isbox we can precompute\n the multiplication we'll need to do to do MixColumns() later.\n */\n\n // apply affine transformation\n sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);\n sx = (sx >> 8) ^ (sx & 255) ^ 0x63;\n\n // update tables\n sbox[e] = sx;\n isbox[sx] = e;\n\n /* Mixing columns is done using matrix multiplication. The columns\n that are to be mixed are each a single word in the current state.\n The state has Nb columns (4 columns). Therefore each column is a\n 4 byte word. So to mix the columns in a single column 'c' where\n its rows are r0, r1, r2, and r3, we use the following matrix\n multiplication:\n\n [2 3 1 1]*[r0,c]=[r'0,c]\n [1 2 3 1] [r1,c] [r'1,c]\n [1 1 2 3] [r2,c] [r'2,c]\n [3 1 1 2] [r3,c] [r'3,c]\n\n r0, r1, r2, and r3 are each 1 byte of one of the words in the\n state (a column). To do matrix multiplication for each mixed\n column c' we multiply the corresponding row from the left matrix\n with the corresponding column from the right matrix. In total, we\n get 4 equations:\n\n r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c\n r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c\n r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c\n r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c\n\n As usual, the multiplication is as previously defined and the\n addition is XOR. In order to optimize mixing columns we can store\n the multiplication results in tables. If you think of the whole\n column as a word (it might help to visualize by mentally rotating\n the equations above by counterclockwise 90 degrees) then you can\n see that it would be useful to map the multiplications performed on\n each byte (r0, r1, r2, r3) onto a word as well. For instance, we\n could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the\n highest 8 bits and 3*r0 in the lowest 8 bits (with the other two\n respectively in the middle). This means that a table can be\n constructed that uses r0 as an index to the word. We can do the\n same with r1, r2, and r3, creating a total of 4 tables.\n\n To construct a full c', we can just look up each byte of c in\n their respective tables and XOR the results together.\n\n Also, to build each table we only have to calculate the word\n for 2,1,1,3 for every byte ... which we can do on each iteration\n of this loop since we will iterate over every byte. After we have\n calculated 2,1,1,3 we can get the results for the other tables\n by cycling the byte at the end to the beginning. For instance\n we can take the result of table 2,1,1,3 and produce table 3,2,1,1\n by moving the right most byte to the left most position just like\n how you can imagine the 3 moved out of 2,1,1,3 and to the front\n to produce 3,2,1,1.\n\n There is another optimization in that the same multiples of\n the current element we need in order to advance our generator\n to the next iteration can be reused in performing the 2,1,1,3\n calculation. We also calculate the inverse mix column tables,\n with e,9,d,b being the inverse of 2,1,1,3.\n\n When we're done, and we need to actually mix columns, the first\n byte of each state word should be put through mix[0] (2,1,1,3),\n the second through mix[1] (3,2,1,1) and so forth. Then they should\n be XOR'd together to produce the fully mixed column.\n */\n\n // calculate mix and imix table values\n sx2 = xtime[sx];\n e2 = xtime[e];\n e4 = xtime[e2];\n e8 = xtime[e4];\n me =\n (sx2 << 24) ^ // 2\n (sx << 16) ^ // 1\n (sx << 8) ^ // 1\n (sx ^ sx2); // 3\n ime =\n (e2 ^ e4 ^ e8) << 24 ^ // E (14)\n (e ^ e8) << 16 ^ // 9\n (e ^ e4 ^ e8) << 8 ^ // D (13)\n (e ^ e2 ^ e8); // B (11)\n // produce each of the mix tables by rotating the 2,1,1,3 value\n for(var n = 0; n < 4; ++n) {\n mix[n][e] = me;\n imix[n][sx] = ime;\n // cycle the right most byte to the left most position\n // ie: 2,1,1,3 becomes 3,2,1,1\n me = me << 24 | me >>> 8;\n ime = ime << 24 | ime >>> 8;\n }\n\n // get next element and inverse\n if(e === 0) {\n // 1 is the inverse of 1\n e = ei = 1;\n } else {\n // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)\n // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)\n e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];\n ei ^= xtime[xtime[ei]];\n }\n }\n}\n\n/**\n * Generates a key schedule using the AES key expansion algorithm.\n *\n * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion\n * routine to generate a key schedule. The Key Expansion generates a total\n * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,\n * and each of the Nr rounds requires Nb words of key data. The resulting\n * key schedule consists of a linear array of 4-byte words, denoted [wi ],\n * with i in the range 0 <= i < Nb(Nr + 1).\n *\n * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)\n * AES-128 (Nb=4, Nk=4, Nr=10)\n * AES-192 (Nb=4, Nk=6, Nr=12)\n * AES-256 (Nb=4, Nk=8, Nr=14)\n * Note: Nr=Nk+6.\n *\n * Nb is the number of columns (32-bit words) comprising the State (or\n * number of bytes in a block). For AES, Nb=4.\n *\n * @param key the key to schedule (as an array of 32-bit words).\n * @param decrypt true to modify the key schedule to decrypt, false not to.\n *\n * @return the generated key schedule.\n */\nfunction _expandKey(key, decrypt) {\n // copy the key's words to initialize the key schedule\n var w = key.slice(0);\n\n /* RotWord() will rotate a word, moving the first byte to the last\n byte's position (shifting the other bytes left).\n\n We will be getting the value of Rcon at i / Nk. 'i' will iterate\n from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in\n a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from\n 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will\n increase by 1. We use a counter iNk to keep track of this.\n */\n\n // go through the rounds expanding the key\n var temp, iNk = 1;\n var Nk = w.length;\n var Nr1 = Nk + 6 + 1;\n var end = Nb * Nr1;\n for(var i = Nk; i < end; ++i) {\n temp = w[i - 1];\n if(i % Nk === 0) {\n // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]\n temp =\n sbox[temp >>> 16 & 255] << 24 ^\n sbox[temp >>> 8 & 255] << 16 ^\n sbox[temp & 255] << 8 ^\n sbox[temp >>> 24] ^ (rcon[iNk] << 24);\n iNk++;\n } else if(Nk > 6 && (i % Nk === 4)) {\n // temp = SubWord(temp)\n temp =\n sbox[temp >>> 24] << 24 ^\n sbox[temp >>> 16 & 255] << 16 ^\n sbox[temp >>> 8 & 255] << 8 ^\n sbox[temp & 255];\n }\n w[i] = w[i - Nk] ^ temp;\n }\n\n /* When we are updating a cipher block we always use the code path for\n encryption whether we are decrypting or not (to shorten code and\n simplify the generation of look up tables). However, because there\n are differences in the decryption algorithm, other than just swapping\n in different look up tables, we must transform our key schedule to\n account for these changes:\n\n 1. The decryption algorithm gets its key rounds in reverse order.\n 2. The decryption algorithm adds the round key before mixing columns\n instead of afterwards.\n\n We don't need to modify our key schedule to handle the first case,\n we can just traverse the key schedule in reverse order when decrypting.\n\n The second case requires a little work.\n\n The tables we built for performing rounds will take an input and then\n perform SubBytes() and MixColumns() or, for the decrypt version,\n InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires\n us to AddRoundKey() before InvMixColumns(). This means we'll need to\n apply some transformations to the round key to inverse-mix its columns\n so they'll be correct for moving AddRoundKey() to after the state has\n had its columns inverse-mixed.\n\n To inverse-mix the columns of the state when we're decrypting we use a\n lookup table that will apply InvSubBytes() and InvMixColumns() at the\n same time. However, the round key's bytes are not inverse-substituted\n in the decryption algorithm. To get around this problem, we can first\n substitute the bytes in the round key so that when we apply the\n transformation via the InvSubBytes()+InvMixColumns() table, it will\n undo our substitution leaving us with the original value that we\n want -- and then inverse-mix that value.\n\n This change will correctly alter our key schedule so that we can XOR\n each round key with our already transformed decryption state. This\n allows us to use the same code path as the encryption algorithm.\n\n We make one more change to the decryption key. Since the decryption\n algorithm runs in reverse from the encryption algorithm, we reverse\n the order of the round keys to avoid having to iterate over the key\n schedule backwards when running the encryption algorithm later in\n decryption mode. In addition to reversing the order of the round keys,\n we also swap each round key's 2nd and 4th rows. See the comments\n section where rounds are performed for more details about why this is\n done. These changes are done inline with the other substitution\n described above.\n */\n if(decrypt) {\n var tmp;\n var m0 = imix[0];\n var m1 = imix[1];\n var m2 = imix[2];\n var m3 = imix[3];\n var wnew = w.slice(0);\n end = w.length;\n for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {\n // do not sub the first or last round key (round keys are Nb\n // words) as no column mixing is performed before they are added,\n // but do change the key order\n if(i === 0 || i === (end - Nb)) {\n wnew[i] = w[wi];\n wnew[i + 1] = w[wi + 3];\n wnew[i + 2] = w[wi + 2];\n wnew[i + 3] = w[wi + 1];\n } else {\n // substitute each round key byte because the inverse-mix\n // table will inverse-substitute it (effectively cancel the\n // substitution because round key bytes aren't sub'd in\n // decryption mode) and swap indexes 3 and 1\n for(var n = 0; n < Nb; ++n) {\n tmp = w[wi + n];\n wnew[i + (3&-n)] =\n m0[sbox[tmp >>> 24]] ^\n m1[sbox[tmp >>> 16 & 255]] ^\n m2[sbox[tmp >>> 8 & 255]] ^\n m3[sbox[tmp & 255]];\n }\n }\n }\n w = wnew;\n }\n\n return w;\n}\n\n/**\n * Updates a single block (16 bytes) using AES. The update will either\n * encrypt or decrypt the block.\n *\n * @param w the key schedule.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(w, input, output, decrypt) {\n /*\n Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[0, Nb-1])\n for round = 1 step 1 to Nr-1\n SubBytes(state)\n ShiftRows(state)\n MixColumns(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n end for\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n out = state\n end\n\n InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])\n begin\n byte state[4,Nb]\n state = in\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n for round = Nr-1 step -1 downto 1\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])\n InvMixColumns(state)\n end for\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n out = state\n end\n */\n\n // Encrypt: AddRoundKey(state, w[0, Nb-1])\n // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n var Nr = w.length / 4 - 1;\n var m0, m1, m2, m3, sub;\n if(decrypt) {\n m0 = imix[0];\n m1 = imix[1];\n m2 = imix[2];\n m3 = imix[3];\n sub = isbox;\n } else {\n m0 = mix[0];\n m1 = mix[1];\n m2 = mix[2];\n m3 = mix[3];\n sub = sbox;\n }\n var a, b, c, d, a2, b2, c2;\n a = input[0] ^ w[0];\n b = input[decrypt ? 3 : 1] ^ w[1];\n c = input[2] ^ w[2];\n d = input[decrypt ? 1 : 3] ^ w[3];\n var i = 3;\n\n /* In order to share code we follow the encryption algorithm when both\n encrypting and decrypting. To account for the changes required in the\n decryption algorithm, we use different lookup tables when decrypting\n and use a modified key schedule to account for the difference in the\n order of transformations applied when performing rounds. We also get\n key rounds in reverse order (relative to encryption). */\n for(var round = 1; round < Nr; ++round) {\n /* As described above, we'll be using table lookups to perform the\n column mixing. Each column is stored as a word in the state (the\n array 'input' has one column as a word at each index). In order to\n mix a column, we perform these transformations on each row in c,\n which is 1 byte in each word. The new column for c0 is c'0:\n\n m0 m1 m2 m3\n r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0\n r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0\n r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0\n r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0\n\n So using mix tables where c0 is a word with r0 being its upper\n 8 bits and r3 being its lower 8 bits:\n\n m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]\n ...\n m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]\n\n Therefore to mix the columns in each word in the state we\n do the following (& 255 omitted for brevity):\n c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]\n\n However, before mixing, the algorithm requires us to perform\n ShiftRows(). The ShiftRows() transformation cyclically shifts the\n last 3 rows of the state over different offsets. The first row\n (r = 0) is not shifted.\n\n s'_r,c = s_r,(c + shift(r, Nb) mod Nb\n for 0 < r < 4 and 0 <= c < Nb and\n shift(1, 4) = 1\n shift(2, 4) = 2\n shift(3, 4) = 3.\n\n This causes the first byte in r = 1 to be moved to the end of\n the row, the first 2 bytes in r = 2 to be moved to the end of\n the row, the first 3 bytes in r = 3 to be moved to the end of\n the row:\n\n r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]\n r2: [c0 c1 c2 c3] [c2 c3 c0 c1]\n r3: [c0 c1 c2 c3] [c3 c0 c1 c2]\n\n We can make these substitutions inline with our column mixing to\n generate an updated set of equations to produce each word in the\n state (note the columns have changed positions):\n\n c0 c1 c2 c3 => c0 c1 c2 c3\n c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)\n c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)\n c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)\n\n Therefore:\n\n c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3\n c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3\n c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3\n\n c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0\n c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0\n c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0\n\n ... and so forth for c'2 and c'3. The important distinction is\n that the columns are cycling, with c0 being used with the m0\n map when calculating c0, but c1 being used with the m0 map when\n calculating c1 ... and so forth.\n\n When performing the inverse we transform the mirror image and\n skip the bottom row, instead of the top one, and move upwards:\n\n c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption\n c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)\n c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption\n c3 c2 c1 c0 c3 c2 c1 c0\n\n If you compare the resulting matrices for ShiftRows()+MixColumns()\n and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are\n different (in encrypt mode vs. decrypt mode). So in order to use\n the same code to handle both encryption and decryption, we will\n need to do some mapping.\n\n If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be\n a row number in the state, then the resulting matrix in encryption\n mode for applying the above transformations would be:\n\n r1: a b c d\n r2: b c d a\n r3: c d a b\n r4: d a b c\n\n If we did the same in decryption mode we would get:\n\n r1: a d c b\n r2: b a d c\n r3: c b a d\n r4: d c b a\n\n If instead we swap d and b (set b=c3 and d=c1), then we get:\n\n r1: a b c d\n r2: d a b c\n r3: c d a b\n r4: b c d a\n\n Now the 1st and 3rd rows are the same as the encryption matrix. All\n we need to do then to make the mapping exactly the same is to swap\n the 2nd and 4th rows when in decryption mode. To do this without\n having to do it on each iteration, we swapped the 2nd and 4th rows\n in the decryption key schedule. We also have to do the swap above\n when we first pull in the input and when we set the final output. */\n a2 =\n m0[a >>> 24] ^\n m1[b >>> 16 & 255] ^\n m2[c >>> 8 & 255] ^\n m3[d & 255] ^ w[++i];\n b2 =\n m0[b >>> 24] ^\n m1[c >>> 16 & 255] ^\n m2[d >>> 8 & 255] ^\n m3[a & 255] ^ w[++i];\n c2 =\n m0[c >>> 24] ^\n m1[d >>> 16 & 255] ^\n m2[a >>> 8 & 255] ^\n m3[b & 255] ^ w[++i];\n d =\n m0[d >>> 24] ^\n m1[a >>> 16 & 255] ^\n m2[b >>> 8 & 255] ^\n m3[c & 255] ^ w[++i];\n a = a2;\n b = b2;\n c = c2;\n }\n\n /*\n Encrypt:\n SubBytes(state)\n ShiftRows(state)\n AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])\n\n Decrypt:\n InvShiftRows(state)\n InvSubBytes(state)\n AddRoundKey(state, w[0, Nb-1])\n */\n // Note: rows are shifted inline\n output[0] =\n (sub[a >>> 24] << 24) ^\n (sub[b >>> 16 & 255] << 16) ^\n (sub[c >>> 8 & 255] << 8) ^\n (sub[d & 255]) ^ w[++i];\n output[decrypt ? 3 : 1] =\n (sub[b >>> 24] << 24) ^\n (sub[c >>> 16 & 255] << 16) ^\n (sub[d >>> 8 & 255] << 8) ^\n (sub[a & 255]) ^ w[++i];\n output[2] =\n (sub[c >>> 24] << 24) ^\n (sub[d >>> 16 & 255] << 16) ^\n (sub[a >>> 8 & 255] << 8) ^\n (sub[b & 255]) ^ w[++i];\n output[decrypt ? 1 : 3] =\n (sub[d >>> 24] << 24) ^\n (sub[a >>> 16 & 255] << 16) ^\n (sub[b >>> 8 & 255] << 8) ^\n (sub[c & 255]) ^ w[++i];\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('AES-', key);\n * forge.cipher.createDecipher('AES-', key);\n *\n * Creates a deprecated AES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key and iv may be given as a string of bytes, an array of bytes, a\n * byte buffer, or an array of 32-bit words.\n *\n * @param options the options to use.\n * key the symmetric key to use.\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'AES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * Object IDs for ASN.1.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nforge.pki = forge.pki || {};\nvar oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};\n\n// set id to name mapping and name to id mapping\nfunction _IN(id, name) {\n oids[id] = name;\n oids[name] = id;\n}\n// set id to name mapping only\nfunction _I_(id, name) {\n oids[id] = name;\n}\n\n// algorithm OIDs\n_IN('1.2.840.113549.1.1.1', 'rsaEncryption');\n// Note: md2 & md4 not implemented\n//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');\n//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');\n_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');\n_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');\n_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');\n_IN('1.2.840.113549.1.1.8', 'mgf1');\n_IN('1.2.840.113549.1.1.9', 'pSpecified');\n_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');\n_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');\n_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');\n_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');\n// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519\n_IN('1.3.101.112', 'EdDSA25519');\n\n_IN('1.2.840.10040.4.3', 'dsa-with-sha1');\n\n_IN('1.3.14.3.2.7', 'desCBC');\n\n_IN('1.3.14.3.2.26', 'sha1');\n_IN('2.16.840.1.101.3.4.2.1', 'sha256');\n_IN('2.16.840.1.101.3.4.2.2', 'sha384');\n_IN('2.16.840.1.101.3.4.2.3', 'sha512');\n_IN('1.2.840.113549.2.5', 'md5');\n\n// pkcs#7 content types\n_IN('1.2.840.113549.1.7.1', 'data');\n_IN('1.2.840.113549.1.7.2', 'signedData');\n_IN('1.2.840.113549.1.7.3', 'envelopedData');\n_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');\n_IN('1.2.840.113549.1.7.5', 'digestedData');\n_IN('1.2.840.113549.1.7.6', 'encryptedData');\n\n// pkcs#9 oids\n_IN('1.2.840.113549.1.9.1', 'emailAddress');\n_IN('1.2.840.113549.1.9.2', 'unstructuredName');\n_IN('1.2.840.113549.1.9.3', 'contentType');\n_IN('1.2.840.113549.1.9.4', 'messageDigest');\n_IN('1.2.840.113549.1.9.5', 'signingTime');\n_IN('1.2.840.113549.1.9.6', 'counterSignature');\n_IN('1.2.840.113549.1.9.7', 'challengePassword');\n_IN('1.2.840.113549.1.9.8', 'unstructuredAddress');\n_IN('1.2.840.113549.1.9.14', 'extensionRequest');\n\n_IN('1.2.840.113549.1.9.20', 'friendlyName');\n_IN('1.2.840.113549.1.9.21', 'localKeyId');\n_IN('1.2.840.113549.1.9.22.1', 'x509Certificate');\n\n// pkcs#12 safe bags\n_IN('1.2.840.113549.1.12.10.1.1', 'keyBag');\n_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');\n_IN('1.2.840.113549.1.12.10.1.3', 'certBag');\n_IN('1.2.840.113549.1.12.10.1.4', 'crlBag');\n_IN('1.2.840.113549.1.12.10.1.5', 'secretBag');\n_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');\n\n// password-based-encryption for pkcs#12\n_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');\n_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');\n\n_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');\n_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');\n_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');\n_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');\n_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');\n\n// hmac OIDs\n_IN('1.2.840.113549.2.7', 'hmacWithSHA1');\n_IN('1.2.840.113549.2.8', 'hmacWithSHA224');\n_IN('1.2.840.113549.2.9', 'hmacWithSHA256');\n_IN('1.2.840.113549.2.10', 'hmacWithSHA384');\n_IN('1.2.840.113549.2.11', 'hmacWithSHA512');\n\n// symmetric key algorithm oids\n_IN('1.2.840.113549.3.7', 'des-EDE3-CBC');\n_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');\n_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');\n_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');\n\n// certificate issuer/subject OIDs\n_IN('2.5.4.3', 'commonName');\n_IN('2.5.4.5', 'serialName');\n_IN('2.5.4.6', 'countryName');\n_IN('2.5.4.7', 'localityName');\n_IN('2.5.4.8', 'stateOrProvinceName');\n_IN('2.5.4.9', 'streetAddress');\n_IN('2.5.4.10', 'organizationName');\n_IN('2.5.4.11', 'organizationalUnitName');\n_IN('2.5.4.13', 'description');\n_IN('2.5.4.15', 'businessCategory');\n_IN('2.5.4.17', 'postalCode');\n_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');\n_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');\n\n// X.509 extension OIDs\n_IN('2.16.840.1.113730.1.1', 'nsCertType');\n_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used\n_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35\n_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15\n_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32\n_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15\n_I_('2.5.29.5', 'policyMapping'); // deprecated use .33\n_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30\n_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17\n_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18\n_I_('2.5.29.9', 'subjectDirectoryAttributes');\n_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19\n_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30\n_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36\n_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19\n_IN('2.5.29.14', 'subjectKeyIdentifier');\n_IN('2.5.29.15', 'keyUsage');\n_I_('2.5.29.16', 'privateKeyUsagePeriod');\n_IN('2.5.29.17', 'subjectAltName');\n_IN('2.5.29.18', 'issuerAltName');\n_IN('2.5.29.19', 'basicConstraints');\n_I_('2.5.29.20', 'cRLNumber');\n_I_('2.5.29.21', 'cRLReason');\n_I_('2.5.29.22', 'expirationDate');\n_I_('2.5.29.23', 'instructionCode');\n_I_('2.5.29.24', 'invalidityDate');\n_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31\n_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28\n_I_('2.5.29.27', 'deltaCRLIndicator');\n_I_('2.5.29.28', 'issuingDistributionPoint');\n_I_('2.5.29.29', 'certificateIssuer');\n_I_('2.5.29.30', 'nameConstraints');\n_IN('2.5.29.31', 'cRLDistributionPoints');\n_IN('2.5.29.32', 'certificatePolicies');\n_I_('2.5.29.33', 'policyMappings');\n_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36\n_IN('2.5.29.35', 'authorityKeyIdentifier');\n_I_('2.5.29.36', 'policyConstraints');\n_IN('2.5.29.37', 'extKeyUsage');\n_I_('2.5.29.46', 'freshestCRL');\n_I_('2.5.29.54', 'inhibitAnyPolicy');\n\n// extKeyUsage purposes\n_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');\n_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');\n_IN('1.3.6.1.5.5.7.3.1', 'serverAuth');\n_IN('1.3.6.1.5.5.7.3.2', 'clientAuth');\n_IN('1.3.6.1.5.5.7.3.3', 'codeSigning');\n_IN('1.3.6.1.5.5.7.3.4', 'emailProtection');\n_IN('1.3.6.1.5.5.7.3.8', 'timeStamping');\n","/**\n * Javascript implementation of Abstract Syntax Notation Number One.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n *\n * An API for storing data using the Abstract Syntax Notation Number One\n * format using DER (Distinguished Encoding Rules) encoding. This encoding is\n * commonly used to store data for PKI, i.e. X.509 Certificates, and this\n * implementation exists for that purpose.\n *\n * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract\n * syntax of information without restricting the way the information is encoded\n * for transmission. It provides a standard that allows for open systems\n * communication. ASN.1 defines the syntax of information data and a number of\n * simple data types as well as a notation for describing them and specifying\n * values for them.\n *\n * The RSA algorithm creates public and private keys that are often stored in\n * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This\n * class provides the most basic functionality required to store and load DSA\n * keys that are encoded according to ASN.1.\n *\n * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)\n * and DER (Distinguished Encoding Rules). DER is just a subset of BER that\n * has stricter requirements for how data must be encoded.\n *\n * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)\n * and a byte array for the value of this ASN1 structure which may be data or a\n * list of ASN.1 structures.\n *\n * Each ASN.1 structure using BER is (Tag-Length-Value):\n *\n * | byte 0 | bytes X | bytes Y |\n * |--------|---------|----------\n * | tag | length | value |\n *\n * ASN.1 allows for tags to be of \"High-tag-number form\" which allows a tag to\n * be two or more octets, but that is not supported by this class. A tag is\n * only 1 byte. Bits 1-5 give the tag number (ie the data type within a\n * particular 'class'), 6 indicates whether or not the ASN.1 value is\n * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If\n * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,\n * then the class is APPLICATION. If only bit 8 is set, then the class is\n * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.\n * The tag numbers for the data types for the class UNIVERSAL are listed below:\n *\n * UNIVERSAL 0 Reserved for use by the encoding rules\n * UNIVERSAL 1 Boolean type\n * UNIVERSAL 2 Integer type\n * UNIVERSAL 3 Bitstring type\n * UNIVERSAL 4 Octetstring type\n * UNIVERSAL 5 Null type\n * UNIVERSAL 6 Object identifier type\n * UNIVERSAL 7 Object descriptor type\n * UNIVERSAL 8 External type and Instance-of type\n * UNIVERSAL 9 Real type\n * UNIVERSAL 10 Enumerated type\n * UNIVERSAL 11 Embedded-pdv type\n * UNIVERSAL 12 UTF8String type\n * UNIVERSAL 13 Relative object identifier type\n * UNIVERSAL 14-15 Reserved for future editions\n * UNIVERSAL 16 Sequence and Sequence-of types\n * UNIVERSAL 17 Set and Set-of types\n * UNIVERSAL 18-22, 25-30 Character string types\n * UNIVERSAL 23-24 Time types\n *\n * The length of an ASN.1 structure is specified after the tag identifier.\n * There is a definite form and an indefinite form. The indefinite form may\n * be used if the encoding is constructed and not all immediately available.\n * The indefinite form is encoded using a length byte with only the 8th bit\n * set. The end of the constructed object is marked using end-of-contents\n * octets (two zero bytes).\n *\n * The definite form looks like this:\n *\n * The length may take up 1 or more bytes, it depends on the length of the\n * value of the ASN.1 structure. DER encoding requires that if the ASN.1\n * structure has a value that has a length greater than 127, more than 1 byte\n * will be used to store its length, otherwise just one byte will be used.\n * This is strict.\n *\n * In the case that the length of the ASN.1 value is less than 127, 1 octet\n * (byte) is used to store the \"short form\" length. The 8th bit has a value of\n * 0 indicating the length is \"short form\" and not \"long form\" and bits 7-1\n * give the length of the data. (The 8th bit is the left-most, most significant\n * bit: also known as big endian or network format).\n *\n * In the case that the length of the ASN.1 value is greater than 127, 2 to\n * 127 octets (bytes) are used to store the \"long form\" length. The first\n * byte's 8th bit is set to 1 to indicate the length is \"long form.\" Bits 7-1\n * give the number of additional octets. All following octets are in base 256\n * with the most significant digit first (typical big-endian binary unsigned\n * integer storage). So, for instance, if the length of a value was 257, the\n * first byte would be set to:\n *\n * 10000010 = 130 = 0x82.\n *\n * This indicates there are 2 octets (base 256) for the length. The second and\n * third bytes (the octets just mentioned) would store the length in base 256:\n *\n * octet 2: 00000001 = 1 * 256^1 = 256\n * octet 3: 00000001 = 1 * 256^0 = 1\n * total = 257\n *\n * The algorithm for converting a js integer value of 257 to base-256 is:\n *\n * var value = 257;\n * var bytes = [];\n * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first\n * bytes[1] = value & 0xFF; // least significant byte last\n *\n * On the ASN.1 UNIVERSAL Object Identifier (OID) type:\n *\n * An OID can be written like: \"value1.value2.value3...valueN\"\n *\n * The DER encoding rules:\n *\n * The first byte has the value 40 * value1 + value2.\n * The following bytes, if any, encode the remaining values. Each value is\n * encoded in base 128, most significant digit first (big endian), with as\n * few digits as possible, and the most significant bit of each byte set\n * to 1 except the last in each value's encoding. For example: Given the\n * OID \"1.2.840.113549\", its DER encoding is (remember each byte except the\n * last one in each encoding is OR'd with 0x80):\n *\n * byte 1: 40 * 1 + 2 = 42 = 0x2A.\n * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648\n * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D\n *\n * The final value is: 0x2A864886F70D.\n * The full OID (including ASN.1 tag and length of 6 bytes) is:\n * 0x06062A864886F70D\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./oids');\n\n/* ASN.1 API */\nvar asn1 = module.exports = forge.asn1 = forge.asn1 || {};\n\n/**\n * ASN.1 classes.\n */\nasn1.Class = {\n UNIVERSAL: 0x00,\n APPLICATION: 0x40,\n CONTEXT_SPECIFIC: 0x80,\n PRIVATE: 0xC0\n};\n\n/**\n * ASN.1 types. Not all types are supported by this implementation, only\n * those necessary to implement a simple PKI are implemented.\n */\nasn1.Type = {\n NONE: 0,\n BOOLEAN: 1,\n INTEGER: 2,\n BITSTRING: 3,\n OCTETSTRING: 4,\n NULL: 5,\n OID: 6,\n ODESC: 7,\n EXTERNAL: 8,\n REAL: 9,\n ENUMERATED: 10,\n EMBEDDED: 11,\n UTF8: 12,\n ROID: 13,\n SEQUENCE: 16,\n SET: 17,\n PRINTABLESTRING: 19,\n IA5STRING: 22,\n UTCTIME: 23,\n GENERALIZEDTIME: 24,\n BMPSTRING: 30\n};\n\n/**\n * Creates a new asn1 object.\n *\n * @param tagClass the tag class for the object.\n * @param type the data type (tag number) for the object.\n * @param constructed true if the asn1 object is in constructed form.\n * @param value the value for the object, if it is not constructed.\n * @param [options] the options to use:\n * [bitStringContents] the plain BIT STRING content including padding\n * byte.\n *\n * @return the asn1 object.\n */\nasn1.create = function(tagClass, type, constructed, value, options) {\n /* An asn1 object has a tagClass, a type, a constructed flag, and a\n value. The value's type depends on the constructed flag. If\n constructed, it will contain a list of other asn1 objects. If not,\n it will contain the ASN.1 value as an array of bytes formatted\n according to the ASN.1 data type. */\n\n // remove undefined values\n if(forge.util.isArray(value)) {\n var tmp = [];\n for(var i = 0; i < value.length; ++i) {\n if(value[i] !== undefined) {\n tmp.push(value[i]);\n }\n }\n value = tmp;\n }\n\n var obj = {\n tagClass: tagClass,\n type: type,\n constructed: constructed,\n composed: constructed || forge.util.isArray(value),\n value: value\n };\n if(options && 'bitStringContents' in options) {\n // TODO: copy byte buffer if it's a buffer not a string\n obj.bitStringContents = options.bitStringContents;\n // TODO: add readonly flag to avoid this overhead\n // save copy to detect changes\n obj.original = asn1.copy(obj);\n }\n return obj;\n};\n\n/**\n * Copies an asn1 object.\n *\n * @param obj the asn1 object.\n * @param [options] copy options:\n * [excludeBitStringContents] true to not copy bitStringContents\n *\n * @return the a copy of the asn1 object.\n */\nasn1.copy = function(obj, options) {\n var copy;\n\n if(forge.util.isArray(obj)) {\n copy = [];\n for(var i = 0; i < obj.length; ++i) {\n copy.push(asn1.copy(obj[i], options));\n }\n return copy;\n }\n\n if(typeof obj === 'string') {\n // TODO: copy byte buffer if it's a buffer not a string\n return obj;\n }\n\n copy = {\n tagClass: obj.tagClass,\n type: obj.type,\n constructed: obj.constructed,\n composed: obj.composed,\n value: asn1.copy(obj.value, options)\n };\n if(options && !options.excludeBitStringContents) {\n // TODO: copy byte buffer if it's a buffer not a string\n copy.bitStringContents = obj.bitStringContents;\n }\n return copy;\n};\n\n/**\n * Compares asn1 objects for equality.\n *\n * Note this function does not run in constant time.\n *\n * @param obj1 the first asn1 object.\n * @param obj2 the second asn1 object.\n * @param [options] compare options:\n * [includeBitStringContents] true to compare bitStringContents\n *\n * @return true if the asn1 objects are equal.\n */\nasn1.equals = function(obj1, obj2, options) {\n if(forge.util.isArray(obj1)) {\n if(!forge.util.isArray(obj2)) {\n return false;\n }\n if(obj1.length !== obj2.length) {\n return false;\n }\n for(var i = 0; i < obj1.length; ++i) {\n if(!asn1.equals(obj1[i], obj2[i])) {\n return false;\n }\n }\n return true;\n }\n\n if(typeof obj1 !== typeof obj2) {\n return false;\n }\n\n if(typeof obj1 === 'string') {\n return obj1 === obj2;\n }\n\n var equal = obj1.tagClass === obj2.tagClass &&\n obj1.type === obj2.type &&\n obj1.constructed === obj2.constructed &&\n obj1.composed === obj2.composed &&\n asn1.equals(obj1.value, obj2.value);\n if(options && options.includeBitStringContents) {\n equal = equal && (obj1.bitStringContents === obj2.bitStringContents);\n }\n\n return equal;\n};\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param b the BER-encoded ASN.1 byte buffer, starting with the first\n * length byte.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nasn1.getBerValueLength = function(b) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n var b2 = b.getByte();\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n length = b.getInt((b2 & 0x7F) << 3);\n }\n return length;\n};\n\n/**\n * Check if the byte buffer has enough bytes. Throws an Error if not.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n * @param n the number of bytes the buffer must have.\n */\nfunction _checkBufferLength(bytes, remaining, n) {\n if(n > remaining) {\n var error = new Error('Too few bytes to parse DER.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = n;\n throw error;\n }\n}\n\n/**\n * Gets the length of a BER-encoded ASN.1 value.\n *\n * In case the length is not specified, undefined is returned.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the bytes remaining in the current parsing state.\n *\n * @return the length of the BER-encoded ASN.1 value or undefined.\n */\nvar _getValueLength = function(bytes, remaining) {\n // TODO: move this function and related DER/BER functions to a der.js\n // file; better abstract ASN.1 away from der/ber.\n // fromDer already checked that this byte exists\n var b2 = bytes.getByte();\n remaining--;\n if(b2 === 0x80) {\n return undefined;\n }\n\n // see if the length is \"short form\" or \"long form\" (bit 8 set)\n var length;\n var longForm = b2 & 0x80;\n if(!longForm) {\n // length is just the first byte\n length = b2;\n } else {\n // the number of bytes the length is specified in bits 7 through 1\n // and each length byte is in big-endian base-256\n var longFormBytes = b2 & 0x7F;\n _checkBufferLength(bytes, remaining, longFormBytes);\n length = bytes.getInt(longFormBytes << 3);\n }\n // FIXME: this will only happen for 32 bit getInt with high bit set\n if(length < 0) {\n throw new Error('Negative length: ' + length);\n }\n return length;\n};\n\n/**\n * Parses an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * @param [options] object with options or boolean strict flag\n * [strict] true to be strict when checking value lengths, false to\n * allow truncated values (default: true).\n * [decodeBitStrings] true to attempt to decode the content of\n * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that\n * without schema support to understand the data context this can\n * erroneously decode values that happen to be valid ASN.1. This\n * flag will be deprecated or removed as soon as schema support is\n * available. (default: true)\n *\n * @return the parsed asn1 object.\n */\nasn1.fromDer = function(bytes, options) {\n if(options === undefined) {\n options = {\n strict: true,\n decodeBitStrings: true\n };\n }\n if(typeof options === 'boolean') {\n options = {\n strict: options,\n decodeBitStrings: true\n };\n }\n if(!('strict' in options)) {\n options.strict = true;\n }\n if(!('decodeBitStrings' in options)) {\n options.decodeBitStrings = true;\n }\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n return _fromDer(bytes, bytes.length(), 0, options);\n};\n\n/**\n * Internal function to parse an asn1 object from a byte buffer in DER format.\n *\n * @param bytes the byte buffer to parse from.\n * @param remaining the number of bytes remaining for this chunk.\n * @param depth the current parsing depth.\n * @param options object with same options as fromDer().\n *\n * @return the parsed asn1 object.\n */\nfunction _fromDer(bytes, remaining, depth, options) {\n // temporary storage for consumption calculations\n var start;\n\n // minimum length for ASN.1 DER structure is 2\n _checkBufferLength(bytes, remaining, 2);\n\n // get the first byte\n var b1 = bytes.getByte();\n // consumed one byte\n remaining--;\n\n // get the tag class\n var tagClass = (b1 & 0xC0);\n\n // get the type (bits 1-5)\n var type = b1 & 0x1F;\n\n // get the variable value length and adjust remaining bytes\n start = bytes.length();\n var length = _getValueLength(bytes, remaining);\n remaining -= start - bytes.length();\n\n // ensure there are enough bytes to get the value\n if(length !== undefined && length > remaining) {\n if(options.strict) {\n var error = new Error('Too few bytes to read ASN.1 value.');\n error.available = bytes.length();\n error.remaining = remaining;\n error.requested = length;\n throw error;\n }\n // Note: be lenient with truncated values and use remaining state bytes\n length = remaining;\n }\n\n // value storage\n var value;\n // possible BIT STRING contents storage\n var bitStringContents;\n\n // constructed flag is bit 6 (32 = 0x20) of the first byte\n var constructed = ((b1 & 0x20) === 0x20);\n if(constructed) {\n // parse child asn1 objects from the value\n value = [];\n if(length === undefined) {\n // asn1 object of indefinite length, read until end tag\n for(;;) {\n _checkBufferLength(bytes, remaining, 2);\n if(bytes.bytes(2) === String.fromCharCode(0, 0)) {\n bytes.getBytes(2);\n remaining -= 2;\n break;\n }\n start = bytes.length();\n value.push(_fromDer(bytes, remaining, depth + 1, options));\n remaining -= start - bytes.length();\n }\n } else {\n // parsing asn1 object of definite length\n while(length > 0) {\n start = bytes.length();\n value.push(_fromDer(bytes, length, depth + 1, options));\n remaining -= start - bytes.length();\n length -= start - bytes.length();\n }\n }\n }\n\n // if a BIT STRING, save the contents including padding\n if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&\n type === asn1.Type.BITSTRING) {\n bitStringContents = bytes.bytes(length);\n }\n\n // determine if a non-constructed value should be decoded as a composed\n // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)\n // can be used this way.\n if(value === undefined && options.decodeBitStrings &&\n tagClass === asn1.Class.UNIVERSAL &&\n // FIXME: OCTET STRINGs not yet supported here\n // .. other parts of forge expect to decode OCTET STRINGs manually\n (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&\n length > 1) {\n // save read position\n var savedRead = bytes.read;\n var savedRemaining = remaining;\n var unused = 0;\n if(type === asn1.Type.BITSTRING) {\n /* The first octet gives the number of bits by which the length of the\n bit string is less than the next multiple of eight (this is called\n the \"number of unused bits\").\n\n The second and following octets give the value of the bit string\n converted to an octet string. */\n _checkBufferLength(bytes, remaining, 1);\n unused = bytes.getByte();\n remaining--;\n }\n // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs\n if(unused === 0) {\n try {\n // attempt to parse child asn1 object from the value\n // (stored in array to signal composed value)\n start = bytes.length();\n var subOptions = {\n // enforce strict mode to avoid parsing ASN.1 from plain data\n verbose: options.verbose,\n strict: true,\n decodeBitStrings: true\n };\n var composed = _fromDer(bytes, remaining, depth + 1, subOptions);\n var used = start - bytes.length();\n remaining -= used;\n if(type == asn1.Type.BITSTRING) {\n used++;\n }\n\n // if the data all decoded and the class indicates UNIVERSAL or\n // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object\n var tc = composed.tagClass;\n if(used === length &&\n (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {\n value = [composed];\n }\n } catch(ex) {\n }\n }\n if(value === undefined) {\n // restore read position\n bytes.read = savedRead;\n remaining = savedRemaining;\n }\n }\n\n if(value === undefined) {\n // asn1 not constructed or composed, get raw value\n // TODO: do DER to OID conversion and vice-versa in .toDer?\n\n if(length === undefined) {\n if(options.strict) {\n throw new Error('Non-constructed ASN.1 object of indefinite length.');\n }\n // be lenient and use remaining state bytes\n length = remaining;\n }\n\n if(type === asn1.Type.BMPSTRING) {\n value = '';\n for(; length > 0; length -= 2) {\n _checkBufferLength(bytes, remaining, 2);\n value += String.fromCharCode(bytes.getInt16());\n remaining -= 2;\n }\n } else {\n value = bytes.getBytes(length);\n }\n }\n\n // add BIT STRING contents if available\n var asn1Options = bitStringContents === undefined ? null : {\n bitStringContents: bitStringContents\n };\n\n // create and return asn1 object\n return asn1.create(tagClass, type, constructed, value, asn1Options);\n}\n\n/**\n * Converts the given asn1 object to a buffer of bytes in DER format.\n *\n * @param asn1 the asn1 object to convert to bytes.\n *\n * @return the buffer of bytes.\n */\nasn1.toDer = function(obj) {\n var bytes = forge.util.createBuffer();\n\n // build the first byte\n var b1 = obj.tagClass | obj.type;\n\n // for storing the ASN.1 value\n var value = forge.util.createBuffer();\n\n // use BIT STRING contents if available and data not changed\n var useBitStringContents = false;\n if('bitStringContents' in obj) {\n useBitStringContents = true;\n if(obj.original) {\n useBitStringContents = asn1.equals(obj, obj.original);\n }\n }\n\n if(useBitStringContents) {\n value.putBytes(obj.bitStringContents);\n } else if(obj.composed) {\n // if composed, use each child asn1 object's DER bytes as value\n // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed\n // from other asn1 objects\n if(obj.constructed) {\n b1 |= 0x20;\n } else {\n // type is a bit string, add unused bits of 0x00\n value.putByte(0x00);\n }\n\n // add all of the child DER bytes together\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n value.putBuffer(asn1.toDer(obj.value[i]));\n }\n }\n } else {\n // use asn1.value directly\n if(obj.type === asn1.Type.BMPSTRING) {\n for(var i = 0; i < obj.value.length; ++i) {\n value.putInt16(obj.value.charCodeAt(i));\n }\n } else {\n // ensure integer is minimally-encoded\n // TODO: should all leading bytes be stripped vs just one?\n // .. ex '00 00 01' => '01'?\n if(obj.type === asn1.Type.INTEGER &&\n obj.value.length > 1 &&\n // leading 0x00 for positive integer\n ((obj.value.charCodeAt(0) === 0 &&\n (obj.value.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (obj.value.charCodeAt(0) === 0xFF &&\n (obj.value.charCodeAt(1) & 0x80) === 0x80))) {\n value.putBytes(obj.value.substr(1));\n } else {\n value.putBytes(obj.value);\n }\n }\n }\n\n // add tag byte\n bytes.putByte(b1);\n\n // use \"short form\" encoding\n if(value.length() <= 127) {\n // one byte describes the length\n // bit 8 = 0 and bits 7-1 = length\n bytes.putByte(value.length() & 0x7F);\n } else {\n // use \"long form\" encoding\n // 2 to 127 bytes describe the length\n // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes\n // other bytes: length in base 256, big-endian\n var len = value.length();\n var lenBytes = '';\n do {\n lenBytes += String.fromCharCode(len & 0xFF);\n len = len >>> 8;\n } while(len > 0);\n\n // set first byte to # bytes used to store the length and turn on\n // bit 8 to indicate long-form length is used\n bytes.putByte(lenBytes.length | 0x80);\n\n // concatenate length bytes in reverse since they were generated\n // little endian and we need big endian\n for(var i = lenBytes.length - 1; i >= 0; --i) {\n bytes.putByte(lenBytes.charCodeAt(i));\n }\n }\n\n // concatenate value bytes\n bytes.putBuffer(value);\n return bytes;\n};\n\n/**\n * Converts an OID dot-separated string to a byte buffer. The byte buffer\n * contains only the DER-encoded value, not any tag or length bytes.\n *\n * @param oid the OID dot-separated string.\n *\n * @return the byte buffer.\n */\nasn1.oidToDer = function(oid) {\n // split OID into individual values\n var values = oid.split('.');\n var bytes = forge.util.createBuffer();\n\n // first byte is 40 * value1 + value2\n bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var last, valueBytes, value, b;\n for(var i = 2; i < values.length; ++i) {\n // produce value bytes in reverse because we don't know how many\n // bytes it will take to store the value\n last = true;\n valueBytes = [];\n value = parseInt(values[i], 10);\n do {\n b = value & 0x7F;\n value = value >>> 7;\n // if value is not last, then turn on 8th bit\n if(!last) {\n b |= 0x80;\n }\n valueBytes.push(b);\n last = false;\n } while(value > 0);\n\n // add value bytes in reverse (needs to be in big endian)\n for(var n = valueBytes.length - 1; n >= 0; --n) {\n bytes.putByte(valueBytes[n]);\n }\n }\n\n return bytes;\n};\n\n/**\n * Converts a DER-encoded byte buffer to an OID dot-separated string. The\n * byte buffer should contain only the DER-encoded value, not any tag or\n * length bytes.\n *\n * @param bytes the byte buffer.\n *\n * @return the OID dot-separated string.\n */\nasn1.derToOid = function(bytes) {\n var oid;\n\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n // first byte is 40 * value1 + value2\n var b = bytes.getByte();\n oid = Math.floor(b / 40) + '.' + (b % 40);\n\n // other bytes are each value in base 128 with 8th bit set except for\n // the last byte for each value\n var value = 0;\n while(bytes.length() > 0) {\n b = bytes.getByte();\n value = value << 7;\n // not the last byte for the value\n if(b & 0x80) {\n value += b & 0x7F;\n } else {\n // last byte\n oid += '.' + (value + b);\n value = 0;\n }\n }\n\n return oid;\n};\n\n/**\n * Converts a UTCTime value to a date.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Parsing that structure hasn't been implemented yet.\n *\n * @param utc the UTCTime value to convert.\n *\n * @return the date.\n */\nasn1.utcTimeToDate = function(utc) {\n /* The following formats can be used:\n\n YYMMDDhhmmZ\n YYMMDDhhmm+hh'mm'\n YYMMDDhhmm-hh'mm'\n YYMMDDhhmmssZ\n YYMMDDhhmmss+hh'mm'\n YYMMDDhhmmss-hh'mm'\n\n Where:\n\n YY is the least significant two digits of the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n // if YY >= 50 use 19xx, if YY < 50 use 20xx\n var year = parseInt(utc.substr(0, 2), 10);\n year = (year >= 50) ? 1900 + year : 2000 + year;\n var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(utc.substr(4, 2), 10);\n var hh = parseInt(utc.substr(6, 2), 10);\n var mm = parseInt(utc.substr(8, 2), 10);\n var ss = 0;\n\n // not just YYMMDDhhmmZ\n if(utc.length > 11) {\n // get character after minutes\n var c = utc.charAt(10);\n var end = 10;\n\n // see if seconds are present\n if(c !== '+' && c !== '-') {\n // get seconds\n ss = parseInt(utc.substr(10, 2), 10);\n end += 2;\n }\n }\n\n // update date\n date.setUTCFullYear(year, MM, DD);\n date.setUTCHours(hh, mm, ss, 0);\n\n if(end) {\n // get +/- after end of time\n c = utc.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(utc.substr(end + 1, 2), 10);\n var mmoffset = parseInt(utc.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n var offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n date.setTime(+date - offset);\n } else {\n date.setTime(+date + offset);\n }\n }\n }\n\n return date;\n};\n\n/**\n * Converts a GeneralizedTime value to a date.\n *\n * @param gentime the GeneralizedTime value to convert.\n *\n * @return the date.\n */\nasn1.generalizedTimeToDate = function(gentime) {\n /* The following formats can be used:\n\n YYYYMMDDHHMMSS\n YYYYMMDDHHMMSS.fff\n YYYYMMDDHHMMSSZ\n YYYYMMDDHHMMSS.fffZ\n YYYYMMDDHHMMSS+hh'mm'\n YYYYMMDDHHMMSS.fff+hh'mm'\n YYYYMMDDHHMMSS-hh'mm'\n YYYYMMDDHHMMSS.fff-hh'mm'\n\n Where:\n\n YYYY is the year\n MM is the month (01 to 12)\n DD is the day (01 to 31)\n hh is the hour (00 to 23)\n mm are the minutes (00 to 59)\n ss are the seconds (00 to 59)\n .fff is the second fraction, accurate to three decimal places\n Z indicates that local time is GMT, + indicates that local time is\n later than GMT, and - indicates that local time is earlier than GMT\n hh' is the absolute value of the offset from GMT in hours\n mm' is the absolute value of the offset from GMT in minutes */\n var date = new Date();\n\n var YYYY = parseInt(gentime.substr(0, 4), 10);\n var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month\n var DD = parseInt(gentime.substr(6, 2), 10);\n var hh = parseInt(gentime.substr(8, 2), 10);\n var mm = parseInt(gentime.substr(10, 2), 10);\n var ss = parseInt(gentime.substr(12, 2), 10);\n var fff = 0;\n var offset = 0;\n var isUTC = false;\n\n if(gentime.charAt(gentime.length - 1) === 'Z') {\n isUTC = true;\n }\n\n var end = gentime.length - 5, c = gentime.charAt(end);\n if(c === '+' || c === '-') {\n // get hours+minutes offset\n var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);\n var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);\n\n // calculate offset in milliseconds\n offset = hhoffset * 60 + mmoffset;\n offset *= 60000;\n\n // apply offset\n if(c === '+') {\n offset *= -1;\n }\n\n isUTC = true;\n }\n\n // check for second fraction\n if(gentime.charAt(14) === '.') {\n fff = parseFloat(gentime.substr(14), 10) * 1000;\n }\n\n if(isUTC) {\n date.setUTCFullYear(YYYY, MM, DD);\n date.setUTCHours(hh, mm, ss, fff);\n\n // apply offset\n date.setTime(+date + offset);\n } else {\n date.setFullYear(YYYY, MM, DD);\n date.setHours(hh, mm, ss, fff);\n }\n\n return date;\n};\n\n/**\n * Converts a date to a UTCTime value.\n *\n * Note: GeneralizedTime has 4 digits for the year and is used for X.509\n * dates past 2049. Converting to a GeneralizedTime hasn't been\n * implemented yet.\n *\n * @param date the date to convert.\n *\n * @return the UTCTime value.\n */\nasn1.dateToUtcTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYMMDDhhmmssZ\n var format = [];\n format.push(('' + date.getUTCFullYear()).substr(2));\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a date to a GeneralizedTime value.\n *\n * @param date the date to convert.\n *\n * @return the GeneralizedTime value as a string.\n */\nasn1.dateToGeneralizedTime = function(date) {\n // TODO: validate; currently assumes proper format\n if(typeof date === 'string') {\n return date;\n }\n\n var rval = '';\n\n // create format YYYYMMDDHHMMSSZ\n var format = [];\n format.push('' + date.getUTCFullYear());\n format.push('' + (date.getUTCMonth() + 1));\n format.push('' + date.getUTCDate());\n format.push('' + date.getUTCHours());\n format.push('' + date.getUTCMinutes());\n format.push('' + date.getUTCSeconds());\n\n // ensure 2 digits are used for each format entry\n for(var i = 0; i < format.length; ++i) {\n if(format[i].length < 2) {\n rval += '0';\n }\n rval += format[i];\n }\n rval += 'Z';\n\n return rval;\n};\n\n/**\n * Converts a javascript integer to a DER-encoded byte buffer to be used\n * as the value for an INTEGER type.\n *\n * @param x the integer.\n *\n * @return the byte buffer.\n */\nasn1.integerToDer = function(x) {\n var rval = forge.util.createBuffer();\n if(x >= -0x80 && x < 0x80) {\n return rval.putSignedInt(x, 8);\n }\n if(x >= -0x8000 && x < 0x8000) {\n return rval.putSignedInt(x, 16);\n }\n if(x >= -0x800000 && x < 0x800000) {\n return rval.putSignedInt(x, 24);\n }\n if(x >= -0x80000000 && x < 0x80000000) {\n return rval.putSignedInt(x, 32);\n }\n var error = new Error('Integer too large; max is 32-bits.');\n error.integer = x;\n throw error;\n};\n\n/**\n * Converts a DER-encoded byte buffer to a javascript integer. This is\n * typically used to decode the value of an INTEGER type.\n *\n * @param bytes the byte buffer.\n *\n * @return the integer.\n */\nasn1.derToInteger = function(bytes) {\n // wrap in buffer if needed\n if(typeof bytes === 'string') {\n bytes = forge.util.createBuffer(bytes);\n }\n\n var n = bytes.length() * 8;\n if(n > 32) {\n throw new Error('Integer too large; max is 32-bits.');\n }\n return bytes.getSignedInt(n);\n};\n\n/**\n * Validates that the given ASN.1 object is at least a super set of the\n * given ASN.1 structure. Only tag classes and types are checked. An\n * optional map may also be provided to capture ASN.1 values while the\n * structure is checked.\n *\n * To capture an ASN.1 value, set an object in the validator's 'capture'\n * parameter to the key to use in the capture map. To capture the full\n * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including\n * the leading unused bits counter byte, specify 'captureBitStringContents'.\n * To capture BIT STRING bytes, without the leading unused bits counter byte,\n * specify 'captureBitStringValue'.\n *\n * Objects in the validator may set a field 'optional' to true to indicate\n * that it isn't necessary to pass validation.\n *\n * @param obj the ASN.1 object to validate.\n * @param v the ASN.1 structure validator.\n * @param capture an optional map to capture values in.\n * @param errors an optional array for storing validation errors.\n *\n * @return true on success, false on failure.\n */\nasn1.validate = function(obj, v, capture, errors) {\n var rval = false;\n\n // ensure tag class and type are the same if specified\n if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&\n (obj.type === v.type || typeof(v.type) === 'undefined')) {\n // ensure constructed flag is the same if specified\n if(obj.constructed === v.constructed ||\n typeof(v.constructed) === 'undefined') {\n rval = true;\n\n // handle sub values\n if(v.value && forge.util.isArray(v.value)) {\n var j = 0;\n for(var i = 0; rval && i < v.value.length; ++i) {\n rval = v.value[i].optional || false;\n if(obj.value[j]) {\n rval = asn1.validate(obj.value[j], v.value[i], capture, errors);\n if(rval) {\n ++j;\n } else if(v.value[i].optional) {\n rval = true;\n }\n }\n if(!rval && errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Tag class \"' + v.tagClass + '\", type \"' +\n v.type + '\" expected value length \"' +\n v.value.length + '\", got \"' +\n obj.value.length + '\"');\n }\n }\n }\n\n if(rval && capture) {\n if(v.capture) {\n capture[v.capture] = obj.value;\n }\n if(v.captureAsn1) {\n capture[v.captureAsn1] = obj;\n }\n if(v.captureBitStringContents && 'bitStringContents' in obj) {\n capture[v.captureBitStringContents] = obj.bitStringContents;\n }\n if(v.captureBitStringValue && 'bitStringContents' in obj) {\n var value;\n if(obj.bitStringContents.length < 2) {\n capture[v.captureBitStringValue] = '';\n } else {\n // FIXME: support unused bits with data shifting\n var unused = obj.bitStringContents.charCodeAt(0);\n if(unused !== 0) {\n throw new Error(\n 'captureBitStringValue only supported for zero unused bits');\n }\n capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);\n }\n }\n }\n } else if(errors) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected constructed \"' + v.constructed + '\", got \"' +\n obj.constructed + '\"');\n }\n } else if(errors) {\n if(obj.tagClass !== v.tagClass) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected tag class \"' + v.tagClass + '\", got \"' +\n obj.tagClass + '\"');\n }\n if(obj.type !== v.type) {\n errors.push(\n '[' + v.name + '] ' +\n 'Expected type \"' + v.type + '\", got \"' + obj.type + '\"');\n }\n }\n return rval;\n};\n\n// regex for testing for non-latin characters\nvar _nonLatinRegex = /[^\\\\u0000-\\\\u00ff]/;\n\n/**\n * Pretty prints an ASN.1 object to a string.\n *\n * @param obj the object to write out.\n * @param level the level in the tree.\n * @param indentation the indentation to use.\n *\n * @return the string.\n */\nasn1.prettyPrint = function(obj, level, indentation) {\n var rval = '';\n\n // set default level and indentation\n level = level || 0;\n indentation = indentation || 2;\n\n // start new line for deep levels\n if(level > 0) {\n rval += '\\n';\n }\n\n // create indent\n var indent = '';\n for(var i = 0; i < level * indentation; ++i) {\n indent += ' ';\n }\n\n // print class:type\n rval += indent + 'Tag: ';\n switch(obj.tagClass) {\n case asn1.Class.UNIVERSAL:\n rval += 'Universal:';\n break;\n case asn1.Class.APPLICATION:\n rval += 'Application:';\n break;\n case asn1.Class.CONTEXT_SPECIFIC:\n rval += 'Context-Specific:';\n break;\n case asn1.Class.PRIVATE:\n rval += 'Private:';\n break;\n }\n\n if(obj.tagClass === asn1.Class.UNIVERSAL) {\n rval += obj.type;\n\n // known types\n switch(obj.type) {\n case asn1.Type.NONE:\n rval += ' (None)';\n break;\n case asn1.Type.BOOLEAN:\n rval += ' (Boolean)';\n break;\n case asn1.Type.INTEGER:\n rval += ' (Integer)';\n break;\n case asn1.Type.BITSTRING:\n rval += ' (Bit string)';\n break;\n case asn1.Type.OCTETSTRING:\n rval += ' (Octet string)';\n break;\n case asn1.Type.NULL:\n rval += ' (Null)';\n break;\n case asn1.Type.OID:\n rval += ' (Object Identifier)';\n break;\n case asn1.Type.ODESC:\n rval += ' (Object Descriptor)';\n break;\n case asn1.Type.EXTERNAL:\n rval += ' (External or Instance of)';\n break;\n case asn1.Type.REAL:\n rval += ' (Real)';\n break;\n case asn1.Type.ENUMERATED:\n rval += ' (Enumerated)';\n break;\n case asn1.Type.EMBEDDED:\n rval += ' (Embedded PDV)';\n break;\n case asn1.Type.UTF8:\n rval += ' (UTF8)';\n break;\n case asn1.Type.ROID:\n rval += ' (Relative Object Identifier)';\n break;\n case asn1.Type.SEQUENCE:\n rval += ' (Sequence)';\n break;\n case asn1.Type.SET:\n rval += ' (Set)';\n break;\n case asn1.Type.PRINTABLESTRING:\n rval += ' (Printable String)';\n break;\n case asn1.Type.IA5String:\n rval += ' (IA5String (ASCII))';\n break;\n case asn1.Type.UTCTIME:\n rval += ' (UTC time)';\n break;\n case asn1.Type.GENERALIZEDTIME:\n rval += ' (Generalized time)';\n break;\n case asn1.Type.BMPSTRING:\n rval += ' (BMP String)';\n break;\n }\n } else {\n rval += obj.type;\n }\n\n rval += '\\n';\n rval += indent + 'Constructed: ' + obj.constructed + '\\n';\n\n if(obj.composed) {\n var subvalues = 0;\n var sub = '';\n for(var i = 0; i < obj.value.length; ++i) {\n if(obj.value[i] !== undefined) {\n subvalues += 1;\n sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);\n if((i + 1) < obj.value.length) {\n sub += ',';\n }\n }\n }\n rval += indent + 'Sub values: ' + subvalues + sub;\n } else {\n rval += indent + 'Value: ';\n if(obj.type === asn1.Type.OID) {\n var oid = asn1.derToOid(obj.value);\n rval += oid;\n if(forge.pki && forge.pki.oids) {\n if(oid in forge.pki.oids) {\n rval += ' (' + forge.pki.oids[oid] + ') ';\n }\n }\n }\n if(obj.type === asn1.Type.INTEGER) {\n try {\n rval += asn1.derToInteger(obj.value);\n } catch(ex) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n }\n } else if(obj.type === asn1.Type.BITSTRING) {\n // TODO: shift bits as needed to display without padding\n if(obj.value.length > 1) {\n // remove unused bits field\n rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));\n } else {\n rval += '(none)';\n }\n // show unused bit count\n if(obj.value.length > 0) {\n var unused = obj.value.charCodeAt(0);\n if(unused == 1) {\n rval += ' (1 unused bit shown)';\n } else if(unused > 1) {\n rval += ' (' + unused + ' unused bits shown)';\n }\n }\n } else if(obj.type === asn1.Type.OCTETSTRING) {\n if(!_nonLatinRegex.test(obj.value)) {\n rval += '(' + obj.value + ') ';\n }\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.type === asn1.Type.UTF8) {\n rval += forge.util.decodeUtf8(obj.value);\n } else if(obj.type === asn1.Type.PRINTABLESTRING ||\n obj.type === asn1.Type.IA5String) {\n rval += obj.value;\n } else if(_nonLatinRegex.test(obj.value)) {\n rval += '0x' + forge.util.bytesToHex(obj.value);\n } else if(obj.value.length === 0) {\n rval += '[null]';\n } else {\n rval += obj.value;\n }\n }\n\n return rval;\n};\n","/**\n * Node.js module for Forge message digests.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2017 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\nmodule.exports = forge.md = forge.md || {};\nforge.md.algorithms = forge.md.algorithms || {};\n","/**\n * Hash-based Message Authentication Code implementation. Requires a message\n * digest object that can be obtained, for example, from forge.md.sha1 or\n * forge.md.md5.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\n/* HMAC API */\nvar hmac = module.exports = forge.hmac = forge.hmac || {};\n\n/**\n * Creates an HMAC object that uses the given message digest object.\n *\n * @return an HMAC object.\n */\nhmac.create = function() {\n // the hmac key to use\n var _key = null;\n\n // the message digest to use\n var _md = null;\n\n // the inner padding\n var _ipadding = null;\n\n // the outer padding\n var _opadding = null;\n\n // hmac context\n var ctx = {};\n\n /**\n * Starts or restarts the HMAC with the given key and message digest.\n *\n * @param md the message digest to use, null to reuse the previous one,\n * a string to use builtin 'sha1', 'md5', 'sha256'.\n * @param key the key to use as a string, array of bytes, byte buffer,\n * or null to reuse the previous key.\n */\n ctx.start = function(md, key) {\n if(md !== null) {\n if(typeof md === 'string') {\n // create builtin message digest\n md = md.toLowerCase();\n if(md in forge.md.algorithms) {\n _md = forge.md.algorithms[md].create();\n } else {\n throw new Error('Unknown hash algorithm \"' + md + '\"');\n }\n } else {\n // store message digest\n _md = md;\n }\n }\n\n if(key === null) {\n // reuse previous key\n key = _key;\n } else {\n if(typeof key === 'string') {\n // convert string into byte buffer\n key = forge.util.createBuffer(key);\n } else if(forge.util.isArray(key)) {\n // convert byte array into byte buffer\n var tmp = key;\n key = forge.util.createBuffer();\n for(var i = 0; i < tmp.length; ++i) {\n key.putByte(tmp[i]);\n }\n }\n\n // if key is longer than blocksize, hash it\n var keylen = key.length();\n if(keylen > _md.blockLength) {\n _md.start();\n _md.update(key.bytes());\n key = _md.digest();\n }\n\n // mix key into inner and outer padding\n // ipadding = [0x36 * blocksize] ^ key\n // opadding = [0x5C * blocksize] ^ key\n _ipadding = forge.util.createBuffer();\n _opadding = forge.util.createBuffer();\n keylen = key.length();\n for(var i = 0; i < keylen; ++i) {\n var tmp = key.at(i);\n _ipadding.putByte(0x36 ^ tmp);\n _opadding.putByte(0x5C ^ tmp);\n }\n\n // if key is shorter than blocksize, add additional padding\n if(keylen < _md.blockLength) {\n var tmp = _md.blockLength - keylen;\n for(var i = 0; i < tmp; ++i) {\n _ipadding.putByte(0x36);\n _opadding.putByte(0x5C);\n }\n }\n _key = key;\n _ipadding = _ipadding.bytes();\n _opadding = _opadding.bytes();\n }\n\n // digest is done like so: hash(opadding | hash(ipadding | message))\n\n // prepare to do inner hash\n // hash(ipadding | message)\n _md.start();\n _md.update(_ipadding);\n };\n\n /**\n * Updates the HMAC with the given message bytes.\n *\n * @param bytes the bytes to update with.\n */\n ctx.update = function(bytes) {\n _md.update(bytes);\n };\n\n /**\n * Produces the Message Authentication Code (MAC).\n *\n * @return a byte buffer containing the digest value.\n */\n ctx.getMac = function() {\n // digest is done like so: hash(opadding | hash(ipadding | message))\n // here we do the outer hashing\n var inner = _md.digest().bytes();\n _md.start();\n _md.update(_opadding);\n _md.update(inner);\n return _md.digest();\n };\n // alias for getMac\n ctx.digest = ctx.getMac;\n\n return ctx;\n};\n","/**\n * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar md5 = module.exports = forge.md5 = forge.md5 || {};\nforge.md.md5 = forge.md.algorithms.md5 = md5;\n\n/**\n * Creates an MD5 message digest object.\n *\n * @return a message digest object.\n */\nmd5.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // MD5 state contains four 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(16);\n\n // message digest object\n var md = {\n algorithm: 'md5',\n blockLength: 64,\n digestLength: 16,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = (len[1] / 0x100000000) >>> 0;\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate MD5 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in little-endian order; since length\n // is stored in bytes we multiply by 8 and add carry\n var bits, carry = 0;\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n bits = md.fullMessageLength[i] * 8 + carry;\n carry = (bits / 0x100000000) >>> 0;\n finalBlock.putInt32Le(bits >>> 0);\n }\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32Le(s2.h0);\n rval.putInt32Le(s2.h1);\n rval.putInt32Le(s2.h2);\n rval.putInt32Le(s2.h3);\n return rval;\n };\n\n return md;\n};\n\n// padding, constant tables for calculating md5\nvar _padding = null;\nvar _g = null;\nvar _r = null;\nvar _k = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // g values\n _g = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12,\n 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2,\n 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9];\n\n // rounds table\n _r = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];\n\n // get the result of abs(sin(i + 1)) as a 32-bit integer\n _k = new Array(64);\n for(var i = 0; i < 64; ++i) {\n _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000);\n }\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates an MD5 state with the given byte buffer.\n *\n * @param s the MD5 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, f, r, i;\n var len = bytes.length();\n while(len >= 64) {\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32Le();\n f = d ^ (b & (c ^ d));\n t = (a + f + _k[i] + w[i]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 2\n for(; i < 32; ++i) {\n f = c ^ (d & (b ^ c));\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 3\n for(; i < 48; ++i) {\n f = b ^ c ^ d;\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n // round 4\n for(; i < 64; ++i) {\n f = c ^ (b | ~d);\n t = (a + f + _k[i] + w[_g[i]]);\n r = _r[i];\n a = d;\n d = c;\n c = b;\n b += (t << r) | (t >>> (32 - r));\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.\n *\n * See: RFC 1421.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n *\n * A Forge PEM object has the following fields:\n *\n * type: identifies the type of message (eg: \"RSA PRIVATE KEY\").\n *\n * procType: identifies the type of processing performed on the message,\n * it has two subfields: version and type, eg: 4,ENCRYPTED.\n *\n * contentDomain: identifies the type of content in the message, typically\n * only uses the value: \"RFC822\".\n *\n * dekInfo: identifies the message encryption algorithm and mode and includes\n * any parameters for the algorithm, it has two subfields: algorithm and\n * parameters, eg: DES-CBC,F8143EDE5960C597.\n *\n * headers: contains all other PEM encapsulated headers -- where order is\n * significant (for pairing data like recipient ID + key info).\n *\n * body: the binary-encoded body.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n// shortcut for pem API\nvar pem = module.exports = forge.pem = forge.pem || {};\n\n/**\n * Encodes (serializes) the given PEM object.\n *\n * @param msg the PEM message object to encode.\n * @param options the options to use:\n * maxline the maximum characters per line for the body, (default: 64).\n *\n * @return the PEM-formatted string.\n */\npem.encode = function(msg, options) {\n options = options || {};\n var rval = '-----BEGIN ' + msg.type + '-----\\r\\n';\n\n // encode special headers\n var header;\n if(msg.procType) {\n header = {\n name: 'Proc-Type',\n values: [String(msg.procType.version), msg.procType.type]\n };\n rval += foldHeader(header);\n }\n if(msg.contentDomain) {\n header = {name: 'Content-Domain', values: [msg.contentDomain]};\n rval += foldHeader(header);\n }\n if(msg.dekInfo) {\n header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};\n if(msg.dekInfo.parameters) {\n header.values.push(msg.dekInfo.parameters);\n }\n rval += foldHeader(header);\n }\n\n if(msg.headers) {\n // encode all other headers\n for(var i = 0; i < msg.headers.length; ++i) {\n rval += foldHeader(msg.headers[i]);\n }\n }\n\n // terminate header\n if(msg.procType) {\n rval += '\\r\\n';\n }\n\n // add body\n rval += forge.util.encode64(msg.body, options.maxline || 64) + '\\r\\n';\n\n rval += '-----END ' + msg.type + '-----\\r\\n';\n return rval;\n};\n\n/**\n * Decodes (deserializes) all PEM messages found in the given string.\n *\n * @param str the PEM-formatted string to decode.\n *\n * @return the PEM message objects in an array.\n */\npem.decode = function(str) {\n var rval = [];\n\n // split string into PEM messages (be lenient w/EOF on BEGIN line)\n var rMessage = /\\s*-----BEGIN ([A-Z0-9- ]+)-----\\r?\\n?([\\x21-\\x7e\\s]+?(?:\\r?\\n\\r?\\n))?([:A-Za-z0-9+\\/=\\s]+?)-----END \\1-----/g;\n var rHeader = /([\\x21-\\x7e]+):\\s*([\\x21-\\x7e\\s^:]+)/;\n var rCRLF = /\\r?\\n/;\n var match;\n while(true) {\n match = rMessage.exec(str);\n if(!match) {\n break;\n }\n\n var msg = {\n type: match[1],\n procType: null,\n contentDomain: null,\n dekInfo: null,\n headers: [],\n body: forge.util.decode64(match[3])\n };\n rval.push(msg);\n\n // no headers\n if(!match[2]) {\n continue;\n }\n\n // parse headers\n var lines = match[2].split(rCRLF);\n var li = 0;\n while(match && li < lines.length) {\n // get line, trim any rhs whitespace\n var line = lines[li].replace(/\\s+$/, '');\n\n // RFC2822 unfold any following folded lines\n for(var nl = li + 1; nl < lines.length; ++nl) {\n var next = lines[nl];\n if(!/\\s/.test(next[0])) {\n break;\n }\n line += next;\n li = nl;\n }\n\n // parse header\n match = line.match(rHeader);\n if(match) {\n var header = {name: match[1], values: []};\n var values = match[2].split(',');\n for(var vi = 0; vi < values.length; ++vi) {\n header.values.push(ltrim(values[vi]));\n }\n\n // Proc-Type must be the first header\n if(!msg.procType) {\n if(header.name !== 'Proc-Type') {\n throw new Error('Invalid PEM formatted message. The first ' +\n 'encapsulated header must be \"Proc-Type\".');\n } else if(header.values.length !== 2) {\n throw new Error('Invalid PEM formatted message. The \"Proc-Type\" ' +\n 'header must have two subfields.');\n }\n msg.procType = {version: values[0], type: values[1]};\n } else if(!msg.contentDomain && header.name === 'Content-Domain') {\n // special-case Content-Domain\n msg.contentDomain = values[0] || '';\n } else if(!msg.dekInfo && header.name === 'DEK-Info') {\n // special-case DEK-Info\n if(header.values.length === 0) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must have at least one subfield.');\n }\n msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};\n } else {\n msg.headers.push(header);\n }\n }\n\n ++li;\n }\n\n if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {\n throw new Error('Invalid PEM formatted message. The \"DEK-Info\" ' +\n 'header must be present if \"Proc-Type\" is \"ENCRYPTED\".');\n }\n }\n\n if(rval.length === 0) {\n throw new Error('Invalid PEM formatted message.');\n }\n\n return rval;\n};\n\nfunction foldHeader(header) {\n var rval = header.name + ': ';\n\n // ensure values with CRLF are folded\n var values = [];\n var insertSpace = function(match, $1) {\n return ' ' + $1;\n };\n for(var i = 0; i < header.values.length; ++i) {\n values.push(header.values[i].replace(/^(\\S+\\r\\n)/, insertSpace));\n }\n rval += values.join(',') + '\\r\\n';\n\n // do folding\n var length = 0;\n var candidate = -1;\n for(var i = 0; i < rval.length; ++i, ++length) {\n if(length > 65 && candidate !== -1) {\n var insert = rval[candidate];\n if(insert === ',') {\n ++candidate;\n rval = rval.substr(0, candidate) + '\\r\\n ' + rval.substr(candidate);\n } else {\n rval = rval.substr(0, candidate) +\n '\\r\\n' + insert + rval.substr(candidate + 1);\n }\n length = (i - candidate - 1);\n candidate = -1;\n ++i;\n } else if(rval[i] === ' ' || rval[i] === '\\t' || rval[i] === ',') {\n candidate = i;\n }\n }\n\n return rval;\n}\n\nfunction ltrim(str) {\n return str.replace(/^\\s+/, '');\n}\n","/**\n * DES (Data Encryption Standard) implementation.\n *\n * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.\n * It is based on the BSD-licensed implementation by Paul Tero:\n *\n * Paul Tero, July 2001\n * http://www.tero.co.uk/des/\n *\n * Optimised for performance with large blocks by\n * Michael Hayworth, November 2001\n * http://www.netdealing.com\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./cipher');\nrequire('./cipherModes');\nrequire('./util');\n\n/* DES API */\nmodule.exports = forge.des = forge.des || {};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n * cipher.start({iv: iv});\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startEncrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: false,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var cipher = forge.cipher.createCipher('DES-', key);\n *\n * Creates an DES cipher object to encrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createEncryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: false,\n mode: mode\n });\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n * decipher.start({iv: iv});\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n * The output will be stored in the 'output' member of the returned cipher.\n *\n * The key and iv may be given as binary-encoded strings of bytes or\n * byte buffers.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n * @param mode the cipher mode to use (default: 'CBC' if IV is\n * given, 'ECB' if null).\n *\n * @return the cipher.\n */\nforge.des.startDecrypting = function(key, iv, output, mode) {\n var cipher = _createCipher({\n key: key,\n output: output,\n decrypt: true,\n mode: mode || (iv === null ? 'ECB' : 'CBC')\n });\n cipher.start(iv);\n return cipher;\n};\n\n/**\n * Deprecated. Instead, use:\n *\n * var decipher = forge.cipher.createDecipher('DES-', key);\n *\n * Creates an DES cipher object to decrypt data using the given symmetric key.\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param key the symmetric key to use (64 or 192 bits).\n * @param mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nforge.des.createDecryptionCipher = function(key, mode) {\n return _createCipher({\n key: key,\n output: null,\n decrypt: true,\n mode: mode\n });\n};\n\n/**\n * Creates a new DES cipher algorithm object.\n *\n * @param name the name of the algorithm.\n * @param mode the mode factory function.\n *\n * @return the DES algorithm object.\n */\nforge.des.Algorithm = function(name, mode) {\n var self = this;\n self.name = name;\n self.mode = new mode({\n blockSize: 8,\n cipher: {\n encrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, false);\n },\n decrypt: function(inBlock, outBlock) {\n return _updateBlock(self._keys, inBlock, outBlock, true);\n }\n }\n });\n self._init = false;\n};\n\n/**\n * Initializes this DES algorithm by expanding its key.\n *\n * @param options the options to use.\n * key the key to use with this algorithm.\n * decrypt true if the algorithm should be initialized for decryption,\n * false for encryption.\n */\nforge.des.Algorithm.prototype.initialize = function(options) {\n if(this._init) {\n return;\n }\n\n var key = forge.util.createBuffer(options.key);\n if(this.name.indexOf('3DES') === 0) {\n if(key.length() !== 24) {\n throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);\n }\n }\n\n // do key expansion to 16 or 48 subkeys (single or triple DES)\n this._keys = _createKeys(key);\n this._init = true;\n};\n\n/** Register DES algorithms **/\n\nregisterAlgorithm('DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('DES-CTR', forge.cipher.modes.ctr);\n\nregisterAlgorithm('3DES-ECB', forge.cipher.modes.ecb);\nregisterAlgorithm('3DES-CBC', forge.cipher.modes.cbc);\nregisterAlgorithm('3DES-CFB', forge.cipher.modes.cfb);\nregisterAlgorithm('3DES-OFB', forge.cipher.modes.ofb);\nregisterAlgorithm('3DES-CTR', forge.cipher.modes.ctr);\n\nfunction registerAlgorithm(name, mode) {\n var factory = function() {\n return new forge.des.Algorithm(name, mode);\n };\n forge.cipher.registerAlgorithm(name, factory);\n}\n\n/** DES implementation **/\n\nvar spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];\nvar spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];\nvar spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];\nvar spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];\nvar spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];\nvar spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];\nvar spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];\nvar spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];\n\n/**\n * Create necessary sub keys.\n *\n * @param key the 64-bit or 192-bit key.\n *\n * @return the expanded keys.\n */\nfunction _createKeys(key) {\n var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],\n pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],\n pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],\n pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],\n pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],\n pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],\n pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],\n pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],\n pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],\n pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],\n pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],\n pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],\n pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],\n pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];\n\n // how many iterations (1 for des, 3 for triple des)\n // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys\n var iterations = key.length() > 8 ? 3 : 1;\n\n // stores the return keys\n var keys = [];\n\n // now define the left shifts which need to be done\n var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];\n\n var n = 0, tmp;\n for(var j = 0; j < iterations; j++) {\n var left = key.getInt32();\n var right = key.getInt32();\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 2) ^ right) & 0x33333333;\n right ^= tmp;\n left ^= (tmp << 2);\n\n tmp = ((right >>> -16) ^ left) & 0x0000ffff;\n left ^= tmp;\n right ^= (tmp << -16);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // right needs to be shifted and OR'd with last four bits of left\n tmp = (left << 8) | ((right >>> 20) & 0x000000f0);\n\n // left needs to be put upside down\n left = ((right << 24) | ((right << 8) & 0xff0000) |\n ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));\n right = tmp;\n\n // now go through and perform these shifts on the left and right keys\n for(var i = 0; i < shifts.length; ++i) {\n //shift the keys either one or two bits to the left\n if(shifts[i]) {\n left = (left << 2) | (left >>> 26);\n right = (right << 2) | (right >>> 26);\n } else {\n left = (left << 1) | (left >>> 27);\n right = (right << 1) | (right >>> 27);\n }\n left &= -0xf;\n right &= -0xf;\n\n // now apply PC-2, in such a way that E is easier when encrypting or\n // decrypting this conversion will look like PC-2 except only the last 6\n // bits of each byte are used rather than 48 consecutive bits and the\n // order of lines will be according to how the S selection functions will\n // be applied: S2, S4, S6, S8, S1, S3, S5, S7\n var lefttmp = (\n pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |\n pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |\n pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |\n pc2bytes6[(left >>> 4) & 0xf]);\n var righttmp = (\n pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |\n pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |\n pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |\n pc2bytes13[(right >>> 4) & 0xf]);\n tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;\n keys[n++] = lefttmp ^ tmp;\n keys[n++] = righttmp ^ (tmp << 16);\n }\n }\n\n return keys;\n}\n\n/**\n * Updates a single block (1 byte) using DES. The update will either\n * encrypt or decrypt the block.\n *\n * @param keys the expanded keys.\n * @param input the input block (an array of 32-bit words).\n * @param output the updated output block.\n * @param decrypt true to decrypt the block, false to encrypt it.\n */\nfunction _updateBlock(keys, input, output, decrypt) {\n // set up loops for single or triple DES\n var iterations = keys.length === 32 ? 3 : 9;\n var looping;\n if(iterations === 3) {\n looping = decrypt ? [30, -2, -2] : [0, 32, 2];\n } else {\n looping = (decrypt ?\n [94, 62, -2, 32, 64, 2, 30, -2, -2] :\n [0, 32, 2, 62, 30, -2, 64, 96, 2]);\n }\n\n var tmp;\n\n var left = input[0];\n var right = input[1];\n\n // first each 64 bit chunk of the message must be permuted according to IP\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n // rotate left 1 bit\n left = ((left << 1) | (left >>> 31));\n right = ((right << 1) | (right >>> 31));\n\n for(var j = 0; j < iterations; j += 3) {\n var endloop = looping[j + 1];\n var loopinc = looping[j + 2];\n\n // now go through and perform the encryption or decryption\n for(var i = looping[j]; i != endloop; i += loopinc) {\n var right1 = right ^ keys[i];\n var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];\n\n // passing these bytes through the S selection functions\n tmp = left;\n left = right;\n right = tmp ^ (\n spfunction2[(right1 >>> 24) & 0x3f] |\n spfunction4[(right1 >>> 16) & 0x3f] |\n spfunction6[(right1 >>> 8) & 0x3f] |\n spfunction8[right1 & 0x3f] |\n spfunction1[(right2 >>> 24) & 0x3f] |\n spfunction3[(right2 >>> 16) & 0x3f] |\n spfunction5[(right2 >>> 8) & 0x3f] |\n spfunction7[right2 & 0x3f]);\n }\n // unreverse left and right\n tmp = left;\n left = right;\n right = tmp;\n }\n\n // rotate right 1 bit\n left = ((left >>> 1) | (left << 31));\n right = ((right >>> 1) | (right << 31));\n\n // now perform IP-1, which is IP in the opposite direction\n tmp = ((left >>> 1) ^ right) & 0x55555555;\n right ^= tmp;\n left ^= (tmp << 1);\n\n tmp = ((right >>> 8) ^ left) & 0x00ff00ff;\n left ^= tmp;\n right ^= (tmp << 8);\n\n tmp = ((right >>> 2) ^ left) & 0x33333333;\n left ^= tmp;\n right ^= (tmp << 2);\n\n tmp = ((left >>> 16) ^ right) & 0x0000ffff;\n right ^= tmp;\n left ^= (tmp << 16);\n\n tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;\n right ^= tmp;\n left ^= (tmp << 4);\n\n output[0] = left;\n output[1] = right;\n}\n\n/**\n * Deprecated. Instead, use:\n *\n * forge.cipher.createCipher('DES-', key);\n * forge.cipher.createDecipher('DES-', key);\n *\n * Creates a deprecated DES cipher object. This object's mode will default to\n * CBC (cipher-block-chaining).\n *\n * The key may be given as a binary-encoded string of bytes or a byte buffer.\n *\n * @param options the options to use.\n * key the symmetric key to use (64 or 192 bits).\n * output the buffer to write to.\n * decrypt true for decryption, false for encryption.\n * mode the cipher mode to use (default: 'CBC').\n *\n * @return the cipher.\n */\nfunction _createCipher(options) {\n options = options || {};\n var mode = (options.mode || 'CBC').toUpperCase();\n var algorithm = 'DES-' + mode;\n\n var cipher;\n if(options.decrypt) {\n cipher = forge.cipher.createDecipher(algorithm, options.key);\n } else {\n cipher = forge.cipher.createCipher(algorithm, options.key);\n }\n\n // backwards compatible start API\n var start = cipher.start;\n cipher.start = function(iv, options) {\n // backwards compatibility: support second arg as output buffer\n var output = null;\n if(options instanceof forge.util.ByteBuffer) {\n output = options;\n options = {};\n }\n options = options || {};\n options.output = output;\n options.iv = iv;\n start.call(cipher, options);\n };\n\n return cipher;\n}\n","/**\n * Password-Based Key-Derivation Function #2 implementation.\n *\n * See RFC 2898 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./hmac');\nrequire('./md');\nrequire('./util');\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = require('crypto');\n}\n\n/**\n * Derives a key from a password.\n *\n * @param p the password as a binary-encoded string of bytes.\n * @param s the salt as a binary-encoded string of bytes.\n * @param c the iteration count, a positive integer.\n * @param dkLen the intended length, in bytes, of the derived key,\n * (max: 2^32 - 1) * hash length of the PRF.\n * @param [md] the message digest (or algorithm identifier as a string) to use\n * in the PRF, defaults to SHA-1.\n * @param [callback(err, key)] presence triggers asynchronous version, called\n * once the operation completes.\n *\n * @return the derived key, as a binary-encoded string of bytes, for the\n * synchronous version (if no callback is specified).\n */\nmodule.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(\n p, s, c, dkLen, md, callback) {\n if(typeof md === 'function') {\n callback = md;\n md = null;\n }\n\n // use native implementation if possible and not disabled, note that\n // some node versions only support SHA-1, others allow digest to be changed\n if(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n crypto.pbkdf2 && (md === null || typeof md !== 'object') &&\n (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {\n if(typeof md !== 'string') {\n // default prf to SHA-1\n md = 'sha1';\n }\n p = Buffer.from(p, 'binary');\n s = Buffer.from(s, 'binary');\n if(!callback) {\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');\n }\n return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');\n }\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n\n if(typeof md === 'undefined' || md === null) {\n // default prf to SHA-1\n md = 'sha1';\n }\n if(typeof md === 'string') {\n if(!(md in forge.md.algorithms)) {\n throw new Error('Unknown hash algorithm: ' + md);\n }\n md = forge.md[md].create();\n }\n\n var hLen = md.digestLength;\n\n /* 1. If dkLen > (2^32 - 1) * hLen, output \"derived key too long\" and\n stop. */\n if(dkLen > (0xFFFFFFFF * hLen)) {\n var err = new Error('Derived key is too long.');\n if(callback) {\n return callback(err);\n }\n throw err;\n }\n\n /* 2. Let len be the number of hLen-octet blocks in the derived key,\n rounding up, and let r be the number of octets in the last\n block:\n\n len = CEIL(dkLen / hLen),\n r = dkLen - (len - 1) * hLen. */\n var len = Math.ceil(dkLen / hLen);\n var r = dkLen - (len - 1) * hLen;\n\n /* 3. For each block of the derived key apply the function F defined\n below to the password P, the salt S, the iteration count c, and\n the block index to compute the block:\n\n T_1 = F(P, S, c, 1),\n T_2 = F(P, S, c, 2),\n ...\n T_len = F(P, S, c, len),\n\n where the function F is defined as the exclusive-or sum of the\n first c iterates of the underlying pseudorandom function PRF\n applied to the password P and the concatenation of the salt S\n and the block index i:\n\n F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c\n\n where\n\n u_1 = PRF(P, S || INT(i)),\n u_2 = PRF(P, u_1),\n ...\n u_c = PRF(P, u_{c-1}).\n\n Here, INT(i) is a four-octet encoding of the integer i, most\n significant octet first. */\n var prf = forge.hmac.create();\n prf.start(md, p);\n var dk = '';\n var xor, u_c, u_c1;\n\n // sync version\n if(!callback) {\n for(var i = 1; i <= len; ++i) {\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n for(var j = 2; j <= c; ++j) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n }\n /* 5. Output the derived key DK. */\n return dk;\n }\n\n // async version\n var i = 1, j;\n function outer() {\n if(i > len) {\n // done\n return callback(null, dk);\n }\n\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n j = 2;\n inner();\n }\n\n function inner() {\n if(j <= c) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n ++j;\n return forge.util.setImmediate(inner);\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n\n ++i;\n outer();\n }\n\n outer();\n};\n","/**\n * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.\n *\n * See FIPS 180-2 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha256 = module.exports = forge.sha256 = forge.sha256 || {};\nforge.md.sha256 = forge.md.algorithms.sha256 = sha256;\n\n/**\n * Creates a SHA-256 message digest object.\n *\n * @return a message digest object.\n */\nsha256.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-256 state contains eight 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(64);\n\n // message digest object\n var md = {\n algorithm: 'sha256',\n blockLength: 64,\n digestLength: 32,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x6A09E667,\n h1: 0xBB67AE85,\n h2: 0x3C6EF372,\n h3: 0xA54FF53A,\n h4: 0x510E527F,\n h5: 0x9B05688C,\n h6: 0x1F83D9AB,\n h7: 0x5BE0CD19\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-256 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4,\n h5: _state.h5,\n h6: _state.h6,\n h7: _state.h7\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n rval.putInt32(s2.h5);\n rval.putInt32(s2.h6);\n rval.putInt32(s2.h7);\n return rval;\n };\n\n return md;\n};\n\n// sha-256 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // create K table for SHA-256\n _k = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-256 state with the given byte buffer.\n *\n * @param s the SHA-256 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 64 32-bit words according to SHA-256\n for(i = 0; i < 16; ++i) {\n w[i] = bytes.getInt32();\n }\n for(; i < 64; ++i) {\n // XOR word 2 words ago rot right 17, rot right 19, shft right 10\n t1 = w[i - 2];\n t1 =\n ((t1 >>> 17) | (t1 << 15)) ^\n ((t1 >>> 19) | (t1 << 13)) ^\n (t1 >>> 10);\n // XOR word 15 words ago rot right 7, rot right 18, shft right 3\n t2 = w[i - 15];\n t2 =\n ((t2 >>> 7) | (t2 << 25)) ^\n ((t2 >>> 18) | (t2 << 14)) ^\n (t2 >>> 3);\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32\n w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;\n }\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n f = s.h5;\n g = s.h6;\n h = s.h7;\n\n // round function\n for(i = 0; i < 64; ++i) {\n // Sum1(e)\n s1 =\n ((e >>> 6) | (e << 26)) ^\n ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch = g ^ (e & (f ^ g));\n // Sum0(a)\n s0 =\n ((a >>> 2) | (a << 30)) ^\n ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj = (a & b) | (c & (a ^ b));\n\n // main algorithm\n t1 = h + s1 + ch + _k[i] + w[i];\n t2 = s0 + maj;\n h = g;\n g = f;\n f = e;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n // can't truncate with `| 0`\n a = (t1 + t2) >>> 0;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n s.h5 = (s.h5 + f) | 0;\n s.h6 = (s.h6 + g) | 0;\n s.h7 = (s.h7 + h) | 0;\n len -= 64;\n }\n}\n","/**\n * A javascript implementation of a cryptographically-secure\n * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed\n * here though the use of SHA-256 is not enforced; when generating an\n * a PRNG context, the hashing algorithm and block cipher used for\n * the generator are specified via a plugin.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = require('crypto');\n}\n\n/* PRNG API */\nvar prng = module.exports = forge.prng = forge.prng || {};\n\n/**\n * Creates a new PRNG context.\n *\n * A PRNG plugin must be passed in that will provide:\n *\n * 1. A function that initializes the key and seed of a PRNG context. It\n * will be given a 16 byte key and a 16 byte seed. Any key expansion\n * or transformation of the seed from a byte string into an array of\n * integers (or similar) should be performed.\n * 2. The cryptographic function used by the generator. It takes a key and\n * a seed.\n * 3. A seed increment function. It takes the seed and returns seed + 1.\n * 4. An api to create a message digest.\n *\n * For an example, see random.js.\n *\n * @param plugin the PRNG plugin to use.\n */\nprng.create = function(plugin) {\n var ctx = {\n plugin: plugin,\n key: null,\n seed: null,\n time: null,\n // number of reseeds so far\n reseeds: 0,\n // amount of data generated so far\n generated: 0,\n // no initial key bytes\n keyBytes: ''\n };\n\n // create 32 entropy pools (each is a message digest)\n var md = plugin.md;\n var pools = new Array(32);\n for(var i = 0; i < 32; ++i) {\n pools[i] = md.create();\n }\n ctx.pools = pools;\n\n // entropy pools are written to cyclically, starting at index 0\n ctx.pool = 0;\n\n /**\n * Generates random bytes. The bytes may be generated synchronously or\n * asynchronously. Web workers must use the asynchronous interface or\n * else the behavior is undefined.\n *\n * @param count the number of random bytes to generate.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return count random bytes as a string.\n */\n ctx.generate = function(count, callback) {\n // do synchronously\n if(!callback) {\n return ctx.generateSync(count);\n }\n\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n var b = forge.util.createBuffer();\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generate` call\n ctx.key = null;\n\n generate();\n\n function generate(err) {\n if(err) {\n return callback(err);\n }\n\n // sufficient bytes generated\n if(b.length() >= count) {\n return callback(null, b.getBytes(count));\n }\n\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n // prevent stack overflow\n return forge.util.nextTick(function() {\n _reseed(generate);\n });\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n\n forge.util.setImmediate(generate);\n }\n };\n\n /**\n * Generates random bytes synchronously.\n *\n * @param count the number of random bytes to generate.\n *\n * @return count random bytes as a string.\n */\n ctx.generateSync = function(count) {\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generateSync` call\n ctx.key = null;\n\n var b = forge.util.createBuffer();\n while(b.length() < count) {\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n _reseedSync();\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n }\n\n return b.getBytes(count);\n };\n\n /**\n * Private function that asynchronously reseeds a generator.\n *\n * @param callback(err) called once the operation completes.\n */\n function _reseed(callback) {\n if(ctx.pools[0].messageLength >= 32) {\n _seed();\n return callback();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.seedFile(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n ctx.collect(bytes);\n _seed();\n callback();\n });\n }\n\n /**\n * Private function that synchronously reseeds a generator.\n */\n function _reseedSync() {\n if(ctx.pools[0].messageLength >= 32) {\n return _seed();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.collect(ctx.seedFileSync(needed));\n _seed();\n }\n\n /**\n * Private function that seeds a generator once enough bytes are available.\n */\n function _seed() {\n // update reseed count\n ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;\n\n // goal is to update `key` via:\n // key = hash(key + s)\n // where 's' is all collected entropy from selected pools, then...\n\n // create a plugin-based message digest\n var md = ctx.plugin.md.create();\n\n // consume current key bytes\n md.update(ctx.keyBytes);\n\n // digest the entropy of pools whose index k meet the\n // condition 'n mod 2^k == 0' where n is the number of reseeds\n var _2powK = 1;\n for(var k = 0; k < 32; ++k) {\n if(ctx.reseeds % _2powK === 0) {\n md.update(ctx.pools[k].digest().getBytes());\n ctx.pools[k].start();\n }\n _2powK = _2powK << 1;\n }\n\n // get digest for key bytes\n ctx.keyBytes = md.digest().getBytes();\n\n // paranoid deviation from Fortuna:\n // update `seed` via `seed = hash(key)`\n // instead of initializing to zero once and only\n // ever incrementing it\n md.start();\n md.update(ctx.keyBytes);\n var seedBytes = md.digest().getBytes();\n\n // update state\n ctx.key = ctx.plugin.formatKey(ctx.keyBytes);\n ctx.seed = ctx.plugin.formatSeed(seedBytes);\n ctx.generated = 0;\n }\n\n /**\n * The built-in default seedFile. This seedFile is used when entropy\n * is needed immediately.\n *\n * @param needed the number of bytes that are needed.\n *\n * @return the random bytes.\n */\n function defaultSeedFile(needed) {\n // use window.crypto.getRandomValues strong source of entropy if available\n var getRandomValues = null;\n var globalScope = forge.util.globalScope;\n var _crypto = globalScope.crypto || globalScope.msCrypto;\n if(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n }\n\n var b = forge.util.createBuffer();\n if(getRandomValues) {\n while(b.length() < needed) {\n // max byte length is 65536 before QuotaExceededError is thrown\n // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues\n var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);\n var entropy = new Uint32Array(Math.floor(count));\n try {\n getRandomValues(entropy);\n for(var i = 0; i < entropy.length; ++i) {\n b.putInt32(entropy[i]);\n }\n } catch(e) {\n /* only ignore QuotaExceededError */\n if(!(typeof QuotaExceededError !== 'undefined' &&\n e instanceof QuotaExceededError)) {\n throw e;\n }\n }\n }\n }\n\n // be sad and add some weak random data\n if(b.length() < needed) {\n /* Draws from Park-Miller \"minimal standard\" 31 bit PRNG,\n implemented with David G. Carta's optimization: with 32 bit math\n and without division (Public Domain). */\n var hi, lo, next;\n var seed = Math.floor(Math.random() * 0x010000);\n while(b.length() < needed) {\n lo = 16807 * (seed & 0xFFFF);\n hi = 16807 * (seed >> 16);\n lo += (hi & 0x7FFF) << 16;\n lo += hi >> 15;\n lo = (lo & 0x7FFFFFFF) + (lo >> 31);\n seed = lo & 0xFFFFFFFF;\n\n // consume lower 3 bytes of seed\n for(var i = 0; i < 3; ++i) {\n // throw in more pseudo random\n next = seed >>> (i << 3);\n next ^= Math.floor(Math.random() * 0x0100);\n b.putByte(String.fromCharCode(next & 0xFF));\n }\n }\n }\n\n return b.getBytes(needed);\n }\n // initialize seed file APIs\n if(_crypto) {\n // use nodejs async API\n ctx.seedFile = function(needed, callback) {\n _crypto.randomBytes(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n callback(null, bytes.toString());\n });\n };\n // use nodejs sync API\n ctx.seedFileSync = function(needed) {\n return _crypto.randomBytes(needed).toString();\n };\n } else {\n ctx.seedFile = function(needed, callback) {\n try {\n callback(null, defaultSeedFile(needed));\n } catch(e) {\n callback(e);\n }\n };\n ctx.seedFileSync = defaultSeedFile;\n }\n\n /**\n * Adds entropy to a prng ctx's accumulator.\n *\n * @param bytes the bytes of entropy as a string.\n */\n ctx.collect = function(bytes) {\n // iterate over pools distributing entropy cyclically\n var count = bytes.length;\n for(var i = 0; i < count; ++i) {\n ctx.pools[ctx.pool].update(bytes.substr(i, 1));\n ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;\n }\n };\n\n /**\n * Collects an integer of n bits.\n *\n * @param i the integer entropy.\n * @param n the number of bits in the integer.\n */\n ctx.collectInt = function(i, n) {\n var bytes = '';\n for(var x = 0; x < n; x += 8) {\n bytes += String.fromCharCode((i >> x) & 0xFF);\n }\n ctx.collect(bytes);\n };\n\n /**\n * Registers a Web Worker to receive immediate entropy from the main thread.\n * This method is required until Web Workers can access the native crypto\n * API. This method should be called twice for each created worker, once in\n * the main thread, and once in the worker itself.\n *\n * @param worker the worker to register.\n */\n ctx.registerWorker = function(worker) {\n // worker receives random bytes\n if(worker === self) {\n ctx.seedFile = function(needed, callback) {\n function listener(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n self.removeEventListener('message', listener);\n callback(data.forge.prng.err, data.forge.prng.bytes);\n }\n }\n self.addEventListener('message', listener);\n self.postMessage({forge: {prng: {needed: needed}}});\n };\n } else {\n // main thread sends random bytes upon request\n var listener = function(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n ctx.seedFile(data.forge.prng.needed, function(err, bytes) {\n worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});\n });\n }\n };\n // TODO: do we need to remove the event listener when the worker dies?\n worker.addEventListener('message', listener);\n }\n };\n\n return ctx;\n};\n","/**\n * An API for getting cryptographically-secure random bytes. The bytes are\n * generated using the Fortuna algorithm devised by Bruce Schneier and\n * Niels Ferguson.\n *\n * Getting strong random bytes is not yet easy to do in javascript. The only\n * truish random entropy that can be collected is from the mouse, keyboard, or\n * from timing with respect to page loads, etc. This generator makes a poor\n * attempt at providing random bytes when those sources haven't yet provided\n * enough entropy to initially seed or to reseed the PRNG.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./sha256');\nrequire('./prng');\nrequire('./util');\n\n(function() {\n\n// forge.random already defined\nif(forge.random && forge.random.getBytes) {\n module.exports = forge.random;\n return;\n}\n\n(function(jQuery) {\n\n// the default prng plugin, uses AES-128\nvar prng_aes = {};\nvar _prng_aes_output = new Array(4);\nvar _prng_aes_buffer = forge.util.createBuffer();\nprng_aes.formatKey = function(key) {\n // convert the key into 32-bit integers\n var tmp = forge.util.createBuffer(key);\n key = new Array(4);\n key[0] = tmp.getInt32();\n key[1] = tmp.getInt32();\n key[2] = tmp.getInt32();\n key[3] = tmp.getInt32();\n\n // return the expanded key\n return forge.aes._expandKey(key, false);\n};\nprng_aes.formatSeed = function(seed) {\n // convert seed into 32-bit integers\n var tmp = forge.util.createBuffer(seed);\n seed = new Array(4);\n seed[0] = tmp.getInt32();\n seed[1] = tmp.getInt32();\n seed[2] = tmp.getInt32();\n seed[3] = tmp.getInt32();\n return seed;\n};\nprng_aes.cipher = function(key, seed) {\n forge.aes._updateBlock(key, seed, _prng_aes_output, false);\n _prng_aes_buffer.putInt32(_prng_aes_output[0]);\n _prng_aes_buffer.putInt32(_prng_aes_output[1]);\n _prng_aes_buffer.putInt32(_prng_aes_output[2]);\n _prng_aes_buffer.putInt32(_prng_aes_output[3]);\n return _prng_aes_buffer.getBytes();\n};\nprng_aes.increment = function(seed) {\n // FIXME: do we care about carry or signed issues?\n ++seed[3];\n return seed;\n};\nprng_aes.md = forge.md.sha256;\n\n/**\n * Creates a new PRNG.\n */\nfunction spawnPrng() {\n var ctx = forge.prng.create(prng_aes);\n\n /**\n * Gets random bytes. If a native secure crypto API is unavailable, this\n * method tries to make the bytes more unpredictable by drawing from data that\n * can be collected from the user of the browser, eg: mouse movement.\n *\n * If a callback is given, this method will be called asynchronously.\n *\n * @param count the number of random bytes to get.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytes = function(count, callback) {\n return ctx.generate(count, callback);\n };\n\n /**\n * Gets random bytes asynchronously. If a native secure crypto API is\n * unavailable, this method tries to make the bytes more unpredictable by\n * drawing from data that can be collected from the user of the browser,\n * eg: mouse movement.\n *\n * @param count the number of random bytes to get.\n *\n * @return the random bytes in a string.\n */\n ctx.getBytesSync = function(count) {\n return ctx.generate(count);\n };\n\n return ctx;\n}\n\n// create default prng context\nvar _ctx = spawnPrng();\n\n// add other sources of entropy only if window.crypto.getRandomValues is not\n// available -- otherwise this source will be automatically used by the prng\nvar getRandomValues = null;\nvar globalScope = forge.util.globalScope;\nvar _crypto = globalScope.crypto || globalScope.msCrypto;\nif(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n}\n\nif(forge.options.usePureJavaScript ||\n (!forge.util.isNodejs && !getRandomValues)) {\n // if this is a web worker, do not use weak entropy, instead register to\n // receive strong entropy asynchronously from the main thread\n if(typeof window === 'undefined' || window.document === undefined) {\n // FIXME:\n }\n\n // get load time entropy\n _ctx.collectInt(+new Date(), 32);\n\n // add some entropy from navigator object\n if(typeof(navigator) !== 'undefined') {\n var _navBytes = '';\n for(var key in navigator) {\n try {\n if(typeof(navigator[key]) == 'string') {\n _navBytes += navigator[key];\n }\n } catch(e) {\n /* Some navigator keys might not be accessible, e.g. the geolocation\n attribute throws an exception if touched in Mozilla chrome://\n context.\n\n Silently ignore this and just don't use this as a source of\n entropy. */\n }\n }\n _ctx.collect(_navBytes);\n _navBytes = null;\n }\n\n // add mouse and keyboard collectors if jquery is available\n if(jQuery) {\n // set up mouse entropy capture\n jQuery().mousemove(function(e) {\n // add mouse coords\n _ctx.collectInt(e.clientX, 16);\n _ctx.collectInt(e.clientY, 16);\n });\n\n // set up keyboard entropy capture\n jQuery().keypress(function(e) {\n _ctx.collectInt(e.charCode, 8);\n });\n }\n}\n\n/* Random API */\nif(!forge.random) {\n forge.random = _ctx;\n} else {\n // extend forge.random with _ctx\n for(var key in _ctx) {\n forge.random[key] = _ctx[key];\n }\n}\n\n// expose spawn PRNG\nforge.random.createInstance = spawnPrng;\n\nmodule.exports = forge.random;\n\n})(typeof(jQuery) !== 'undefined' ? jQuery : null);\n\n})();\n","/**\n * RC2 implementation.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n *\n * Information on the RC2 cipher is available from RFC #2268,\n * http://www.ietf.org/rfc/rfc2268.txt\n */\nvar forge = require('./forge');\nrequire('./util');\n\nvar piTable = [\n 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,\n 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,\n 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,\n 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,\n 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,\n 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,\n 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,\n 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,\n 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,\n 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,\n 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,\n 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,\n 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,\n 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,\n 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,\n 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad\n];\n\nvar s = [1, 2, 3, 5];\n\n/**\n * Rotate a word left by given number of bits.\n *\n * Bits that are shifted out on the left are put back in on the right\n * hand side.\n *\n * @param word The word to shift left.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar rol = function(word, bits) {\n return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));\n};\n\n/**\n * Rotate a word right by given number of bits.\n *\n * Bits that are shifted out on the right are put back in on the left\n * hand side.\n *\n * @param word The word to shift right.\n * @param bits The number of bits to shift by.\n * @return The rotated word.\n */\nvar ror = function(word, bits) {\n return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);\n};\n\n/* RC2 API */\nmodule.exports = forge.rc2 = forge.rc2 || {};\n\n/**\n * Perform RC2 key expansion as per RFC #2268, section 2.\n *\n * @param key variable-length user key (between 1 and 128 bytes)\n * @param effKeyBits number of effective key bits (default: 128)\n * @return the expanded RC2 key (ByteBuffer of 128 bytes)\n */\nforge.rc2.expandKey = function(key, effKeyBits) {\n if(typeof key === 'string') {\n key = forge.util.createBuffer(key);\n }\n effKeyBits = effKeyBits || 128;\n\n /* introduce variables that match the names used in RFC #2268 */\n var L = key;\n var T = key.length();\n var T1 = effKeyBits;\n var T8 = Math.ceil(T1 / 8);\n var TM = 0xff >> (T1 & 0x07);\n var i;\n\n for(i = T; i < 128; i++) {\n L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);\n }\n\n L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);\n\n for(i = 127 - T8; i >= 0; i--) {\n L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);\n }\n\n return L;\n};\n\n/**\n * Creates a RC2 cipher object.\n *\n * @param key the symmetric key to use (as base for key generation).\n * @param bits the number of effective key bits.\n * @param encrypt false for decryption, true for encryption.\n *\n * @return the cipher.\n */\nvar createCipher = function(key, bits, encrypt) {\n var _finish = false, _input = null, _output = null, _iv = null;\n var mixRound, mashRound;\n var i, j, K = [];\n\n /* Expand key and fill into K[] Array */\n key = forge.rc2.expandKey(key, bits);\n for(i = 0; i < 64; i++) {\n K.push(key.getInt16Le());\n }\n\n if(encrypt) {\n /**\n * Perform one mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n R[i] = rol(R[i], s[i]);\n j++;\n }\n };\n\n /**\n * Perform one mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 0; i < 4; i++) {\n R[i] += K[R[(i + 3) % 4] & 63];\n }\n };\n } else {\n /**\n * Perform one r-mixing round \"in place\".\n *\n * @param R Array of four words to perform mixing on.\n */\n mixRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] = ror(R[i], s[i]);\n R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +\n ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);\n j--;\n }\n };\n\n /**\n * Perform one r-mashing round \"in place\".\n *\n * @param R Array of four words to perform mashing on.\n */\n mashRound = function(R) {\n for(i = 3; i >= 0; i--) {\n R[i] -= K[R[(i + 3) % 4] & 63];\n }\n };\n }\n\n /**\n * Run the specified cipher execution plan.\n *\n * This function takes four words from the input buffer, applies the IV on\n * it (if requested) and runs the provided execution plan.\n *\n * The plan must be put together in form of a array of arrays. Where the\n * outer one is simply a list of steps to perform and the inner one needs\n * to have two elements: the first one telling how many rounds to perform,\n * the second one telling what to do (i.e. the function to call).\n *\n * @param {Array} plan The plan to execute.\n */\n var runPlan = function(plan) {\n var R = [];\n\n /* Get data from input buffer and fill the four words into R */\n for(i = 0; i < 4; i++) {\n var val = _input.getInt16Le();\n\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting, apply the IV first. */\n val ^= _iv.getInt16Le();\n } else {\n /* We're decryption, keep cipher text for next block. */\n _iv.putInt16Le(val);\n }\n }\n\n R.push(val & 0xffff);\n }\n\n /* Reset global \"j\" variable as per spec. */\n j = encrypt ? 0 : 63;\n\n /* Run execution plan. */\n for(var ptr = 0; ptr < plan.length; ptr++) {\n for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {\n plan[ptr][1](R);\n }\n }\n\n /* Write back result to output buffer. */\n for(i = 0; i < 4; i++) {\n if(_iv !== null) {\n if(encrypt) {\n /* We're encrypting in CBC-mode, feed back encrypted bytes into\n IV buffer to carry it forward to next block. */\n _iv.putInt16Le(R[i]);\n } else {\n R[i] ^= _iv.getInt16Le();\n }\n }\n\n _output.putInt16Le(R[i]);\n }\n };\n\n /* Create cipher object */\n var cipher = null;\n cipher = {\n /**\n * Starts or restarts the encryption or decryption process, whichever\n * was previously configured.\n *\n * To use the cipher in CBC mode, iv may be given either as a string\n * of bytes, or as a byte buffer. For ECB mode, give null as iv.\n *\n * @param iv the initialization vector to use, null for ECB mode.\n * @param output the output the buffer to write to, null to create one.\n */\n start: function(iv, output) {\n if(iv) {\n /* CBC mode */\n if(typeof iv === 'string') {\n iv = forge.util.createBuffer(iv);\n }\n }\n\n _finish = false;\n _input = forge.util.createBuffer();\n _output = output || new forge.util.createBuffer();\n _iv = iv;\n\n cipher.output = _output;\n },\n\n /**\n * Updates the next block.\n *\n * @param input the buffer to read from.\n */\n update: function(input) {\n if(!_finish) {\n // not finishing, so fill the input buffer with more input\n _input.putBuffer(input);\n }\n\n while(_input.length() >= 8) {\n runPlan([\n [ 5, mixRound ],\n [ 1, mashRound ],\n [ 6, mixRound ],\n [ 1, mashRound ],\n [ 5, mixRound ]\n ]);\n }\n },\n\n /**\n * Finishes encrypting or decrypting.\n *\n * @param pad a padding function to use, null for PKCS#7 padding,\n * signature(blockSize, buffer, decrypt).\n *\n * @return true if successful, false on error.\n */\n finish: function(pad) {\n var rval = true;\n\n if(encrypt) {\n if(pad) {\n rval = pad(8, _input, !encrypt);\n } else {\n // add PKCS#7 padding to block (each pad byte is the\n // value of the number of pad bytes)\n var padding = (_input.length() === 8) ? 8 : (8 - _input.length());\n _input.fillWithByte(padding, padding);\n }\n }\n\n if(rval) {\n // do final update\n _finish = true;\n cipher.update();\n }\n\n if(!encrypt) {\n // check for error: input data not a multiple of block size\n rval = (_input.length() === 0);\n if(rval) {\n if(pad) {\n rval = pad(8, _output, !encrypt);\n } else {\n // ensure padding byte count is valid\n var len = _output.length();\n var count = _output.at(len - 1);\n\n if(count > len) {\n rval = false;\n } else {\n // trim off padding bytes\n _output.truncate(count);\n }\n }\n }\n }\n\n return rval;\n }\n };\n\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startEncrypting = function(key, iv, output) {\n var cipher = forge.rc2.createEncryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start encrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createEncryptionCipher = function(key, bits) {\n return createCipher(key, bits, true);\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key. The output will be stored in the 'output' member\n * of the returned cipher.\n *\n * The key and iv may be given as a string of bytes or a byte buffer.\n * The cipher is initialized to use 128 effective key bits.\n *\n * @param key the symmetric key to use.\n * @param iv the initialization vector to use.\n * @param output the buffer to write to, null to create one.\n *\n * @return the cipher.\n */\nforge.rc2.startDecrypting = function(key, iv, output) {\n var cipher = forge.rc2.createDecryptionCipher(key, 128);\n cipher.start(iv, output);\n return cipher;\n};\n\n/**\n * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the\n * given symmetric key.\n *\n * The key may be given as a string of bytes or a byte buffer.\n *\n * To start decrypting call start() on the cipher with an iv and optional\n * output buffer.\n *\n * @param key the symmetric key to use.\n *\n * @return the cipher.\n */\nforge.rc2.createDecryptionCipher = function(key, bits) {\n return createCipher(key, bits, false);\n};\n","// Copyright (c) 2005 Tom Wu\n// All Rights Reserved.\n// See \"LICENSE\" for details.\n\n// Basic JavaScript BN library - subset useful for RSA encryption.\n\n/*\nLicensing (LICENSE)\n-------------------\n\nThis software is covered under the following copyright:\n*/\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n/*\nAddress all questions regarding this license to:\n\n Tom Wu\n tjw@cs.Stanford.EDU\n*/\nvar forge = require('./forge');\n\nmodule.exports = forge.jsbn = forge.jsbn || {};\n\n// Bits per digit\nvar dbits;\n\n// JavaScript engine analysis\nvar canary = 0xdeadbeefcafe;\nvar j_lm = ((canary&0xffffff)==0xefcafe);\n\n// (public) Constructor\nfunction BigInteger(a,b,c) {\n this.data = [];\n if(a != null)\n if(\"number\" == typeof a) this.fromNumber(a,b,c);\n else if(b == null && \"string\" != typeof a) this.fromString(a,256);\n else this.fromString(a,b);\n}\nforge.jsbn.BigInteger = BigInteger;\n\n// return new, unset BigInteger\nfunction nbi() { return new BigInteger(null); }\n\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i,x,w,j,c,n) {\n while(--n >= 0) {\n var v = x*this.data[i++]+w.data[j]+c;\n c = Math.floor(v/0x4000000);\n w.data[j++] = v&0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i,x,w,j,c,n) {\n var xl = x&0x7fff, xh = x>>15;\n while(--n >= 0) {\n var l = this.data[i]&0x7fff;\n var h = this.data[i++]>>15;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);\n c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);\n w.data[j++] = l&0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i,x,w,j,c,n) {\n var xl = x&0x3fff, xh = x>>14;\n while(--n >= 0) {\n var l = this.data[i]&0x3fff;\n var h = this.data[i++]>>14;\n var m = xh*l+h*xl;\n l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;\n c = (l>>28)+(m>>14)+xh*h;\n w.data[j++] = l&0xfffffff;\n }\n return c;\n}\n\n// node.js (no browser)\nif(typeof(navigator) === 'undefined')\n{\n BigInteger.prototype.am = am3;\n dbits = 28;\n} else if(j_lm && (navigator.appName == \"Microsoft Internet Explorer\")) {\n BigInteger.prototype.am = am2;\n dbits = 30;\n} else if(j_lm && (navigator.appName != \"Netscape\")) {\n BigInteger.prototype.am = am1;\n dbits = 26;\n} else { // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\n\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = ((1<= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}\n\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = (x<0)?-1:0;\n if(x > 0) this.data[0] = x;\n else if(x < -1) this.data[0] = x+this.DV;\n else this.t = 0;\n}\n\n// return bigint initialized to value\nfunction nbv(i) { var r = nbi(); r.fromInt(i); return r; }\n\n// (protected) set from string and radix\nfunction bnpFromString(s,b) {\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 256) k = 8; // byte array\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else { this.fromRadix(s,b); return; }\n this.t = 0;\n this.s = 0;\n var i = s.length, mi = false, sh = 0;\n while(--i >= 0) {\n var x = (k==8)?s[i]&0xff:intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\") mi = true;\n continue;\n }\n mi = false;\n if(sh == 0)\n this.data[this.t++] = x;\n else if(sh+k > this.DB) {\n this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh));\n } else\n this.data[this.t-1] |= x<= this.DB) sh -= this.DB;\n }\n if(k == 8 && (s[0]&0x80) != 0) {\n this.s = -1;\n if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t;\n}\n\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if(this.s < 0) return \"-\"+this.negate().toString(b);\n var k;\n if(b == 16) k = 4;\n else if(b == 8) k = 3;\n else if(b == 2) k = 1;\n else if(b == 32) k = 5;\n else if(b == 4) k = 2;\n else return this.toRadix(b);\n var km = (1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }\n while(i >= 0) {\n if(p < k) {\n d = (this.data[i]&((1<>(p+=this.DB-k);\n } else {\n d = (this.data[i]>>(p-=k))&km;\n if(p <= 0) { p += this.DB; --i; }\n }\n if(d > 0) m = true;\n if(m) r += int2char(d);\n }\n }\n return m?r:\"0\";\n}\n\n// (public) -this\nfunction bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }\n\n// (public) |this|\nfunction bnAbs() { return (this.s<0)?this.negate():this; }\n\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n var r = this.s-a.s;\n if(r != 0) return r;\n var i = this.t;\n r = i-a.t;\n if(r != 0) return (this.s<0)?-r:r;\n while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;\n return 0;\n}\n\n// returns bit length of the integer x\nfunction nbits(x) {\n var r = 1, t;\n if((t=x>>>16) != 0) { x = t; r += 16; }\n if((t=x>>8) != 0) { x = t; r += 8; }\n if((t=x>>4) != 0) { x = t; r += 4; }\n if((t=x>>2) != 0) { x = t; r += 2; }\n if((t=x>>1) != 0) { x = t; r += 1; }\n return r;\n}\n\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if(this.t <= 0) return 0;\n return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));\n}\n\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n,r) {\n var i;\n for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];\n for(i = n-1; i >= 0; --i) r.data[i] = 0;\n r.t = this.t+n;\n r.s = this.s;\n}\n\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n,r) {\n for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];\n r.t = Math.max(this.t-n,0);\n r.s = this.s;\n}\n\n// (protected) r = this << n\nfunction bnpLShiftTo(n,r) {\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<= 0; --i) {\n r.data[i+ds+1] = (this.data[i]>>cbs)|c;\n c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0;\n r.data[ds] = c;\n r.t = this.t+ds+1;\n r.s = this.s;\n r.clamp();\n}\n\n// (protected) r = this >> n\nfunction bnpRShiftTo(n,r) {\n r.s = this.s;\n var ds = Math.floor(n/this.DB);\n if(ds >= this.t) { r.t = 0; return; }\n var bs = n%this.DB;\n var cbs = this.DB-bs;\n var bm = (1<>bs;\n for(var i = ds+1; i < this.t; ++i) {\n r.data[i-ds-1] |= (this.data[i]&bm)<>bs;\n }\n if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB;\n }\n if(a.t < this.t) {\n c -= a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n } else {\n c += this.s;\n while(i < a.t) {\n c -= a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = (c<0)?-1:0;\n if(c < -1) r.data[i++] = this.DV+c;\n else if(c > 0) r.data[i++] = c;\n r.t = i;\n r.clamp();\n}\n\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a,r) {\n var x = this.abs(), y = a.abs();\n var i = x.t;\n r.t = i+y.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);\n r.s = 0;\n r.clamp();\n if(this.s != a.s) BigInteger.ZERO.subTo(r,r);\n}\n\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n var x = this.abs();\n var i = r.t = 2*x.t;\n while(--i >= 0) r.data[i] = 0;\n for(i = 0; i < x.t-1; ++i) {\n var c = x.am(i,x.data[i],r,2*i,0,1);\n if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {\n r.data[i+x.t] -= x.DV;\n r.data[i+x.t+1] = 1;\n }\n }\n if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);\n r.s = 0;\n r.clamp();\n}\n\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m,q,r) {\n var pm = m.abs();\n if(pm.t <= 0) return;\n var pt = this.abs();\n if(pt.t < pm.t) {\n if(q != null) q.fromInt(0);\n if(r != null) this.copyTo(r);\n return;\n }\n if(r == null) r = nbi();\n var y = nbi(), ts = this.s, ms = m.s;\n var nsh = this.DB-nbits(pm.data[pm.t-1]);\t// normalize modulus\n if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }\n var ys = y.t;\n var y0 = y.data[ys-1];\n if(y0 == 0) return;\n var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0);\n var d1 = this.FV/yt, d2 = (1<= 0) {\n r.data[r.t++] = 1;\n r.subTo(t,r);\n }\n BigInteger.ONE.dlShiftTo(ys,t);\n t.subTo(y,y);\t// \"negative\" y so we can replace sub with am later\n while(y.t < ys) y.data[y.t++] = 0;\n while(--j >= 0) {\n // Estimate quotient digit\n var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);\n if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) {\t// Try it out\n y.dlShiftTo(j,t);\n r.subTo(t,r);\n while(r.data[i] < --qd) r.subTo(t,r);\n }\n }\n if(q != null) {\n r.drShiftTo(ys,q);\n if(ts != ms) BigInteger.ZERO.subTo(q,q);\n }\n r.t = ys;\n r.clamp();\n if(nsh > 0) r.rShiftTo(nsh,r);\t// Denormalize remainder\n if(ts < 0) BigInteger.ZERO.subTo(r,r);\n}\n\n// (public) this mod a\nfunction bnMod(a) {\n var r = nbi();\n this.abs().divRemTo(a,null,r);\n if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);\n return r;\n}\n\n// Modular reduction using \"classic\" algorithm\nfunction Classic(m) { this.m = m; }\nfunction cConvert(x) {\n if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);\n else return x;\n}\nfunction cRevert(x) { return x; }\nfunction cReduce(x) { x.divRemTo(this.m,null,x); }\nfunction cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\nfunction cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\nClassic.prototype.convert = cConvert;\nClassic.prototype.revert = cRevert;\nClassic.prototype.reduce = cReduce;\nClassic.prototype.mulTo = cMulTo;\nClassic.prototype.sqrTo = cSqrTo;\n\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if(this.t < 1) return 0;\n var x = this.data[0];\n if((x&1) == 0) return 0;\n var y = x&3;\t\t// y == 1/x mod 2^2\n y = (y*(2-(x&0xf)*y))&0xf;\t// y == 1/x mod 2^4\n y = (y*(2-(x&0xff)*y))&0xff;\t// y == 1/x mod 2^8\n y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;\t// y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y*(2-x*y%this.DV))%this.DV;\t\t// y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return (y>0)?this.DV-y:-y;\n}\n\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp&0x7fff;\n this.mph = this.mp>>15;\n this.um = (1<<(m.DB-15))-1;\n this.mt2 = 2*m.t;\n}\n\n// xR mod m\nfunction montConvert(x) {\n var r = nbi();\n x.abs().dlShiftTo(this.m.t,r);\n r.divRemTo(this.m,null,r);\n if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);\n return r;\n}\n\n// x/R mod m\nfunction montRevert(x) {\n var r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while(x.t <= this.mt2)\t// pad x so am has enough room later\n x.data[x.t++] = 0;\n for(var i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x.data[i]*mp mod DV\n var j = x.data[i]&0x7fff;\n var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i+this.m.t;\n x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);\n // propagate carry\n while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }\n }\n x.clamp();\n x.drShiftTo(this.m.t,x);\n if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n\n// (protected) true iff this is even\nfunction bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }\n\n// (protected) this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\nfunction bnpExp(e,z) {\n if(e > 0xffffffff || e < 1) return BigInteger.ONE;\n var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;\n g.copyTo(r);\n while(--i >= 0) {\n z.sqrTo(r,r2);\n if((e&(1< 0) z.mulTo(r2,g,r);\n else { var t = r; r = r2; r2 = t; }\n }\n return z.revert(r);\n}\n\n// (public) this^e % m, 0 <= e < 2^32\nfunction bnModPowInt(e,m) {\n var z;\n if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);\n return this.exp(e,z);\n}\n\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.isEven = bnpIsEven;\nBigInteger.prototype.exp = bnpExp;\n\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.modPowInt = bnModPowInt;\n\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n\n// jsbn2 lib\n\n//Copyright (c) 2005-2009 Tom Wu\n//All Rights Reserved.\n//See \"LICENSE\" for details (See jsbn.js for LICENSE).\n\n//Extended JavaScript BN functions, required for RSA private ops.\n\n//Version 1.1: new BigInteger(\"0\", 10) returns \"proper\" zero\n\n//(public)\nfunction bnClone() { var r = nbi(); this.copyTo(r); return r; }\n\n//(public) return value as integer\nfunction bnIntValue() {\nif(this.s < 0) {\n if(this.t == 1) return this.data[0]-this.DV;\n else if(this.t == 0) return -1;\n} else if(this.t == 1) return this.data[0];\nelse if(this.t == 0) return 0;\n// assumes 16 < DB < 32\nreturn ((this.data[1]&((1<<(32-this.DB))-1))<>24; }\n\n//(public) return value as short (assumes DB>=16)\nfunction bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }\n\n//(protected) return x s.t. r^x < DV\nfunction bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }\n\n//(public) 0 if this == 0, 1 if this > 0\nfunction bnSigNum() {\nif(this.s < 0) return -1;\nelse if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;\nelse return 1;\n}\n\n//(protected) convert to radix string\nfunction bnpToRadix(b) {\nif(b == null) b = 10;\nif(this.signum() == 0 || b < 2 || b > 36) return \"0\";\nvar cs = this.chunkSize(b);\nvar a = Math.pow(b,cs);\nvar d = nbv(a), y = nbi(), z = nbi(), r = \"\";\nthis.divRemTo(d,y,z);\nwhile(y.signum() > 0) {\n r = (a+z.intValue()).toString(b).substr(1) + r;\n y.divRemTo(d,y,z);\n}\nreturn z.intValue().toString(b) + r;\n}\n\n//(protected) convert from radix string\nfunction bnpFromRadix(s,b) {\nthis.fromInt(0);\nif(b == null) b = 10;\nvar cs = this.chunkSize(b);\nvar d = Math.pow(b,cs), mi = false, j = 0, w = 0;\nfor(var i = 0; i < s.length; ++i) {\n var x = intAt(s,i);\n if(x < 0) {\n if(s.charAt(i) == \"-\" && this.signum() == 0) mi = true;\n continue;\n }\n w = b*w+x;\n if(++j >= cs) {\n this.dMultiply(d);\n this.dAddOffset(w,0);\n j = 0;\n w = 0;\n }\n}\nif(j > 0) {\n this.dMultiply(Math.pow(b,j));\n this.dAddOffset(w,0);\n}\nif(mi) BigInteger.ZERO.subTo(this,this);\n}\n\n//(protected) alternate constructor\nfunction bnpFromNumber(a,b,c) {\nif(\"number\" == typeof b) {\n // new BigInteger(int,int,RNG)\n if(a < 2) this.fromInt(1);\n else {\n this.fromNumber(a,c);\n if(!this.testBit(a-1)) // force MSB set\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);\n if(this.isEven()) this.dAddOffset(1,0); // force odd\n while(!this.isProbablePrime(b)) {\n this.dAddOffset(2,0);\n if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);\n }\n }\n} else {\n // new BigInteger(int,RNG)\n var x = new Array(), t = a&7;\n x.length = (a>>3)+1;\n b.nextBytes(x);\n if(t > 0) x[0] &= ((1< 0) {\n if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)\n r[k++] = d|(this.s<<(this.DB-p));\n while(i >= 0) {\n if(p < 8) {\n d = (this.data[i]&((1<>(p+=this.DB-8);\n } else {\n d = (this.data[i]>>(p-=8))&0xff;\n if(p <= 0) { p += this.DB; --i; }\n }\n if((d&0x80) != 0) d |= -256;\n if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;\n if(k > 0 || d != this.s) r[k++] = d;\n }\n}\nreturn r;\n}\n\nfunction bnEquals(a) { return(this.compareTo(a)==0); }\nfunction bnMin(a) { return(this.compareTo(a)<0)?this:a; }\nfunction bnMax(a) { return(this.compareTo(a)>0)?this:a; }\n\n//(protected) r = this op a (bitwise)\nfunction bnpBitwiseTo(a,op,r) {\nvar i, f, m = Math.min(a.t,this.t);\nfor(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);\nif(a.t < this.t) {\n f = a.s&this.DM;\n for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);\n r.t = this.t;\n} else {\n f = this.s&this.DM;\n for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);\n r.t = a.t;\n}\nr.s = op(this.s,a.s);\nr.clamp();\n}\n\n//(public) this & a\nfunction op_and(x,y) { return x&y; }\nfunction bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }\n\n//(public) this | a\nfunction op_or(x,y) { return x|y; }\nfunction bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }\n\n//(public) this ^ a\nfunction op_xor(x,y) { return x^y; }\nfunction bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }\n\n//(public) this & ~a\nfunction op_andnot(x,y) { return x&~y; }\nfunction bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }\n\n//(public) ~this\nfunction bnNot() {\nvar r = nbi();\nfor(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];\nr.t = this.t;\nr.s = ~this.s;\nreturn r;\n}\n\n//(public) this << n\nfunction bnShiftLeft(n) {\nvar r = nbi();\nif(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);\nreturn r;\n}\n\n//(public) this >> n\nfunction bnShiftRight(n) {\nvar r = nbi();\nif(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);\nreturn r;\n}\n\n//return index of lowest 1-bit in x, x < 2^31\nfunction lbit(x) {\nif(x == 0) return -1;\nvar r = 0;\nif((x&0xffff) == 0) { x >>= 16; r += 16; }\nif((x&0xff) == 0) { x >>= 8; r += 8; }\nif((x&0xf) == 0) { x >>= 4; r += 4; }\nif((x&3) == 0) { x >>= 2; r += 2; }\nif((x&1) == 0) ++r;\nreturn r;\n}\n\n//(public) returns index of lowest 1-bit (or -1 if none)\nfunction bnGetLowestSetBit() {\nfor(var i = 0; i < this.t; ++i)\n if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);\nif(this.s < 0) return this.t*this.DB;\nreturn -1;\n}\n\n//return number of 1 bits in x\nfunction cbit(x) {\nvar r = 0;\nwhile(x != 0) { x &= x-1; ++r; }\nreturn r;\n}\n\n//(public) return number of set bits\nfunction bnBitCount() {\nvar r = 0, x = this.s&this.DM;\nfor(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);\nreturn r;\n}\n\n//(public) true iff nth bit is set\nfunction bnTestBit(n) {\nvar j = Math.floor(n/this.DB);\nif(j >= this.t) return(this.s!=0);\nreturn((this.data[j]&(1<<(n%this.DB)))!=0);\n}\n\n//(protected) this op (1<>= this.DB;\n}\nif(a.t < this.t) {\n c += a.s;\n while(i < this.t) {\n c += this.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += this.s;\n} else {\n c += this.s;\n while(i < a.t) {\n c += a.data[i];\n r.data[i++] = c&this.DM;\n c >>= this.DB;\n }\n c += a.s;\n}\nr.s = (c<0)?-1:0;\nif(c > 0) r.data[i++] = c;\nelse if(c < -1) r.data[i++] = this.DV+c;\nr.t = i;\nr.clamp();\n}\n\n//(public) this + a\nfunction bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }\n\n//(public) this - a\nfunction bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }\n\n//(public) this * a\nfunction bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }\n\n//(public) this / a\nfunction bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }\n\n//(public) this % a\nfunction bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }\n\n//(public) [this/a,this%a]\nfunction bnDivideAndRemainder(a) {\nvar q = nbi(), r = nbi();\nthis.divRemTo(a,q,r);\nreturn new Array(q,r);\n}\n\n//(protected) this *= n, this >= 0, 1 < n < DV\nfunction bnpDMultiply(n) {\nthis.data[this.t] = this.am(0,n-1,this,0,0,this.t);\n++this.t;\nthis.clamp();\n}\n\n//(protected) this += n << w words, this >= 0\nfunction bnpDAddOffset(n,w) {\nif(n == 0) return;\nwhile(this.t <= w) this.data[this.t++] = 0;\nthis.data[w] += n;\nwhile(this.data[w] >= this.DV) {\n this.data[w] -= this.DV;\n if(++w >= this.t) this.data[this.t++] = 0;\n ++this.data[w];\n}\n}\n\n//A \"null\" reducer\nfunction NullExp() {}\nfunction nNop(x) { return x; }\nfunction nMulTo(x,y,r) { x.multiplyTo(y,r); }\nfunction nSqrTo(x,r) { x.squareTo(r); }\n\nNullExp.prototype.convert = nNop;\nNullExp.prototype.revert = nNop;\nNullExp.prototype.mulTo = nMulTo;\nNullExp.prototype.sqrTo = nSqrTo;\n\n//(public) this^e\nfunction bnPow(e) { return this.exp(e,new NullExp()); }\n\n//(protected) r = lower n words of \"this * a\", a.t <= n\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyLowerTo(a,n,r) {\nvar i = Math.min(this.t+a.t,n);\nr.s = 0; // assumes a,this >= 0\nr.t = i;\nwhile(i > 0) r.data[--i] = 0;\nvar j;\nfor(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);\nfor(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);\nr.clamp();\n}\n\n//(protected) r = \"this * a\" without lower n words, n > 0\n//\"this\" should be the larger one if appropriate.\nfunction bnpMultiplyUpperTo(a,n,r) {\n--n;\nvar i = r.t = this.t+a.t-n;\nr.s = 0; // assumes a,this >= 0\nwhile(--i >= 0) r.data[i] = 0;\nfor(i = Math.max(n-this.t,0); i < a.t; ++i)\n r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);\nr.clamp();\nr.drShiftTo(1,r);\n}\n\n//Barrett modular reduction\nfunction Barrett(m) {\n// setup Barrett\nthis.r2 = nbi();\nthis.q3 = nbi();\nBigInteger.ONE.dlShiftTo(2*m.t,this.r2);\nthis.mu = this.r2.divide(m);\nthis.m = m;\n}\n\nfunction barrettConvert(x) {\nif(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);\nelse if(x.compareTo(this.m) < 0) return x;\nelse { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }\n}\n\nfunction barrettRevert(x) { return x; }\n\n//x = x mod m (HAC 14.42)\nfunction barrettReduce(x) {\nx.drShiftTo(this.m.t-1,this.r2);\nif(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\nthis.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\nthis.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\nwhile(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\nx.subTo(this.r2,x);\nwhile(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}\n\n//r = x^2 mod m; x != r\nfunction barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\n\n//r = x*y mod m; x,y != r\nfunction barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\n\nBarrett.prototype.convert = barrettConvert;\nBarrett.prototype.revert = barrettRevert;\nBarrett.prototype.reduce = barrettReduce;\nBarrett.prototype.mulTo = barrettMulTo;\nBarrett.prototype.sqrTo = barrettSqrTo;\n\n//(public) this^e % m (HAC 14.85)\nfunction bnModPow(e,m) {\nvar i = e.bitLength(), k, r = nbv(1), z;\nif(i <= 0) return r;\nelse if(i < 18) k = 1;\nelse if(i < 48) k = 3;\nelse if(i < 144) k = 4;\nelse if(i < 768) k = 5;\nelse k = 6;\nif(i < 8)\n z = new Classic(m);\nelse if(m.isEven())\n z = new Barrett(m);\nelse\n z = new Montgomery(m);\n\n// precomputation\nvar g = new Array(), n = 3, k1 = k-1, km = (1< 1) {\n var g2 = nbi();\n z.sqrTo(g[1],g2);\n while(n <= km) {\n g[n] = nbi();\n z.mulTo(g2,g[n-2],g[n]);\n n += 2;\n }\n}\n\nvar j = e.t-1, w, is1 = true, r2 = nbi(), t;\ni = nbits(e.data[j])-1;\nwhile(j >= 0) {\n if(i >= k1) w = (e.data[j]>>(i-k1))&km;\n else {\n w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);\n if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);\n }\n\n n = k;\n while((w&1) == 0) { w >>= 1; --n; }\n if((i -= n) < 0) { i += this.DB; --j; }\n if(is1) { // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n } else {\n while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }\n if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }\n z.mulTo(r2,g[w],r);\n }\n\n while(j >= 0 && (e.data[j]&(1< 0) {\n x.rShiftTo(g,x);\n y.rShiftTo(g,y);\n}\nwhile(x.signum() > 0) {\n if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);\n if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);\n if(x.compareTo(y) >= 0) {\n x.subTo(y,x);\n x.rShiftTo(1,x);\n } else {\n y.subTo(x,y);\n y.rShiftTo(1,y);\n }\n}\nif(g > 0) y.lShiftTo(g,y);\nreturn y;\n}\n\n//(protected) this % n, n < 2^26\nfunction bnpModInt(n) {\nif(n <= 0) return 0;\nvar d = this.DV%n, r = (this.s<0)?n-1:0;\nif(this.t > 0)\n if(d == 0) r = this.data[0]%n;\n else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;\nreturn r;\n}\n\n//(public) 1/this % m (HAC 14.61)\nfunction bnModInverse(m) {\nvar ac = m.isEven();\nif((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;\nvar u = m.clone(), v = this.clone();\nvar a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);\nwhile(u.signum() != 0) {\n while(u.isEven()) {\n u.rShiftTo(1,u);\n if(ac) {\n if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }\n a.rShiftTo(1,a);\n } else if(!b.isEven()) b.subTo(m,b);\n b.rShiftTo(1,b);\n }\n while(v.isEven()) {\n v.rShiftTo(1,v);\n if(ac) {\n if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }\n c.rShiftTo(1,c);\n } else if(!d.isEven()) d.subTo(m,d);\n d.rShiftTo(1,d);\n }\n if(u.compareTo(v) >= 0) {\n u.subTo(v,u);\n if(ac) a.subTo(c,a);\n b.subTo(d,b);\n } else {\n v.subTo(u,v);\n if(ac) c.subTo(a,c);\n d.subTo(b,d);\n }\n}\nif(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;\nif(d.compareTo(m) >= 0) return d.subtract(m);\nif(d.signum() < 0) d.addTo(m,d); else return d;\nif(d.signum() < 0) return d.add(m); else return d;\n}\n\nvar lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];\nvar lplim = (1<<26)/lowprimes[lowprimes.length-1];\n\n//(public) test primality with certainty >= 1-.5^t\nfunction bnIsProbablePrime(t) {\nvar i, x = this.abs();\nif(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {\n for(i = 0; i < lowprimes.length; ++i)\n if(x.data[0] == lowprimes[i]) return true;\n return false;\n}\nif(x.isEven()) return false;\ni = 1;\nwhile(i < lowprimes.length) {\n var m = lowprimes[i], j = i+1;\n while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];\n m = x.modInt(m);\n while(i < j) if(m%lowprimes[i++] == 0) return false;\n}\nreturn x.millerRabin(t);\n}\n\n//(protected) true if probably prime (HAC 4.24, Miller-Rabin)\nfunction bnpMillerRabin(t) {\nvar n1 = this.subtract(BigInteger.ONE);\nvar k = n1.getLowestSetBit();\nif(k <= 0) return false;\nvar r = n1.shiftRight(k);\nvar prng = bnGetPrng();\nvar a;\nfor(var i = 0; i < t; ++i) {\n // select witness 'a' at random from between 1 and n1\n do {\n a = new BigInteger(this.bitLength(), prng);\n }\n while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0);\n var y = a.modPow(r,this);\n if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {\n var j = 1;\n while(j++ < k && y.compareTo(n1) != 0) {\n y = y.modPowInt(2,this);\n if(y.compareTo(BigInteger.ONE) == 0) return false;\n }\n if(y.compareTo(n1) != 0) return false;\n }\n}\nreturn true;\n}\n\n// get pseudo random number generator\nfunction bnGetPrng() {\n // create prng with api that matches BigInteger secure random\n return {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n for(var i = 0; i < x.length; ++i) {\n x[i] = Math.floor(Math.random() * 0x0100);\n }\n }\n };\n}\n\n//protected\nBigInteger.prototype.chunkSize = bnpChunkSize;\nBigInteger.prototype.toRadix = bnpToRadix;\nBigInteger.prototype.fromRadix = bnpFromRadix;\nBigInteger.prototype.fromNumber = bnpFromNumber;\nBigInteger.prototype.bitwiseTo = bnpBitwiseTo;\nBigInteger.prototype.changeBit = bnpChangeBit;\nBigInteger.prototype.addTo = bnpAddTo;\nBigInteger.prototype.dMultiply = bnpDMultiply;\nBigInteger.prototype.dAddOffset = bnpDAddOffset;\nBigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;\nBigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;\nBigInteger.prototype.modInt = bnpModInt;\nBigInteger.prototype.millerRabin = bnpMillerRabin;\n\n//public\nBigInteger.prototype.clone = bnClone;\nBigInteger.prototype.intValue = bnIntValue;\nBigInteger.prototype.byteValue = bnByteValue;\nBigInteger.prototype.shortValue = bnShortValue;\nBigInteger.prototype.signum = bnSigNum;\nBigInteger.prototype.toByteArray = bnToByteArray;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.min = bnMin;\nBigInteger.prototype.max = bnMax;\nBigInteger.prototype.and = bnAnd;\nBigInteger.prototype.or = bnOr;\nBigInteger.prototype.xor = bnXor;\nBigInteger.prototype.andNot = bnAndNot;\nBigInteger.prototype.not = bnNot;\nBigInteger.prototype.shiftLeft = bnShiftLeft;\nBigInteger.prototype.shiftRight = bnShiftRight;\nBigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;\nBigInteger.prototype.bitCount = bnBitCount;\nBigInteger.prototype.testBit = bnTestBit;\nBigInteger.prototype.setBit = bnSetBit;\nBigInteger.prototype.clearBit = bnClearBit;\nBigInteger.prototype.flipBit = bnFlipBit;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.remainder = bnRemainder;\nBigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;\nBigInteger.prototype.modPow = bnModPow;\nBigInteger.prototype.modInverse = bnModInverse;\nBigInteger.prototype.pow = bnPow;\nBigInteger.prototype.gcd = bnGCD;\nBigInteger.prototype.isProbablePrime = bnIsProbablePrime;\n\n//BigInteger interfaces not implemented in jsbn:\n\n//BigInteger(int signum, byte[] magnitude)\n//double doubleValue()\n//float floatValue()\n//int hashCode()\n//long longValue()\n//static BigInteger valueOf(long val)\n","/**\n * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha1 = module.exports = forge.sha1 = forge.sha1 || {};\nforge.md.sha1 = forge.md.algorithms.sha1 = sha1;\n\n/**\n * Creates a SHA-1 message digest object.\n *\n * @return a message digest object.\n */\nsha1.create = function() {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n // SHA-1 state contains five 32-bit integers\n var _state = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for word storage\n var _w = new Array(80);\n\n // message digest object\n var md = {\n algorithm: 'sha1',\n blockLength: 64,\n digestLength: 20,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 8\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength64 for backwards-compatibility)\n md.fullMessageLength = md.messageLength64 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476,\n h4: 0xC3D2E1F0\n };\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_state, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-1 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 448 mod 512. In other words,\n the data to be digested must be a multiple of 512 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 8 bytes (64\n bits), that means that the last segment of the data must have 56 bytes\n (448 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 448 mod 512 because\n 512 - 128 = 448.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 448 mod 512, then 512 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var s2 = {\n h0: _state.h0,\n h1: _state.h1,\n h2: _state.h2,\n h3: _state.h3,\n h4: _state.h4\n };\n _update(s2, _w, finalBlock);\n var rval = forge.util.createBuffer();\n rval.putInt32(s2.h0);\n rval.putInt32(s2.h1);\n rval.putInt32(s2.h2);\n rval.putInt32(s2.h3);\n rval.putInt32(s2.h4);\n return rval;\n };\n\n return md;\n};\n\n// sha-1 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 64);\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-1 state with the given byte buffer.\n *\n * @param s the SHA-1 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, e, f, i;\n var len = bytes.length();\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 80 32-bit words according to SHA-1 algorithm\n // and for 32-79 using Max Locktyukhin's optimization\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n\n // round 1\n for(i = 0; i < 16; ++i) {\n t = bytes.getInt32();\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 20; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 2\n for(; i < 32; ++i) {\n t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);\n t = (t << 1) | (t >>> 31);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n for(; i < 40; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 3\n for(; i < 60; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = (b & c) | (d & (b ^ c));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n // round 4\n for(; i < 80; ++i) {\n t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);\n t = (t << 2) | (t >>> 30);\n w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;\n e = d;\n d = c;\n // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug\n c = ((b << 30) | (b >>> 2)) >>> 0;\n b = a;\n a = t;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n\n len -= 64;\n }\n}\n","/**\n * Partial implementation of PKCS#1 v2.2: RSA-OEAP\n *\n * Modified but based on the following MIT and BSD licensed code:\n *\n * https://github.com/kjur/jsjws/blob/master/rsa.js:\n *\n * The 'jsjws'(JSON Web Signature JavaScript Library) License\n *\n * Copyright (c) 2012 Kenji Urushima\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:\n *\n * RSAES-OAEP.js\n * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $\n * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)\n * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.\n * Contact: ellis@nukinetics.com\n * Distributed under the BSD License.\n *\n * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125\n *\n * @author Evan Jones (http://evanjones.ca/)\n * @author Dave Longley\n *\n * Copyright (c) 2013-2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./sha1');\n\n// shortcut for PKCS#1 API\nvar pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};\n\n/**\n * Encode the given RSAES-OAEP message (M) using key, with optional label (L)\n * and seed.\n *\n * This method does not perform RSA encryption, it only encodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param message the message to encode.\n * @param options the options to use:\n * label an optional label to use.\n * seed the seed to use.\n * md the message digest object to use, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the encoded message bytes.\n */\npkcs1.encode_rsa_oaep = function(key, message, options) {\n // parse arguments\n var label;\n var seed;\n var md;\n var mgf1Md;\n // legacy args (label, seed, md)\n if(typeof options === 'string') {\n label = options;\n seed = arguments[3] || undefined;\n md = arguments[4] || undefined;\n } else if(options) {\n label = options.label || undefined;\n seed = options.seed || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // default OAEP to SHA-1 message digest\n if(!md) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n // compute length in bytes and check output\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n var maxLength = keyLength - 2 * md.digestLength - 2;\n if(message.length > maxLength) {\n var error = new Error('RSAES-OAEP input message length is too long.');\n error.length = message.length;\n error.maxLength = maxLength;\n throw error;\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest();\n\n var PS = '';\n var PS_length = maxLength - message.length;\n for(var i = 0; i < PS_length; i++) {\n PS += '\\x00';\n }\n\n var DB = lHash.getBytes() + PS + '\\x01' + message;\n\n if(!seed) {\n seed = forge.random.getBytes(md.digestLength);\n } else if(seed.length !== md.digestLength) {\n var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +\n 'match the digest length.');\n error.seedLength = seed.length;\n error.digestLength = md.digestLength;\n throw error;\n }\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);\n\n // return encoded message\n return '\\x00' + maskedSeed + maskedDB;\n};\n\n/**\n * Decode the given RSAES-OAEP encoded message (EM) using key, with optional\n * label (L).\n *\n * This method does not perform RSA decryption, it only decodes the message\n * using RSAES-OAEP.\n *\n * @param key the RSA key to use.\n * @param em the encoded message to decode.\n * @param options the options to use:\n * label an optional label to use.\n * md the message digest object to use for OAEP, undefined for SHA-1.\n * mgf1 optional mgf1 parameters:\n * md the message digest object to use for MGF1.\n *\n * @return the decoded message bytes.\n */\npkcs1.decode_rsa_oaep = function(key, em, options) {\n // parse args\n var label;\n var md;\n var mgf1Md;\n // legacy args\n if(typeof options === 'string') {\n label = options;\n md = arguments[3] || undefined;\n } else if(options) {\n label = options.label || undefined;\n md = options.md || undefined;\n if(options.mgf1 && options.mgf1.md) {\n mgf1Md = options.mgf1.md;\n }\n }\n\n // compute length in bytes\n var keyLength = Math.ceil(key.n.bitLength() / 8);\n\n if(em.length !== keyLength) {\n var error = new Error('RSAES-OAEP encoded message length is invalid.');\n error.length = em.length;\n error.expectedLength = keyLength;\n throw error;\n }\n\n // default OAEP to SHA-1 message digest\n if(md === undefined) {\n md = forge.md.sha1.create();\n } else {\n md.start();\n }\n\n // default MGF-1 to same as OAEP\n if(!mgf1Md) {\n mgf1Md = md;\n }\n\n if(keyLength < 2 * md.digestLength + 2) {\n throw new Error('RSAES-OAEP key is too short for the hash function.');\n }\n\n if(!label) {\n label = '';\n }\n md.update(label, 'raw');\n var lHash = md.digest().getBytes();\n\n // split the message into its parts\n var y = em.charAt(0);\n var maskedSeed = em.substring(1, md.digestLength + 1);\n var maskedDB = em.substring(1 + md.digestLength);\n\n var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);\n var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);\n\n var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);\n var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);\n\n var lHashPrime = db.substring(0, md.digestLength);\n\n // constant time check that all values match what is expected\n var error = (y !== '\\x00');\n\n // constant time check lHash vs lHashPrime\n for(var i = 0; i < md.digestLength; ++i) {\n error |= (lHash.charAt(i) !== lHashPrime.charAt(i));\n }\n\n // \"constant time\" find the 0x1 byte separating the padding (zeros) from the\n // message\n // TODO: It must be possible to do this in a better/smarter way?\n var in_ps = 1;\n var index = md.digestLength;\n for(var j = md.digestLength; j < db.length; j++) {\n var code = db.charCodeAt(j);\n\n var is_0 = (code & 0x1) ^ 0x1;\n\n // non-zero if not 0 or 1 in the ps section\n var error_mask = in_ps ? 0xfffe : 0x0000;\n error |= (code & error_mask);\n\n // latch in_ps to zero after we find 0x1\n in_ps = in_ps & is_0;\n index += in_ps;\n }\n\n if(error || db.charCodeAt(index) !== 0x1) {\n throw new Error('Invalid RSAES-OAEP padding.');\n }\n\n return db.substring(index + 1);\n};\n\nfunction rsa_mgf1(seed, maskLength, hash) {\n // default to SHA-1 message digest\n if(!hash) {\n hash = forge.md.sha1.create();\n }\n var t = '';\n var count = Math.ceil(maskLength / hash.digestLength);\n for(var i = 0; i < count; ++i) {\n var c = String.fromCharCode(\n (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);\n hash.start();\n hash.update(seed + c);\n t += hash.digest().getBytes();\n }\n return t.substring(0, maskLength);\n}\n","/**\n * Prime number generation API.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./jsbn');\nrequire('./random');\n\n(function() {\n\n// forge.prime already defined\nif(forge.prime) {\n module.exports = forge.prime;\n return;\n}\n\n/* PRIME API */\nvar prime = module.exports = forge.prime = forge.prime || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\nvar THIRTY = new BigInteger(null);\nTHIRTY.fromInt(30);\nvar op_or = function(x, y) {return x|y;};\n\n/**\n * Generates a random probable prime with the given number of bits.\n *\n * Alternative algorithms can be specified by name as a string or as an\n * object with custom options like so:\n *\n * {\n * name: 'PRIMEINC',\n * options: {\n * maxBlockTime: ,\n * millerRabinTests: ,\n * workerScript: ,\n * workers: .\n * workLoad: the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * }\n * }\n *\n * @param bits the number of bits for the prime number.\n * @param options the options to use.\n * [algorithm] the algorithm to use (default: 'PRIMEINC').\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n *\n * @return callback(err, num) called once the operation completes.\n */\nprime.generateProbablePrime = function(bits, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // default to PRIMEINC algorithm\n var algorithm = options.algorithm || 'PRIMEINC';\n if(typeof algorithm === 'string') {\n algorithm = {name: algorithm};\n }\n algorithm.options = algorithm.options || {};\n\n // create prng with api that matches BigInteger secure random\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n if(algorithm.name === 'PRIMEINC') {\n return primeincFindPrime(bits, rng, algorithm.options, callback);\n }\n\n throw new Error('Invalid prime generation algorithm: ' + algorithm.name);\n};\n\nfunction primeincFindPrime(bits, rng, options, callback) {\n if('workers' in options) {\n return primeincFindPrimeWithWorkers(bits, rng, options, callback);\n }\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n}\n\nfunction primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {\n // initialize random number\n var num = generateRandom(bits, rng);\n\n /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The\n number we are given is always aligned at 30k + 1. Each time the number is\n determined not to be prime we add to get to the next 'i', eg: if the number\n was at 30k + 1 we add 6. */\n var deltaIdx = 0;\n\n // get required number of MR tests\n var mrTests = getMillerRabinTests(num.bitLength());\n if('millerRabinTests' in options) {\n mrTests = options.millerRabinTests;\n }\n\n // find prime nearest to 'num' for maxBlockTime ms\n // 10 ms gives 5ms of leeway for other calculations before dropping\n // below 60fps (1000/60 == 16.67), but in reality, the number will\n // likely be higher due to an 'atomic' big int modPow\n var maxBlockTime = 10;\n if('maxBlockTime' in options) {\n maxBlockTime = options.maxBlockTime;\n }\n\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n}\n\nfunction _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {\n var start = +new Date();\n do {\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n // do primality test\n if(num.isProbablePrime(mrTests)) {\n return callback(null, num);\n }\n // get next potential prime\n num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));\n\n // keep trying later\n forge.util.setImmediate(function() {\n _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);\n });\n}\n\n// NOTE: This algorithm is indeterminate in nature because workers\n// run in parallel looking at different segments of numbers. Even if this\n// algorithm is run twice with the same input from a predictable RNG, it\n// may produce different outputs.\nfunction primeincFindPrimeWithWorkers(bits, rng, options, callback) {\n // web workers unavailable\n if(typeof Worker === 'undefined') {\n return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);\n }\n\n // initialize random number\n var num = generateRandom(bits, rng);\n\n // use web workers to generate keys\n var numWorkers = options.workers;\n var workLoad = options.workLoad || 100;\n var range = workLoad * 30 / 8;\n var workerScript = options.workerScript || 'forge/prime.worker.js';\n if(numWorkers === -1) {\n return forge.util.estimateCores(function(err, cores) {\n if(err) {\n // default to 2\n cores = 2;\n }\n numWorkers = cores - 1;\n generate();\n });\n }\n generate();\n\n function generate() {\n // require at least 1 worker\n numWorkers = Math.max(1, numWorkers);\n\n // TODO: consider optimizing by starting workers outside getPrime() ...\n // note that in order to clean up they will have to be made internally\n // asynchronous which may actually be slower\n\n // start workers immediately\n var workers = [];\n for(var i = 0; i < numWorkers; ++i) {\n // FIXME: fix path or use blob URLs\n workers[i] = new Worker(workerScript);\n }\n var running = numWorkers;\n\n // listen for requests from workers and assign ranges to find prime\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].addEventListener('message', workerMessage);\n }\n\n /* Note: The distribution of random numbers is unknown. Therefore, each\n web worker is continuously allocated a range of numbers to check for a\n random number until one is found.\n\n Every 30 numbers will be checked just 8 times, because prime numbers\n have the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)\n\n Therefore, if we want a web worker to run N checks before asking for\n a new range of numbers, each range must contain N*30/8 numbers.\n\n For 100 checks (workLoad), this is a range of 375. */\n\n var found = false;\n function workerMessage(e) {\n // ignore message, prime already found\n if(found) {\n return;\n }\n\n --running;\n var data = e.data;\n if(data.found) {\n // terminate all workers\n for(var i = 0; i < workers.length; ++i) {\n workers[i].terminate();\n }\n found = true;\n return callback(null, new BigInteger(data.prime, 16));\n }\n\n // overflow, regenerate random number\n if(num.bitLength() > bits) {\n num = generateRandom(bits, rng);\n }\n\n // assign new range to check\n var hex = num.toString(16);\n\n // start prime search\n e.target.postMessage({\n hex: hex,\n workLoad: workLoad\n });\n\n num.dAddOffset(range, 0);\n }\n }\n}\n\n/**\n * Generates a random number using the given number of bits and RNG.\n *\n * @param bits the number of bits for the number.\n * @param rng the random number generator to use.\n *\n * @return the random number.\n */\nfunction generateRandom(bits, rng) {\n var num = new BigInteger(bits, rng);\n // force MSB set\n var bits1 = bits - 1;\n if(!num.testBit(bits1)) {\n num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);\n }\n // align number on 30k+1 boundary\n num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);\n return num;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n})();\n","/**\n * Javascript implementation of basic RSA algorithms.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The only algorithm currently supported for PKI is RSA.\n *\n * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo\n * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier\n * and a subjectPublicKey of type bit string.\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of RSA, there aren't any.\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * For an RSA public key, the subjectPublicKey is:\n *\n * RSAPublicKey ::= SEQUENCE {\n * modulus INTEGER, -- n\n * publicExponent INTEGER -- e\n * }\n *\n * PrivateKeyInfo ::= SEQUENCE {\n * version Version,\n * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,\n * privateKey PrivateKey,\n * attributes [0] IMPLICIT Attributes OPTIONAL\n * }\n *\n * Version ::= INTEGER\n * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier\n * PrivateKey ::= OCTET STRING\n * Attributes ::= SET OF Attribute\n *\n * An RSA private key as the following structure:\n *\n * RSAPrivateKey ::= SEQUENCE {\n * version Version,\n * modulus INTEGER, -- n\n * publicExponent INTEGER, -- e\n * privateExponent INTEGER, -- d\n * prime1 INTEGER, -- p\n * prime2 INTEGER, -- q\n * exponent1 INTEGER, -- d mod (p-1)\n * exponent2 INTEGER, -- d mod (q-1)\n * coefficient INTEGER -- (inverse of q) mod p\n * }\n *\n * Version ::= INTEGER\n *\n * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./jsbn');\nrequire('./oids');\nrequire('./pkcs1');\nrequire('./prime');\nrequire('./random');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar _crypto = forge.util.isNodejs ? require('crypto') : null;\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for util API\nvar util = forge.util;\n\n/*\n * RSA encryption and decryption, see RFC 2313.\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};\nvar pki = forge.pki;\n\n// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29\nvar GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];\n\n// validator for a PrivateKeyInfo structure\nvar privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\n// validator for an RSA private key\nvar rsaPrivateKeyValidator = {\n // RSAPrivateKey\n name: 'RSAPrivateKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'RSAPrivateKey.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // modulus (n)\n name: 'RSAPrivateKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPrivateKey.publicExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPublicExponent'\n }, {\n // privateExponent (d)\n name: 'RSAPrivateKey.privateExponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrivateExponent'\n }, {\n // prime1 (p)\n name: 'RSAPrivateKey.prime1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime1'\n }, {\n // prime2 (q)\n name: 'RSAPrivateKey.prime2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyPrime2'\n }, {\n // exponent1 (d mod (p-1))\n name: 'RSAPrivateKey.exponent1',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent1'\n }, {\n // exponent2 (d mod (q-1))\n name: 'RSAPrivateKey.exponent2',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyExponent2'\n }, {\n // coefficient ((inverse of q) mod p)\n name: 'RSAPrivateKey.coefficient',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyCoefficient'\n }]\n};\n\n// validator for an RSA public key\nvar rsaPublicKeyValidator = {\n // RSAPublicKey\n name: 'RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // modulus (n)\n name: 'RSAPublicKey.modulus',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyModulus'\n }, {\n // publicExponent (e)\n name: 'RSAPublicKey.exponent',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'publicKeyExponent'\n }]\n};\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n }, {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n }]\n};\n\n/**\n * Wrap digest in DigestInfo object.\n *\n * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * @param md the message digest object with the hash to sign.\n *\n * @return the encoded message (ready for RSA encrytion)\n */\nvar emsaPkcs1v15encode = function(md) {\n // get the oid for the algorithm\n var oid;\n if(md.algorithm in pki.oids) {\n oid = pki.oids[md.algorithm];\n } else {\n var error = new Error('Unknown message digest algorithm.');\n error.algorithm = md.algorithm;\n throw error;\n }\n var oidBytes = asn1.oidToDer(oid).getBytes();\n\n // create the digest info\n var digestInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var digestAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));\n digestAlgorithm.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));\n var digest = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, md.digest().getBytes());\n digestInfo.value.push(digestAlgorithm);\n digestInfo.value.push(digest);\n\n // encode digest info\n return asn1.toDer(digestInfo).getBytes();\n};\n\n/**\n * Performs x^c mod n (RSA encryption or decryption operation).\n *\n * @param x the number to raise and mod.\n * @param key the key to use.\n * @param pub true if the key is public, false if private.\n *\n * @return the result of x^c mod n.\n */\nvar _modPow = function(x, key, pub) {\n if(pub) {\n return x.modPow(key.e, key.n);\n }\n\n if(!key.p || !key.q) {\n // allow calculation without CRT params (slow)\n return x.modPow(key.d, key.n);\n }\n\n // pre-compute dP, dQ, and qInv if necessary\n if(!key.dP) {\n key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));\n }\n if(!key.dQ) {\n key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));\n }\n if(!key.qInv) {\n key.qInv = key.q.modInverse(key.p);\n }\n\n /* Chinese remainder theorem (CRT) states:\n\n Suppose n1, n2, ..., nk are positive integers which are pairwise\n coprime (n1 and n2 have no common factors other than 1). For any\n integers x1, x2, ..., xk there exists an integer x solving the\n system of simultaneous congruences (where ~= means modularly\n congruent so a ~= b mod n means a mod n = b mod n):\n\n x ~= x1 mod n1\n x ~= x2 mod n2\n ...\n x ~= xk mod nk\n\n This system of congruences has a single simultaneous solution x\n between 0 and n - 1. Furthermore, each xk solution and x itself\n is congruent modulo the product n = n1*n2*...*nk.\n So x1 mod n = x2 mod n = xk mod n = x mod n.\n\n The single simultaneous solution x can be solved with the following\n equation:\n\n x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.\n\n Where x is less than n, xi = x mod ni.\n\n For RSA we are only concerned with k = 2. The modulus n = pq, where\n p and q are coprime. The RSA decryption algorithm is:\n\n y = x^d mod n\n\n Given the above:\n\n x1 = x^d mod p\n r1 = n/p = q\n s1 = q^-1 mod p\n x2 = x^d mod q\n r2 = n/q = p\n s2 = p^-1 mod q\n\n So y = (x1r1s1 + x2r2s2) mod n\n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n\n\n According to Fermat's Little Theorem, if the modulus P is prime,\n for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.\n Since A is not divisible by P it follows that if:\n N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:\n\n A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort\n to calculate). In order to calculate x^d mod p more quickly the\n exponent d mod (p - 1) is stored in the RSA private key (the same\n is done for x^d mod q). These values are referred to as dP and dQ\n respectively. Therefore we now have:\n\n y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n\n\n Since we'll be reducing x^dP by modulo p (same for q) we can also\n reduce x by p (and q respectively) before hand. Therefore, let\n\n xp = ((x mod p)^dP mod p), and\n xq = ((x mod q)^dQ mod q), yielding:\n\n y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n\n\n This can be further reduced to a simple algorithm that only\n requires 1 inverse (the q inverse is used) to be used and stored.\n The algorithm is called Garner's algorithm. If qInv is the\n inverse of q, we simply calculate:\n\n y = (qInv*(xp - xq) mod p) * q + xq\n\n However, there are two further complications. First, we need to\n ensure that xp > xq to prevent signed BigIntegers from being used\n so we add p until this is true (since we will be mod'ing with\n p anyway). Then, there is a known timing attack on algorithms\n using the CRT. To mitigate this risk, \"cryptographic blinding\"\n should be used. This requires simply generating a random number r\n between 0 and n-1 and its inverse and multiplying x by r^e before\n calculating y and then multiplying y by r^-1 afterwards. Note that\n r must be coprime with n (gcd(r, n) === 1) in order to have an\n inverse.\n */\n\n // cryptographic blinding\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),\n 16);\n } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));\n x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);\n\n // calculate xp and xq\n var xp = x.mod(key.p).modPow(key.dP, key.p);\n var xq = x.mod(key.q).modPow(key.dQ, key.q);\n\n // xp must be larger than xq to avoid signed bit usage\n while(xp.compareTo(xq) < 0) {\n xp = xp.add(key.p);\n }\n\n // do last step\n var y = xp.subtract(xq)\n .multiply(key.qInv).mod(key.p)\n .multiply(key.q).add(xq);\n\n // remove effect of random for cryptographic blinding\n y = y.multiply(r.modInverse(key.n)).mod(key.n);\n\n return y;\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or\n * 'encrypt' on a public key object instead.\n *\n * Performs RSA encryption.\n *\n * The parameter bt controls whether to put padding bytes before the\n * message passed in. Set bt to either true or false to disable padding\n * completely (in order to handle e.g. EMSA-PSS encoding seperately before),\n * signaling whether the encryption operation is a public key operation\n * (i.e. encrypting data) or not, i.e. private key operation (data signing).\n *\n * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01\n * (for signing) or 0x02 (for encryption). The key operation mode (private\n * or public) is derived from this flag in that case).\n *\n * @param m the message to encrypt as a byte string.\n * @param key the RSA key to use.\n * @param bt for PKCS#1 v1.5 padding, the block type to use\n * (0x01 for private key, 0x02 for public),\n * to disable padding: true = public key, false = private key.\n *\n * @return the encrypted bytes as a string.\n */\npki.rsa.encrypt = function(m, key, bt) {\n var pub = bt;\n var eb;\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n if(bt !== false && bt !== true) {\n // legacy, default to PKCS#1 v1.5 padding\n pub = (bt === 0x02);\n eb = _encodePkcs1_v1_5(m, key, bt);\n } else {\n eb = forge.util.createBuffer();\n eb.putBytes(m);\n }\n\n // load encryption block as big integer 'x'\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var x = new BigInteger(eb.toHex(), 16);\n\n // do RSA encryption\n var y = _modPow(x, key, pub);\n\n // convert y into the encrypted data byte string, if y is shorter in\n // bytes than k, then prepend zero bytes to fill up ed\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var yhex = y.toString(16);\n var ed = forge.util.createBuffer();\n var zeros = k - Math.ceil(yhex.length / 2);\n while(zeros > 0) {\n ed.putByte(0x00);\n --zeros;\n }\n ed.putBytes(forge.util.hexToBytes(yhex));\n return ed.getBytes();\n};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or\n * 'verify' on a public key object instead.\n *\n * Performs RSA decryption.\n *\n * The parameter ml controls whether to apply PKCS#1 v1.5 padding\n * or not. Set ml = false to disable padding removal completely\n * (in order to handle e.g. EMSA-PSS later on) and simply pass back\n * the RSA encryption block.\n *\n * @param ed the encrypted data to decrypt in as a byte string.\n * @param key the RSA key to use.\n * @param pub true for a public key operation, false for private.\n * @param ml the message length, if known, false to disable padding.\n *\n * @return the decrypted message as a byte string.\n */\npki.rsa.decrypt = function(ed, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n // error if the length of the encrypted data ED is not k\n if(ed.length !== k) {\n var error = new Error('Encrypted message length is invalid.');\n error.length = ed.length;\n error.expected = k;\n throw error;\n }\n\n // convert encrypted data into a big integer\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);\n\n // y must be less than the modulus or it wasn't the result of\n // a previous mod operation (encryption) using that modulus\n if(y.compareTo(key.n) >= 0) {\n throw new Error('Encrypted message is invalid.');\n }\n\n // do RSA decryption\n var x = _modPow(y, key, pub);\n\n // create the encryption block, if x is shorter in bytes than k, then\n // prepend zero bytes to fill up eb\n // FIXME: hex conversion inefficient, get BigInteger w/byte strings\n var xhex = x.toString(16);\n var eb = forge.util.createBuffer();\n var zeros = k - Math.ceil(xhex.length / 2);\n while(zeros > 0) {\n eb.putByte(0x00);\n --zeros;\n }\n eb.putBytes(forge.util.hexToBytes(xhex));\n\n if(ml !== false) {\n // legacy, default to PKCS#1 v1.5 padding\n return _decodePkcs1_v1_5(eb.getBytes(), key, pub);\n }\n\n // return message\n return eb.getBytes();\n};\n\n/**\n * Creates an RSA key-pair generation state object. It is used to allow\n * key-generation to be performed in steps. It also allows for a UI to\n * display progress updates.\n *\n * @param bits the size for the private key in bits, defaults to 2048.\n * @param e the public exponent to use, defaults to 65537 (0x10001).\n * @param [options] the options to use.\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n * algorithm the algorithm to use (default: 'PRIMEINC').\n *\n * @return the state object to use to generate the key-pair.\n */\npki.rsa.createKeyPairGenerationState = function(bits, e, options) {\n // TODO: migrate step-based prime generation code to forge.prime\n\n // set default bits\n if(typeof(bits) === 'string') {\n bits = parseInt(bits, 10);\n }\n bits = bits || 2048;\n\n // create prng with api that matches BigInteger secure random\n options = options || {};\n var prng = options.prng || forge.random;\n var rng = {\n // x is an array to fill with bytes\n nextBytes: function(x) {\n var b = prng.getBytesSync(x.length);\n for(var i = 0; i < x.length; ++i) {\n x[i] = b.charCodeAt(i);\n }\n }\n };\n\n var algorithm = options.algorithm || 'PRIMEINC';\n\n // create PRIMEINC algorithm state\n var rval;\n if(algorithm === 'PRIMEINC') {\n rval = {\n algorithm: algorithm,\n state: 0,\n bits: bits,\n rng: rng,\n eInt: e || 65537,\n e: new BigInteger(null),\n p: null,\n q: null,\n qBits: bits >> 1,\n pBits: bits - (bits >> 1),\n pqState: 0,\n num: null,\n keys: null\n };\n rval.e.fromInt(rval.eInt);\n } else {\n throw new Error('Invalid key generation algorithm: ' + algorithm);\n }\n\n return rval;\n};\n\n/**\n * Attempts to runs the key-generation algorithm for at most n seconds\n * (approximately) using the given state. When key-generation has completed,\n * the keys will be stored in state.keys.\n *\n * To use this function to update a UI while generating a key or to prevent\n * causing browser lockups/warnings, set \"n\" to a value other than 0. A\n * simple pattern for generating a key and showing a progress indicator is:\n *\n * var state = pki.rsa.createKeyPairGenerationState(2048);\n * var step = function() {\n * // step key-generation, run algorithm for 100 ms, repeat\n * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {\n * setTimeout(step, 1);\n * } else {\n * // key-generation complete\n * // TODO: turn off progress indicator here\n * // TODO: use the generated key-pair in \"state.keys\"\n * }\n * };\n * // TODO: turn on progress indicator here\n * setTimeout(step, 0);\n *\n * @param state the state to use.\n * @param n the maximum number of milliseconds to run the algorithm for, 0\n * to run the algorithm to completion.\n *\n * @return true if the key-generation completed, false if not.\n */\npki.rsa.stepKeyPairGenerationState = function(state, n) {\n // set default algorithm if not set\n if(!('algorithm' in state)) {\n state.algorithm = 'PRIMEINC';\n }\n\n // TODO: migrate step-based prime generation code to forge.prime\n // TODO: abstract as PRIMEINC algorithm\n\n // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)\n // with some minor optimizations and designed to run in steps\n\n // local state vars\n var THIRTY = new BigInteger(null);\n THIRTY.fromInt(30);\n var deltaIdx = 0;\n var op_or = function(x, y) {return x | y;};\n\n // keep stepping until time limit is reached or done\n var t1 = +new Date();\n var t2;\n var total = 0;\n while(state.keys === null && (n <= 0 || total < n)) {\n // generate p or q\n if(state.state === 0) {\n /* Note: All primes are of the form:\n\n 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i\n\n When we generate a random number, we always align it at 30k + 1. Each\n time the number is determined not to be prime we add to get to the\n next 'i', eg: if the number was at 30k + 1 we add 6. */\n var bits = (state.p === null) ? state.pBits : state.qBits;\n var bits1 = bits - 1;\n\n // get a random number\n if(state.pqState === 0) {\n state.num = new BigInteger(bits, state.rng);\n // force MSB set\n if(!state.num.testBit(bits1)) {\n state.num.bitwiseTo(\n BigInteger.ONE.shiftLeft(bits1), op_or, state.num);\n }\n // align number on 30k+1 boundary\n state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);\n deltaIdx = 0;\n\n ++state.pqState;\n } else if(state.pqState === 1) {\n // try to make the number a prime\n if(state.num.bitLength() > bits) {\n // overflow, try again\n state.pqState = 0;\n // do primality test\n } else if(state.num.isProbablePrime(\n _getMillerRabinTests(state.num.bitLength()))) {\n ++state.pqState;\n } else {\n // get next potential prime\n state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);\n }\n } else if(state.pqState === 2) {\n // ensure number is coprime with e\n state.pqState =\n (state.num.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) === 0) ? 3 : 0;\n } else if(state.pqState === 3) {\n // store p or q\n state.pqState = 0;\n if(state.p === null) {\n state.p = state.num;\n } else {\n state.q = state.num;\n }\n\n // advance state if both p and q are ready\n if(state.p !== null && state.q !== null) {\n ++state.state;\n }\n state.num = null;\n }\n } else if(state.state === 1) {\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n state.num = state.p;\n state.p = state.q;\n state.q = state.num;\n }\n ++state.state;\n } else if(state.state === 2) {\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n ++state.state;\n } else if(state.state === 3) {\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {\n // phi and e are coprime, advance\n ++state.state;\n } else {\n // phi and e aren't coprime, so generate a new p and q\n state.p = null;\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 4) {\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n\n // ensure n is right number of bits\n if(state.n.bitLength() === state.bits) {\n // success, advance\n ++state.state;\n } else {\n // failed, get new q\n state.q = null;\n state.state = 0;\n }\n } else if(state.state === 5) {\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n }\n\n // update timing\n t2 = +new Date();\n total += t2 - t1;\n t1 = t2;\n }\n\n return state.keys !== null;\n};\n\n/**\n * Generates an RSA public-private key pair in a single call.\n *\n * To generate a key-pair in steps (to allow for progress updates and to\n * prevent blocking or warnings in slow browsers) then use the key-pair\n * generation state functions.\n *\n * To generate a key-pair asynchronously (either through web-workers, if\n * available, or by breaking up the work on the main thread), pass a\n * callback function.\n *\n * @param [bits] the size for the private key in bits, defaults to 2048.\n * @param [e] the public exponent to use, defaults to 65537.\n * @param [options] options for key-pair generation, if given then 'bits'\n * and 'e' must *not* be given:\n * bits the size for the private key in bits, (default: 2048).\n * e the public exponent to use, (default: 65537 (0x10001)).\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * prng a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\". Disables use of native APIs.\n * algorithm the algorithm to use (default: 'PRIMEINC').\n * @param [callback(err, keypair)] called once the operation completes.\n *\n * @return an object with privateKey and publicKey properties.\n */\npki.rsa.generateKeyPair = function(bits, e, options, callback) {\n // (bits), (options), (callback)\n if(arguments.length === 1) {\n if(typeof bits === 'object') {\n options = bits;\n bits = undefined;\n } else if(typeof bits === 'function') {\n callback = bits;\n bits = undefined;\n }\n } else if(arguments.length === 2) {\n // (bits, e), (bits, options), (bits, callback), (options, callback)\n if(typeof bits === 'number') {\n if(typeof e === 'function') {\n callback = e;\n e = undefined;\n } else if(typeof e !== 'number') {\n options = e;\n e = undefined;\n }\n } else {\n options = bits;\n callback = e;\n bits = undefined;\n e = undefined;\n }\n } else if(arguments.length === 3) {\n // (bits, e, options), (bits, e, callback), (bits, options, callback)\n if(typeof e === 'number') {\n if(typeof options === 'function') {\n callback = options;\n options = undefined;\n }\n } else {\n callback = options;\n options = e;\n e = undefined;\n }\n }\n options = options || {};\n if(bits === undefined) {\n bits = options.bits || 2048;\n }\n if(e === undefined) {\n e = options.e || 0x10001;\n }\n\n // use native code if permitted, available, and parameters are acceptable\n if(!forge.options.usePureJavaScript && !options.prng &&\n bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {\n if(callback) {\n // try native async\n if(_detectNodeCrypto('generateKeyPair')) {\n return _crypto.generateKeyPair('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n }, function(err, pub, priv) {\n if(err) {\n return callback(err);\n }\n callback(null, {\n privateKey: pki.privateKeyFromPem(priv),\n publicKey: pki.publicKeyFromPem(pub)\n });\n });\n }\n if(_detectSubtleCrypto('generateKey') &&\n _detectSubtleCrypto('exportKey')) {\n // use standard native generateKey\n return util.globalScope.crypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify'])\n .then(function(pair) {\n return util.globalScope.crypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n // avoiding catch(function(err) {...}) to support IE <= 8\n }).then(undefined, function(err) {\n callback(err);\n }).then(function(pkcs8) {\n if(pkcs8) {\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n }\n });\n }\n if(_detectSubtleMsCrypto('generateKey') &&\n _detectSubtleMsCrypto('exportKey')) {\n var genOp = util.globalScope.msCrypto.subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: _intToUint8Array(e),\n hash: {name: 'SHA-256'}\n }, true /* key can be exported*/, ['sign', 'verify']);\n genOp.oncomplete = function(e) {\n var pair = e.target.result;\n var exportOp = util.globalScope.msCrypto.subtle.exportKey(\n 'pkcs8', pair.privateKey);\n exportOp.oncomplete = function(e) {\n var pkcs8 = e.target.result;\n var privateKey = pki.privateKeyFromAsn1(\n asn1.fromDer(forge.util.createBuffer(pkcs8)));\n callback(null, {\n privateKey: privateKey,\n publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)\n });\n };\n exportOp.onerror = function(err) {\n callback(err);\n };\n };\n genOp.onerror = function(err) {\n callback(err);\n };\n return;\n }\n } else {\n // try native sync\n if(_detectNodeCrypto('generateKeyPairSync')) {\n var keypair = _crypto.generateKeyPairSync('rsa', {\n modulusLength: bits,\n publicExponent: e,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n });\n return {\n privateKey: pki.privateKeyFromPem(keypair.privateKey),\n publicKey: pki.publicKeyFromPem(keypair.publicKey)\n };\n }\n }\n }\n\n // use JavaScript implementation\n var state = pki.rsa.createKeyPairGenerationState(bits, e, options);\n if(!callback) {\n pki.rsa.stepKeyPairGenerationState(state, 0);\n return state.keys;\n }\n _generateKeyPair(state, options, callback);\n};\n\n/**\n * Sets an RSA public key from BigIntegers modulus and exponent.\n *\n * @param n the modulus.\n * @param e the exponent.\n *\n * @return the public key.\n */\npki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {\n var key = {\n n: n,\n e: e\n };\n\n /**\n * Encrypts the given data with this public key. Newer applications\n * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for\n * legacy applications.\n *\n * @param data the byte string to encrypt.\n * @param scheme the encryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA encryption,\n * an object with an 'encode' property set to a function\n * with the signature 'function(data, key)' that returns\n * a binary-encoded string representing the encoded data.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the encrypted byte string.\n */\n key.encrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {\n encode: function(m, key, pub) {\n return _encodePkcs1_v1_5(m, key, 0x02).getBytes();\n }\n };\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n encode: function(m, key) {\n return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {encode: function(e) {return e;}};\n } else if(typeof scheme === 'string') {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // do scheme-based encoding then rsa encryption\n var e = scheme.encode(data, key, true);\n return pki.rsa.encrypt(e, key, true);\n };\n\n /**\n * Verifies the given signature against the given digest.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the\n * signature is an OCTET STRING that holds a DigestInfo.\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n * Digest ::= OCTET STRING\n *\n * To perform PSS signature verification, provide an instance\n * of Forge PSS object as the scheme parameter.\n *\n * @param digest the message digest hash to compare against the signature,\n * as a binary-encoded string.\n * @param signature the signature to verify, as a binary-encoded string.\n * @param scheme signature verification scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be expected, but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return true if the signature was verified, false if not.\n */\n key.verify = function(digest, signature, scheme) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSASSA-PKCS1-V1_5';\n }\n\n if(scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n // d is ASN.1 BER-encoded DigestInfo\n var obj = asn1.fromDer(d);\n // compare the given digest to the decrypted one\n return digest === obj.value[1].value;\n }\n };\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {\n verify: function(digest, d) {\n // remove padding\n d = _decodePkcs1_v1_5(d, key, true);\n return digest === d;\n }\n };\n }\n\n // do rsa decryption w/o any decoding, then verify -- which does decoding\n var d = pki.rsa.decrypt(signature, key, true, false);\n return scheme.verify(digest, d, key.n.bitLength());\n };\n\n return key;\n};\n\n/**\n * Sets an RSA private key from BigIntegers modulus, exponent, primes,\n * prime exponents, and modular multiplicative inverse.\n *\n * @param n the modulus.\n * @param e the public exponent.\n * @param d the private exponent ((inverse of e) mod n).\n * @param p the first prime.\n * @param q the second prime.\n * @param dP exponent1 (d mod (p-1)).\n * @param dQ exponent2 (d mod (q-1)).\n * @param qInv ((inverse of q) mod p)\n *\n * @return the private key.\n */\npki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(\n n, e, d, p, q, dP, dQ, qInv) {\n var key = {\n n: n,\n e: e,\n d: d,\n p: p,\n q: q,\n dP: dP,\n dQ: dQ,\n qInv: qInv\n };\n\n /**\n * Decrypts the given data with this private key. The decryption scheme\n * must match the one used to encrypt the data.\n *\n * @param data the byte string to decrypt.\n * @param scheme the decryption scheme to use:\n * 'RSAES-PKCS1-V1_5' (default),\n * 'RSA-OAEP',\n * 'RAW', 'NONE', or null to perform raw RSA decryption.\n * @param schemeOptions any scheme-specific options.\n *\n * @return the decrypted byte string.\n */\n key.decrypt = function(data, scheme, schemeOptions) {\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n } else if(scheme === undefined) {\n scheme = 'RSAES-PKCS1-V1_5';\n }\n\n // do rsa decryption w/o any decoding\n var d = pki.rsa.decrypt(data, key, false, false);\n\n if(scheme === 'RSAES-PKCS1-V1_5') {\n scheme = {decode: _decodePkcs1_v1_5};\n } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {\n scheme = {\n decode: function(d, key) {\n return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);\n }\n };\n } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {\n scheme = {decode: function(d) {return d;}};\n } else {\n throw new Error('Unsupported encryption scheme: \"' + scheme + '\".');\n }\n\n // decode according to scheme\n return scheme.decode(d, key, false);\n };\n\n /**\n * Signs the given digest, producing a signature.\n *\n * PKCS#1 supports multiple (currently two) signature schemes:\n * RSASSA-PKCS1-V1_5 and RSASSA-PSS.\n *\n * By default this implementation uses the \"old scheme\", i.e.\n * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide\n * an instance of Forge PSS object as the scheme parameter.\n *\n * @param md the message digest object with the hash to sign.\n * @param scheme the signature scheme to use:\n * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,\n * a Forge PSS object for RSASSA-PSS,\n * 'NONE' or null for none, DigestInfo will not be used but\n * PKCS#1 v1.5 padding will still be used.\n *\n * @return the signature as a byte string.\n */\n key.sign = function(md, scheme) {\n /* Note: The internal implementation of RSA operations is being\n transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy\n code like the use of an encoding block identifier 'bt' will eventually\n be removed. */\n\n // private key operation\n var bt = false;\n\n if(typeof scheme === 'string') {\n scheme = scheme.toUpperCase();\n }\n\n if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {\n scheme = {encode: emsaPkcs1v15encode};\n bt = 0x01;\n } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {\n scheme = {encode: function() {return md;}};\n bt = 0x01;\n }\n\n // encode and then encrypt\n var d = scheme.encode(md, key.n.bitLength());\n return pki.rsa.encrypt(d, key, bt);\n };\n\n return key;\n};\n\n/**\n * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.\n *\n * @param rsaKey the ASN.1 RSAPrivateKey.\n *\n * @return the ASN.1 PrivateKeyInfo.\n */\npki.wrapRsaPrivateKey = function(rsaKey) {\n // PrivateKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // privateKeyAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // PrivateKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(rsaKey).getBytes())\n ]);\n};\n\n/**\n * Converts a private key from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a PrivateKeyInfo containing an\n * RSAPrivateKey or an RSAPrivateKey.\n *\n * @return the private key.\n */\npki.privateKeyFromAsn1 = function(obj) {\n // get PrivateKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, privateKeyValidator, capture, errors)) {\n obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));\n }\n\n // get RSAPrivateKey\n capture = {};\n errors = [];\n if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read private key. ' +\n 'ASN.1 object does not contain an RSAPrivateKey.');\n error.errors = errors;\n throw error;\n }\n\n // Note: Version is currently ignored.\n // capture.privateKeyVersion\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n, e, d, p, q, dP, dQ, qInv;\n n = forge.util.createBuffer(capture.privateKeyModulus).toHex();\n e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();\n d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();\n p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();\n q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();\n dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();\n dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();\n qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();\n\n // set private key\n return pki.setRsaPrivateKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16),\n new BigInteger(d, 16),\n new BigInteger(p, 16),\n new BigInteger(q, 16),\n new BigInteger(dP, 16),\n new BigInteger(dQ, 16),\n new BigInteger(qInv, 16));\n};\n\n/**\n * Converts a private key to an ASN.1 RSAPrivateKey.\n *\n * @param key the private key.\n *\n * @return the ASN.1 representation of an RSAPrivateKey.\n */\npki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {\n // RSAPrivateKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (0 = only 2 primes, 1 multiple primes)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(0).getBytes()),\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e)),\n // privateExponent (d)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.d)),\n // privateKeyPrime1 (p)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.p)),\n // privateKeyPrime2 (q)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.q)),\n // privateKeyExponent1 (dP)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dP)),\n // privateKeyExponent2 (dQ)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.dQ)),\n // coefficient (qInv)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.qInv))\n ]);\n};\n\n/**\n * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.\n *\n * @return the public key.\n */\npki.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n if(asn1.validate(obj, publicKeyValidator, capture, errors)) {\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n var error = new Error('Cannot read public key. Unknown OID.');\n error.oid = oid;\n throw error;\n }\n obj = capture.rsaPublicKey;\n }\n\n // get RSA params\n errors = [];\n if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {\n var error = new Error('Cannot read public key. ' +\n 'ASN.1 object does not contain an RSAPublicKey.');\n error.errors = errors;\n throw error;\n }\n\n // FIXME: inefficient, get a BigInteger that uses byte strings\n var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();\n var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();\n\n // set public key\n return pki.setRsaPublicKey(\n new BigInteger(n, 16),\n new BigInteger(e, 16));\n};\n\n/**\n * Converts a public key to an ASN.1 SubjectPublicKeyInfo.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a SubjectPublicKeyInfo.\n */\npki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {\n // SubjectPublicKeyInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // subjectPublicKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [\n pki.publicKeyToRSAPublicKey(key)\n ])\n ]);\n};\n\n/**\n * Converts a public key to an ASN.1 RSAPublicKey.\n *\n * @param key the public key.\n *\n * @return the asn1 representation of a RSAPublicKey.\n */\npki.publicKeyToRSAPublicKey = function(key) {\n // RSAPublicKey\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // modulus (n)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.n)),\n // publicExponent (e)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n _bnToBytes(key.e))\n ]);\n};\n\n/**\n * Encodes a message using PKCS#1 v1.5 padding.\n *\n * @param m the message to encode.\n * @param key the RSA key to use.\n * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02\n * (for encryption).\n *\n * @return the padded byte buffer.\n */\nfunction _encodePkcs1_v1_5(m, key, bt) {\n var eb = forge.util.createBuffer();\n\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* use PKCS#1 v1.5 padding */\n if(m.length > (k - 11)) {\n var error = new Error('Message is too long for PKCS#1 v1.5 padding.');\n error.length = m.length;\n error.max = k - 11;\n throw error;\n }\n\n /* A block type BT, a padding string PS, and the data D shall be\n formatted into an octet string EB, the encryption block:\n\n EB = 00 || BT || PS || 00 || D\n\n The block type BT shall be a single octet indicating the structure of\n the encryption block. For this version of the document it shall have\n value 00, 01, or 02. For a private-key operation, the block type\n shall be 00 or 01. For a public-key operation, it shall be 02.\n\n The padding string PS shall consist of k-3-||D|| octets. For block\n type 00, the octets shall have value 00; for block type 01, they\n shall have value FF; and for block type 02, they shall be\n pseudorandomly generated and nonzero. This makes the length of the\n encryption block EB equal to k. */\n\n // build the encryption block\n eb.putByte(0x00);\n eb.putByte(bt);\n\n // create the padding\n var padNum = k - 3 - m.length;\n var padByte;\n // private key op\n if(bt === 0x00 || bt === 0x01) {\n padByte = (bt === 0x00) ? 0x00 : 0xFF;\n for(var i = 0; i < padNum; ++i) {\n eb.putByte(padByte);\n }\n } else {\n // public key op\n // pad with random non-zero values\n while(padNum > 0) {\n var numZeros = 0;\n var padBytes = forge.random.getBytes(padNum);\n for(var i = 0; i < padNum; ++i) {\n padByte = padBytes.charCodeAt(i);\n if(padByte === 0) {\n ++numZeros;\n } else {\n eb.putByte(padByte);\n }\n }\n padNum = numZeros;\n }\n }\n\n // zero followed by message\n eb.putByte(0x00);\n eb.putBytes(m);\n\n return eb;\n}\n\n/**\n * Decodes a message using PKCS#1 v1.5 padding.\n *\n * @param em the message to decode.\n * @param key the RSA key to use.\n * @param pub true if the key is a public key, false if it is private.\n * @param ml the message length, if specified.\n *\n * @return the decoded bytes.\n */\nfunction _decodePkcs1_v1_5(em, key, pub, ml) {\n // get the length of the modulus in bytes\n var k = Math.ceil(key.n.bitLength() / 8);\n\n /* It is an error if any of the following conditions occurs:\n\n 1. The encryption block EB cannot be parsed unambiguously.\n 2. The padding string PS consists of fewer than eight octets\n or is inconsisent with the block type BT.\n 3. The decryption process is a public-key operation and the block\n type BT is not 00 or 01, or the decryption process is a\n private-key operation and the block type is not 02.\n */\n\n // parse the encryption block\n var eb = forge.util.createBuffer(em);\n var first = eb.getByte();\n var bt = eb.getByte();\n if(first !== 0x00 ||\n (pub && bt !== 0x00 && bt !== 0x01) ||\n (!pub && bt != 0x02) ||\n (pub && bt === 0x00 && typeof(ml) === 'undefined')) {\n throw new Error('Encryption block is invalid.');\n }\n\n var padNum = 0;\n if(bt === 0x00) {\n // check all padding bytes for 0x00\n padNum = k - 3 - ml;\n for(var i = 0; i < padNum; ++i) {\n if(eb.getByte() !== 0x00) {\n throw new Error('Encryption block is invalid.');\n }\n }\n } else if(bt === 0x01) {\n // find the first byte that isn't 0xFF, should be after all padding\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() !== 0xFF) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n } else if(bt === 0x02) {\n // look for 0x00 byte\n padNum = 0;\n while(eb.length() > 1) {\n if(eb.getByte() === 0x00) {\n --eb.read;\n break;\n }\n ++padNum;\n }\n }\n\n // zero must be 0x00 and padNum must be (k - 3 - message length)\n var zero = eb.getByte();\n if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {\n throw new Error('Encryption block is invalid.');\n }\n\n return eb.getBytes();\n}\n\n/**\n * Runs the key-generation algorithm asynchronously, either in the background\n * via Web Workers, or using the main thread and setImmediate.\n *\n * @param state the key-pair generation state.\n * @param [options] options for key-pair generation:\n * workerScript the worker script URL.\n * workers the number of web workers (if supported) to use,\n * (default: 2, -1 to use estimated cores minus one).\n * workLoad the size of the work load, ie: number of possible prime\n * numbers for each web worker to check per work assignment,\n * (default: 100).\n * @param callback(err, keypair) called once the operation completes.\n */\nfunction _generateKeyPair(state, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n var opts = {\n algorithm: {\n name: options.algorithm || 'PRIMEINC',\n options: {\n workers: options.workers || 2,\n workLoad: options.workLoad || 100,\n workerScript: options.workerScript\n }\n }\n };\n if('prng' in options) {\n opts.prng = options.prng;\n }\n\n generate();\n\n function generate() {\n // find p and then q (done in series to simplify)\n getPrime(state.pBits, function(err, num) {\n if(err) {\n return callback(err);\n }\n state.p = num;\n if(state.q !== null) {\n return finish(err, state.q);\n }\n getPrime(state.qBits, finish);\n });\n }\n\n function getPrime(bits, callback) {\n forge.prime.generateProbablePrime(bits, opts, callback);\n }\n\n function finish(err, num) {\n if(err) {\n return callback(err);\n }\n\n // set q\n state.q = num;\n\n // ensure p is larger than q (swap them if not)\n if(state.p.compareTo(state.q) < 0) {\n var tmp = state.p;\n state.p = state.q;\n state.q = tmp;\n }\n\n // ensure p is coprime with e\n if(state.p.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.p = null;\n generate();\n return;\n }\n\n // ensure q is coprime with e\n if(state.q.subtract(BigInteger.ONE).gcd(state.e)\n .compareTo(BigInteger.ONE) !== 0) {\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // compute phi: (p - 1)(q - 1) (Euler's totient function)\n state.p1 = state.p.subtract(BigInteger.ONE);\n state.q1 = state.q.subtract(BigInteger.ONE);\n state.phi = state.p1.multiply(state.q1);\n\n // ensure e and phi are coprime\n if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {\n // phi and e aren't coprime, so generate a new p and q\n state.p = state.q = null;\n generate();\n return;\n }\n\n // create n, ensure n is has the right number of bits\n state.n = state.p.multiply(state.q);\n if(state.n.bitLength() !== state.bits) {\n // failed, get new q\n state.q = null;\n getPrime(state.qBits, finish);\n return;\n }\n\n // set keys\n var d = state.e.modInverse(state.phi);\n state.keys = {\n privateKey: pki.rsa.setPrivateKey(\n state.n, state.e, d, state.p, state.q,\n d.mod(state.p1), d.mod(state.q1),\n state.q.modInverse(state.p)),\n publicKey: pki.rsa.setPublicKey(state.n, state.e)\n };\n\n callback(null, state.keys);\n }\n}\n\n/**\n * Converts a positive BigInteger into 2's-complement big-endian bytes.\n *\n * @param b the big integer to convert.\n *\n * @return the bytes.\n */\nfunction _bnToBytes(b) {\n // prepend 0x00 if first byte >= 0x80\n var hex = b.toString(16);\n if(hex[0] >= '8') {\n hex = '00' + hex;\n }\n var bytes = forge.util.hexToBytes(hex);\n\n // ensure integer is minimally-encoded\n if(bytes.length > 1 &&\n // leading 0x00 for positive integer\n ((bytes.charCodeAt(0) === 0 &&\n (bytes.charCodeAt(1) & 0x80) === 0) ||\n // leading 0xFF for negative integer\n (bytes.charCodeAt(0) === 0xFF &&\n (bytes.charCodeAt(1) & 0x80) === 0x80))) {\n return bytes.substr(1);\n }\n return bytes;\n}\n\n/**\n * Returns the required number of Miller-Rabin tests to generate a\n * prime with an error probability of (1/2)^80.\n *\n * See Handbook of Applied Cryptography Chapter 4, Table 4.4.\n *\n * @param bits the bit size.\n *\n * @return the required number of iterations.\n */\nfunction _getMillerRabinTests(bits) {\n if(bits <= 100) return 27;\n if(bits <= 150) return 18;\n if(bits <= 200) return 15;\n if(bits <= 250) return 12;\n if(bits <= 300) return 9;\n if(bits <= 350) return 8;\n if(bits <= 400) return 7;\n if(bits <= 500) return 6;\n if(bits <= 600) return 5;\n if(bits <= 800) return 4;\n if(bits <= 1250) return 3;\n return 2;\n}\n\n/**\n * Performs feature detection on the Node crypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectNodeCrypto(fn) {\n return forge.util.isNodejs && typeof _crypto[fn] === 'function';\n}\n\n/**\n * Performs feature detection on the SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.crypto === 'object' &&\n typeof util.globalScope.crypto.subtle === 'object' &&\n typeof util.globalScope.crypto.subtle[fn] === 'function');\n}\n\n/**\n * Performs feature detection on the deprecated Microsoft Internet Explorer\n * outdated SubtleCrypto interface. This function should only be used after\n * checking for the modern, standard SubtleCrypto interface.\n *\n * @param fn the feature (function) to detect.\n *\n * @return true if detected, false if not.\n */\nfunction _detectSubtleMsCrypto(fn) {\n return (typeof util.globalScope !== 'undefined' &&\n typeof util.globalScope.msCrypto === 'object' &&\n typeof util.globalScope.msCrypto.subtle === 'object' &&\n typeof util.globalScope.msCrypto.subtle[fn] === 'function');\n}\n\nfunction _intToUint8Array(x) {\n var bytes = forge.util.hexToBytes(x.toString(16));\n var buffer = new Uint8Array(bytes.length);\n for(var i = 0; i < bytes.length; ++i) {\n buffer[i] = bytes.charCodeAt(i);\n }\n return buffer;\n}\n\nfunction _privateKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error(\n 'Unsupported key algorithm \"' + jwk.kty + '\"; algorithm must be \"RSA\".');\n }\n return pki.setRsaPrivateKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e),\n _base64ToBigInt(jwk.d),\n _base64ToBigInt(jwk.p),\n _base64ToBigInt(jwk.q),\n _base64ToBigInt(jwk.dp),\n _base64ToBigInt(jwk.dq),\n _base64ToBigInt(jwk.qi));\n}\n\nfunction _publicKeyFromJwk(jwk) {\n if(jwk.kty !== 'RSA') {\n throw new Error('Key algorithm must be \"RSA\".');\n }\n return pki.setRsaPublicKey(\n _base64ToBigInt(jwk.n),\n _base64ToBigInt(jwk.e));\n}\n\nfunction _base64ToBigInt(b64) {\n return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);\n}\n","/**\n * Password-based encryption functions.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * An EncryptedPrivateKeyInfo:\n *\n * EncryptedPrivateKeyInfo ::= SEQUENCE {\n * encryptionAlgorithm EncryptionAlgorithmIdentifier,\n * encryptedData EncryptedData }\n *\n * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedData ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./oids');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./random');\nrequire('./rc2');\nrequire('./rsa');\nrequire('./util');\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Password-based encryption implementation. */\nvar pki = forge.pki = forge.pki || {};\nmodule.exports = pki.pbe = forge.pbe = forge.pbe || {};\nvar oids = pki.oids;\n\n// validator for an EncryptedPrivateKeyInfo structure\n// Note: Currently only works w/algorithm params\nvar encryptedPrivateKeyValidator = {\n name: 'EncryptedPrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encryptionOid'\n }, {\n name: 'AlgorithmIdentifier.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'encryptionParams'\n }]\n }, {\n // encryptedData\n name: 'EncryptedPrivateKeyInfo.encryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encryptedData'\n }]\n};\n\n// validator for a PBES2Algorithms structure\n// Note: Currently only works w/PBKDF2 + AES encryption schemes\nvar PBES2AlgorithmsValidator = {\n name: 'PBES2Algorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.keyDerivationFunc.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'kdfOid'\n }, {\n name: 'PBES2Algorithms.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.params.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'kdfSalt'\n }, {\n name: 'PBES2Algorithms.params.iterationCount',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'kdfIterationCount'\n }, {\n name: 'PBES2Algorithms.params.keyLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'keyLength'\n }, {\n // prf\n name: 'PBES2Algorithms.params.prf',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'PBES2Algorithms.params.prf.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'prfOid'\n }]\n }]\n }]\n }, {\n name: 'PBES2Algorithms.encryptionScheme',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PBES2Algorithms.encryptionScheme.oid',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encOid'\n }, {\n name: 'PBES2Algorithms.encryptionScheme.iv',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encIv'\n }]\n }]\n};\n\nvar pkcs12PbeParamsValidator = {\n name: 'pkcs-12PbeParams',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'pkcs-12PbeParams.salt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'salt'\n }, {\n name: 'pkcs-12PbeParams.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'iterations'\n }]\n};\n\n/**\n * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.\n *\n * PBES2Algorithms ALGORITHM-IDENTIFIER ::=\n * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}\n *\n * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}\n *\n * PBES2-params ::= SEQUENCE {\n * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},\n * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}\n * }\n *\n * PBES2-KDFs ALGORITHM-IDENTIFIER ::=\n * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }\n *\n * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }\n *\n * PBKDF2-params ::= SEQUENCE {\n * salt CHOICE {\n * specified OCTET STRING,\n * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}\n * },\n * iterationCount INTEGER (1..MAX),\n * keyLength INTEGER (1..MAX) OPTIONAL,\n * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1\n * }\n *\n * @param obj the ASN.1 PrivateKeyInfo object.\n * @param password the password to encrypt with.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * prfAlgorithm the PRF message digest algorithm to use\n * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptPrivateKeyInfo = function(obj, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || 'aes128';\n options.prfAlgorithm = options.prfAlgorithm || 'sha1';\n\n // generate PBE params\n var salt = forge.random.getBytesSync(options.saltSize);\n var count = options.count;\n var countBytes = asn1.integerToDer(count);\n var dkLen;\n var encryptionAlgorithm;\n var encryptedData;\n if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {\n // do PBES2\n var ivLen, encOid, cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n dkLen = 16;\n ivLen = 16;\n encOid = oids['aes128-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n dkLen = 24;\n ivLen = 16;\n encOid = oids['aes192-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n dkLen = 32;\n ivLen = 16;\n encOid = oids['aes256-CBC'];\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'des':\n dkLen = 8;\n ivLen = 8;\n encOid = oids['desCBC'];\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // get PRF message digest\n var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();\n var md = prfAlgorithmToMessageDigest(prfAlgorithm);\n\n // encrypt private key using pbe SHA-1 and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = forge.random.getBytesSync(ivLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n // get PBKDF2-params\n var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // keyDerivationFunc\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),\n // PBKDF2-params\n params\n ]),\n // encryptionScheme\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(encOid).getBytes()),\n // iv\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)\n ])\n ])\n ]);\n } else if(options.algorithm === '3des') {\n // Do PKCS12 PBE\n dkLen = 24;\n\n var saltBytes = new forge.util.ByteBuffer(salt);\n var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);\n var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);\n var cipher = forge.des.createEncryptionCipher(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(obj));\n cipher.finish();\n encryptedData = cipher.output.getBytes();\n\n encryptionAlgorithm = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),\n // pkcs-12PbeParams\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ])\n ]);\n } else {\n var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // EncryptedPrivateKeyInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // encryptionAlgorithm\n encryptionAlgorithm,\n // encryptedData\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)\n ]);\n return rval;\n};\n\n/**\n * Decrypts a ASN.1 PrivateKeyInfo object.\n *\n * @param obj the ASN.1 EncryptedPrivateKeyInfo object.\n * @param password the password to decrypt with.\n *\n * @return the ASN.1 PrivateKeyInfo on success, null on failure.\n */\npki.decryptPrivateKeyInfo = function(obj, password) {\n var rval = null;\n\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // get cipher\n var oid = asn1.derToOid(capture.encryptionOid);\n var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);\n\n // get encrypted data\n var encrypted = forge.util.createBuffer(capture.encryptedData);\n\n cipher.update(encrypted);\n if(cipher.finish()) {\n rval = asn1.fromDer(cipher.output);\n }\n\n return rval;\n};\n\n/**\n * Converts a EncryptedPrivateKeyInfo to PEM format.\n *\n * @param epki the EncryptedPrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted encrypted private key.\n */\npki.encryptedPrivateKeyToPem = function(epki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'ENCRYPTED PRIVATE KEY',\n body: asn1.toDer(epki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption\n * is not performed.\n *\n * @param pem the EncryptedPrivateKeyInfo in PEM-format.\n *\n * @return the ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptedPrivateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY') {\n var error = new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM header type is \"ENCRYPTED PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert encrypted private key from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n return asn1.fromDer(msg.body);\n};\n\n/**\n * Encrypts an RSA private key. By default, the key will be wrapped in\n * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.\n * This is the standard, preferred way to encrypt a private key.\n *\n * To produce a non-standard PEM-encrypted private key that uses encapsulated\n * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL\n * private key encryption), set the 'legacy' option to true. Note: Using this\n * option will cause the iteration count to be forced to 1.\n *\n * Note: The 'des' algorithm is supported, but it is not considered to be\n * secure because it only uses a single 56-bit key. If possible, it is highly\n * recommended that a different algorithm be used.\n *\n * @param rsaKey the RSA key to encrypt.\n * @param password the password to use.\n * @param options:\n * algorithm: the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des', 'des').\n * count: the iteration count to use.\n * saltSize: the salt size to use.\n * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated\n * headers (DEK-Info) private key.\n *\n * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.\n */\npki.encryptRsaPrivateKey = function(rsaKey, password, options) {\n // standard PKCS#8\n options = options || {};\n if(!options.legacy) {\n // encrypt PrivateKeyInfo\n var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));\n rval = pki.encryptPrivateKeyInfo(rval, password, options);\n return pki.encryptedPrivateKeyToPem(rval);\n }\n\n // legacy non-PKCS#8\n var algorithm;\n var iv;\n var dkLen;\n var cipherFn;\n switch(options.algorithm) {\n case 'aes128':\n algorithm = 'AES-128-CBC';\n dkLen = 16;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes192':\n algorithm = 'AES-192-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case 'aes256':\n algorithm = 'AES-256-CBC';\n dkLen = 32;\n iv = forge.random.getBytesSync(16);\n cipherFn = forge.aes.createEncryptionCipher;\n break;\n case '3des':\n algorithm = 'DES-EDE3-CBC';\n dkLen = 24;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n case 'des':\n algorithm = 'DES-CBC';\n dkLen = 8;\n iv = forge.random.getBytesSync(8);\n cipherFn = forge.des.createEncryptionCipher;\n break;\n default:\n var error = new Error('Could not encrypt RSA private key; unsupported ' +\n 'encryption algorithm \"' + options.algorithm + '\".');\n error.algorithm = options.algorithm;\n throw error;\n }\n\n // encrypt private key using OpenSSL legacy key derivation\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));\n cipher.finish();\n\n var msg = {\n type: 'RSA PRIVATE KEY',\n procType: {\n version: '4',\n type: 'ENCRYPTED'\n },\n dekInfo: {\n algorithm: algorithm,\n parameters: forge.util.bytesToHex(iv).toUpperCase()\n },\n body: cipher.output.getBytes()\n };\n return forge.pem.encode(msg);\n};\n\n/**\n * Decrypts an RSA private key.\n *\n * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.\n * @param password the password to use.\n *\n * @return the RSA key on success, null on failure.\n */\npki.decryptRsaPrivateKey = function(pem, password) {\n var rval = null;\n\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&\n msg.type !== 'PRIVATE KEY' &&\n msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM header type ' +\n 'is not \"ENCRYPTED PRIVATE KEY\", \"PRIVATE KEY\", or \"RSA PRIVATE KEY\".');\n error.headerType = error;\n throw error;\n }\n\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n var dkLen;\n var cipherFn;\n switch(msg.dekInfo.algorithm) {\n case 'DES-CBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'DES-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'AES-128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'AES-256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'RC2-40-CBC':\n dkLen = 5;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 40);\n };\n break;\n case 'RC2-64-CBC':\n dkLen = 8;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 64);\n };\n break;\n case 'RC2-128-CBC':\n dkLen = 16;\n cipherFn = function(key) {\n return forge.rc2.createDecryptionCipher(key, 128);\n };\n break;\n default:\n var error = new Error('Could not decrypt private key; unsupported ' +\n 'encryption algorithm \"' + msg.dekInfo.algorithm + '\".');\n error.algorithm = msg.dekInfo.algorithm;\n throw error;\n }\n\n // use OpenSSL legacy key derivation\n var iv = forge.util.hexToBytes(msg.dekInfo.parameters);\n var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);\n var cipher = cipherFn(dk);\n cipher.start(iv);\n cipher.update(forge.util.createBuffer(msg.body));\n if(cipher.finish()) {\n rval = cipher.output.getBytes();\n } else {\n return rval;\n }\n } else {\n rval = msg.body;\n }\n\n if(msg.type === 'ENCRYPTED PRIVATE KEY') {\n rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);\n } else {\n // decryption already performed above\n rval = asn1.fromDer(rval);\n }\n\n if(rval !== null) {\n rval = pki.privateKeyFromAsn1(rval);\n }\n\n return rval;\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\npki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {\n var j, l;\n\n if(typeof md === 'undefined' || md === null) {\n if(!('sha1' in forge.md)) {\n throw new Error('\"sha1\" hash algorithm unavailable.');\n }\n md = forge.md.sha1.create();\n }\n\n var u = md.digestLength;\n var v = md.blockLength;\n var result = new forge.util.ByteBuffer();\n\n /* Convert password to Unicode byte buffer + trailing 0-byte. */\n var passBuf = new forge.util.ByteBuffer();\n if(password !== null && password !== undefined) {\n for(l = 0; l < password.length; l++) {\n passBuf.putInt16(password.charCodeAt(l));\n }\n passBuf.putInt16(0);\n }\n\n /* Length of salt and password in BYTES. */\n var p = passBuf.length();\n var s = salt.length();\n\n /* 1. Construct a string, D (the \"diversifier\"), by concatenating\n v copies of ID. */\n var D = new forge.util.ByteBuffer();\n D.fillWithByte(id, v);\n\n /* 2. Concatenate copies of the salt together to create a string S of length\n v * ceil(s / v) bytes (the final copy of the salt may be trunacted\n to create S).\n Note that if the salt is the empty string, then so is S. */\n var Slen = v * Math.ceil(s / v);\n var S = new forge.util.ByteBuffer();\n for(l = 0; l < Slen; l++) {\n S.putByte(salt.at(l % s));\n }\n\n /* 3. Concatenate copies of the password together to create a string P of\n length v * ceil(p / v) bytes (the final copy of the password may be\n truncated to create P).\n Note that if the password is the empty string, then so is P. */\n var Plen = v * Math.ceil(p / v);\n var P = new forge.util.ByteBuffer();\n for(l = 0; l < Plen; l++) {\n P.putByte(passBuf.at(l % p));\n }\n\n /* 4. Set I=S||P to be the concatenation of S and P. */\n var I = S;\n I.putBuffer(P);\n\n /* 5. Set c=ceil(n / u). */\n var c = Math.ceil(n / u);\n\n /* 6. For i=1, 2, ..., c, do the following: */\n for(var i = 1; i <= c; i++) {\n /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */\n var buf = new forge.util.ByteBuffer();\n buf.putBytes(D.bytes());\n buf.putBytes(I.bytes());\n for(var round = 0; round < iter; round++) {\n md.start();\n md.update(buf.getBytes());\n buf = md.digest();\n }\n\n /* b) Concatenate copies of Ai to create a string B of length v bytes (the\n final copy of Ai may be truncated to create B). */\n var B = new forge.util.ByteBuffer();\n for(l = 0; l < v; l++) {\n B.putByte(buf.at(l % u));\n }\n\n /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,\n where k=ceil(s / v) + ceil(p / v), modify I by setting\n Ij=(Ij+B+1) mod 2v for each j. */\n var k = Math.ceil(s / v) + Math.ceil(p / v);\n var Inew = new forge.util.ByteBuffer();\n for(j = 0; j < k; j++) {\n var chunk = new forge.util.ByteBuffer(I.getBytes(v));\n var x = 0x1ff;\n for(l = B.length() - 1; l >= 0; l--) {\n x = x >> 8;\n x += B.at(l) + chunk.at(l);\n chunk.setAt(l, x & 0xff);\n }\n Inew.putBuffer(chunk);\n }\n I = Inew;\n\n /* Add Ai to A. */\n result.putBuffer(buf);\n }\n\n result.truncate(result.length() - n);\n return result;\n};\n\n/**\n * Get new Forge cipher object instance.\n *\n * @param oid the OID (in string notation).\n * @param params the ASN.1 params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipher = function(oid, params, password) {\n switch(oid) {\n case pki.oids['pkcs5PBES2']:\n return pki.pbe.getCipherForPBES2(oid, params, password);\n\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n return pki.pbe.getCipherForPKCS12PBE(oid, params, password);\n\n default:\n var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');\n error.oid = oid;\n error.supportedOids = [\n 'pkcs5PBES2',\n 'pbeWithSHAAnd3-KeyTripleDES-CBC',\n 'pbewithSHAAnd40BitRC2-CBC'\n ];\n throw error;\n }\n};\n\n/**\n * Get new Forge cipher object instance according to PBES2 params block.\n *\n * The returned cipher instance is already started using the IV\n * from PBES2 parameter block.\n *\n * @param oid the PKCS#5 PBKDF2 OID (in string notation).\n * @param params the ASN.1 PBES2-params object.\n * @param password the password to decrypt with.\n *\n * @return new cipher object instance.\n */\npki.pbe.getCipherForPBES2 = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n // check oids\n oid = asn1.derToOid(capture.kdfOid);\n if(oid !== pki.oids['pkcs5PBKDF2']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported key derivation function OID.');\n error.oid = oid;\n error.supportedOids = ['pkcs5PBKDF2'];\n throw error;\n }\n oid = asn1.derToOid(capture.encOid);\n if(oid !== pki.oids['aes128-CBC'] &&\n oid !== pki.oids['aes192-CBC'] &&\n oid !== pki.oids['aes256-CBC'] &&\n oid !== pki.oids['des-EDE3-CBC'] &&\n oid !== pki.oids['desCBC']) {\n var error = new Error('Cannot read encrypted private key. ' +\n 'Unsupported encryption scheme OID.');\n error.oid = oid;\n error.supportedOids = [\n 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];\n throw error;\n }\n\n // set PBE params\n var salt = capture.kdfSalt;\n var count = forge.util.createBuffer(capture.kdfIterationCount);\n count = count.getInt(count.length() << 3);\n var dkLen;\n var cipherFn;\n switch(pki.oids[oid]) {\n case 'aes128-CBC':\n dkLen = 16;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes192-CBC':\n dkLen = 24;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'aes256-CBC':\n dkLen = 32;\n cipherFn = forge.aes.createDecryptionCipher;\n break;\n case 'des-EDE3-CBC':\n dkLen = 24;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n case 'desCBC':\n dkLen = 8;\n cipherFn = forge.des.createDecryptionCipher;\n break;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n\n // decrypt private key using pbe with chosen PRF and AES/DES\n var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);\n var iv = capture.encIv;\n var cipher = cipherFn(dk);\n cipher.start(iv);\n\n return cipher;\n};\n\n/**\n * Get new Forge cipher object instance for PKCS#12 PBE.\n *\n * The returned cipher instance is already started using the key & IV\n * derived from the provided password and PKCS#12 PBE salt.\n *\n * @param oid The PKCS#12 PBE OID (in string notation).\n * @param params The ASN.1 PKCS#12 PBE-params object.\n * @param password The password to decrypt with.\n *\n * @return the new cipher object instance.\n */\npki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {\n // get PBE params\n var capture = {};\n var errors = [];\n if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {\n var error = new Error('Cannot read password-based-encryption algorithm ' +\n 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');\n error.errors = errors;\n throw error;\n }\n\n var salt = forge.util.createBuffer(capture.salt);\n var count = forge.util.createBuffer(capture.iterations);\n count = count.getInt(count.length() << 3);\n\n var dkLen, dIvLen, cipherFn;\n switch(oid) {\n case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:\n dkLen = 24;\n dIvLen = 8;\n cipherFn = forge.des.startDecrypting;\n break;\n\n case pki.oids['pbewithSHAAnd40BitRC2-CBC']:\n dkLen = 5;\n dIvLen = 8;\n cipherFn = function(key, iv) {\n var cipher = forge.rc2.createDecryptionCipher(key, 40);\n cipher.start(iv, null);\n return cipher;\n };\n break;\n\n default:\n var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');\n error.oid = oid;\n throw error;\n }\n\n // get PRF message digest\n var md = prfOidToMessageDigest(capture.prfOid);\n var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);\n md.start();\n var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);\n\n return cipherFn(key, iv);\n};\n\n/**\n * OpenSSL's legacy key derivation function.\n *\n * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html\n *\n * @param password the password to derive the key from.\n * @param salt the salt to use, null for none.\n * @param dkLen the number of bytes needed for the derived key.\n * @param [options] the options to use:\n * [md] an optional message digest object to use.\n */\npki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {\n if(typeof md === 'undefined' || md === null) {\n if(!('md5' in forge.md)) {\n throw new Error('\"md5\" hash algorithm unavailable.');\n }\n md = forge.md.md5.create();\n }\n if(salt === null) {\n salt = '';\n }\n var digests = [hash(md, password + salt)];\n for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {\n digests.push(hash(md, digests[i - 1] + password + salt));\n }\n return digests.join('').substr(0, dkLen);\n};\n\nfunction hash(md, bytes) {\n return md.start().update(bytes).digest().getBytes();\n}\n\nfunction prfOidToMessageDigest(prfOid) {\n // get PRF algorithm, default to SHA-1\n var prfAlgorithm;\n if(!prfOid) {\n prfAlgorithm = 'hmacWithSHA1';\n } else {\n prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];\n if(!prfAlgorithm) {\n var error = new Error('Unsupported PRF OID.');\n error.oid = prfOid;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n }\n return prfAlgorithmToMessageDigest(prfAlgorithm);\n}\n\nfunction prfAlgorithmToMessageDigest(prfAlgorithm) {\n var factory = forge.md;\n switch(prfAlgorithm) {\n case 'hmacWithSHA224':\n factory = forge.md.sha512;\n case 'hmacWithSHA1':\n case 'hmacWithSHA256':\n case 'hmacWithSHA384':\n case 'hmacWithSHA512':\n prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();\n break;\n default:\n var error = new Error('Unsupported PRF algorithm.');\n error.algorithm = prfAlgorithm;\n error.supported = [\n 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',\n 'hmacWithSHA512'];\n throw error;\n }\n if(!factory || !(prfAlgorithm in factory)) {\n throw new Error('Unknown hash algorithm: ' + prfAlgorithm);\n }\n return factory[prfAlgorithm].create();\n}\n\nfunction createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {\n var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // salt\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),\n // iteration count\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n countBytes.getBytes())\n ]);\n // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm\n if(prfAlgorithm !== 'hmacWithSHA1') {\n params.value.push(\n // key length\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(dkLen.toString(16))),\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n return params;\n}\n","/**\n * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.\n *\n * @author Dave Longley\n * @author Stefan Siegl\n *\n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#7 is as follows\n * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):\n *\n * A PKCS#7 message consists of a ContentInfo on root level, which may\n * contain any number of further ContentInfo nested into it.\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * EnvelopedData ::= SEQUENCE {\n * version Version,\n * recipientInfos RecipientInfos,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * EncryptedData ::= SEQUENCE {\n * version Version,\n * encryptedContentInfo EncryptedContentInfo\n * }\n *\n * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)\n * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }\n *\n * SignedData ::= SEQUENCE {\n * version INTEGER,\n * digestAlgorithms DigestAlgorithmIdentifiers,\n * contentInfo ContentInfo,\n * certificates [0] IMPLICIT Certificates OPTIONAL,\n * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,\n * signerInfos SignerInfos\n * }\n *\n * SignerInfos ::= SET OF SignerInfo\n *\n * SignerInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * digestAlgorithm DigestAlgorithmIdentifier,\n * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,\n * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,\n * encryptedDigest EncryptedDigest,\n * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL\n * }\n *\n * EncryptedDigest ::= OCTET STRING\n *\n * Attributes ::= SET OF Attribute\n *\n * Attribute ::= SEQUENCE {\n * attrType OBJECT IDENTIFIER,\n * attrValues SET OF AttributeValue\n * }\n *\n * AttributeValue ::= ANY\n *\n * Version ::= INTEGER\n *\n * RecipientInfos ::= SET OF RecipientInfo\n *\n * EncryptedContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,\n * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL\n * }\n *\n * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of AES and DES3, there is only one,\n * the IV.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * EncryptedContent ::= OCTET STRING\n *\n * RecipientInfo ::= SEQUENCE {\n * version Version,\n * issuerAndSerialNumber IssuerAndSerialNumber,\n * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,\n * encryptedKey EncryptedKey\n * }\n *\n * IssuerAndSerialNumber ::= SEQUENCE {\n * issuer Name,\n * serialNumber CertificateSerialNumber\n * }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * EncryptedKey ::= OCTET STRING\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./util');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};\nforge.pkcs7 = forge.pkcs7 || {};\nforge.pkcs7.asn1 = p7v;\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'ContentInfo.ContentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n captureAsn1: 'content'\n }]\n};\np7v.contentInfoValidator = contentInfoValidator;\n\nvar encryptedContentInfoValidator = {\n name: 'EncryptedContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'encParameter'\n }]\n }, {\n name: 'EncryptedContentInfo.encryptedContent',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n /* The PKCS#7 structure output by OpenSSL somewhat differs from what\n * other implementations do generate.\n *\n * OpenSSL generates a structure like this:\n * SEQUENCE {\n * ...\n * [0]\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n *\n * Whereas other implementations (and this PKCS#7 module) generate:\n * SEQUENCE {\n * ...\n * [0] {\n * OCTET STRING\n * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38\n * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45\n * ...\n * }\n * }\n *\n * In order to support both, we just capture the context specific\n * field here. The OCTET STRING bit is removed below.\n */\n capture: 'encryptedContent',\n captureAsn1: 'encryptedContentAsn1'\n }]\n};\n\np7v.envelopedDataValidator = {\n name: 'EnvelopedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EnvelopedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'EnvelopedData.RecipientInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'recipientInfos'\n }].concat(encryptedContentInfoValidator)\n};\n\np7v.encryptedDataValidator = {\n name: 'EncryptedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'EncryptedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }].concat(encryptedContentInfoValidator)\n};\n\nvar signerValidator = {\n name: 'SignerInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false\n }, {\n name: 'SignerInfo.issuerAndSerialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.issuerAndSerialNumber.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'SignerInfo.issuerAndSerialNumber.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'SignerInfo.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignerInfo.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'digestAlgorithm'\n }, {\n name: 'SignerInfo.digestAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'digestParameter',\n optional: true\n }]\n }, {\n name: 'SignerInfo.authenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'authenticatedAttributes'\n }, {\n name: 'SignerInfo.digestEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n capture: 'signatureAlgorithm'\n }, {\n name: 'SignerInfo.encryptedDigest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'signature'\n }, {\n name: 'SignerInfo.unauthenticatedAttributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n capture: 'unauthenticatedAttributes'\n }]\n};\n\np7v.signedDataValidator = {\n name: 'SignedData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SignedData.Version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'SignedData.DigestAlgorithms',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n captureAsn1: 'digestAlgorithms'\n },\n contentInfoValidator,\n {\n name: 'SignedData.Certificates',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n optional: true,\n captureAsn1: 'certificates'\n }, {\n name: 'SignedData.CertificateRevocationLists',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n optional: true,\n captureAsn1: 'crls'\n }, {\n name: 'SignedData.SignerInfos',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n capture: 'signerInfos',\n optional: true,\n value: [signerValidator]\n }]\n};\n\np7v.recipientInfoValidator = {\n name: 'RecipientInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n }, {\n name: 'RecipientInfo.issuerAndSerial',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.issuerAndSerial.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'issuer'\n }, {\n name: 'RecipientInfo.issuerAndSerial.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'serial'\n }]\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'encAlgorithm'\n }, {\n name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',\n tagClass: asn1.Class.UNIVERSAL,\n constructed: false,\n captureAsn1: 'encParameter'\n }]\n }, {\n name: 'RecipientInfo.encryptedKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'encKey'\n }]\n};\n","/**\n * Javascript implementation of mask generation function MGF1.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\nforge.mgf = forge.mgf || {};\nvar mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};\n\n/**\n * Creates a MGF1 mask generation function object.\n *\n * @param md the message digest API to use (eg: forge.md.sha1.create()).\n *\n * @return a mask generation function object.\n */\nmgf1.create = function(md) {\n var mgf = {\n /**\n * Generate mask of specified length.\n *\n * @param {String} seed The seed for mask generation.\n * @param maskLen Number of bytes to generate.\n * @return {String} The generated mask.\n */\n generate: function(seed, maskLen) {\n /* 2. Let T be the empty octet string. */\n var t = new forge.util.ByteBuffer();\n\n /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */\n var len = Math.ceil(maskLen / md.digestLength);\n for(var i = 0; i < len; i++) {\n /* a. Convert counter to an octet string C of length 4 octets */\n var c = new forge.util.ByteBuffer();\n c.putInt32(i);\n\n /* b. Concatenate the hash of the seed mgfSeed and C to the octet\n * string T: */\n md.start();\n md.update(seed + c.getBytes());\n t.putBuffer(md.digest());\n }\n\n /* Output the leading maskLen octets of T as the octet string mask. */\n t.truncate(t.length() - maskLen);\n return t.getBytes();\n }\n };\n\n return mgf;\n};\n","/**\n * Node.js module for Forge mask generation functions.\n *\n * @author Stefan Siegl\n *\n * Copyright 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./mgf1');\n\nmodule.exports = forge.mgf = forge.mgf || {};\nforge.mgf.mgf1 = forge.mgf1;\n","/**\n * Javascript implementation of PKCS#1 PSS signature padding.\n *\n * @author Stefan Siegl\n *\n * Copyright (c) 2012 Stefan Siegl \n */\nvar forge = require('./forge');\nrequire('./random');\nrequire('./util');\n\n// shortcut for PSS API\nvar pss = module.exports = forge.pss = forge.pss || {};\n\n/**\n * Creates a PSS signature scheme object.\n *\n * There are several ways to provide a salt for encoding:\n *\n * 1. Specify the saltLength only and the built-in PRNG will generate it.\n * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that\n * will be used.\n * 3. Specify the salt itself as a forge.util.ByteBuffer.\n *\n * @param options the options to use:\n * md the message digest object to use, a forge md instance.\n * mgf the mask generation function to use, a forge mgf instance.\n * [saltLength] the length of the salt in octets.\n * [prng] the pseudo-random number generator to use to produce a salt.\n * [salt] the salt to use when encoding.\n *\n * @return a signature scheme object.\n */\npss.create = function(options) {\n // backwards compatibility w/legacy args: hash, mgf, sLen\n if(arguments.length === 3) {\n options = {\n md: arguments[0],\n mgf: arguments[1],\n saltLength: arguments[2]\n };\n }\n\n var hash = options.md;\n var mgf = options.mgf;\n var hLen = hash.digestLength;\n\n var salt_ = options.salt || null;\n if(typeof salt_ === 'string') {\n // assume binary-encoded string\n salt_ = forge.util.createBuffer(salt_);\n }\n\n var sLen;\n if('saltLength' in options) {\n sLen = options.saltLength;\n } else if(salt_ !== null) {\n sLen = salt_.length();\n } else {\n throw new Error('Salt length not specified or specific salt not given.');\n }\n\n if(salt_ !== null && salt_.length() !== sLen) {\n throw new Error('Given salt length does not match length of given salt.');\n }\n\n var prng = options.prng || forge.random;\n\n var pssobj = {};\n\n /**\n * Encodes a PSS signature.\n *\n * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.\n *\n * @param md the message digest object with the hash to sign.\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return the encoded message as a binary-encoded string of length\n * ceil((modBits - 1) / 8).\n */\n pssobj.encode = function(md, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* 2. Let mHash = Hash(M), an octet string of length hLen. */\n var mHash = md.digest().getBytes();\n\n /* 3. If emLen < hLen + sLen + 2, output \"encoding error\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Message is too long to encrypt.');\n }\n\n /* 4. Generate a random octet string salt of length sLen; if sLen = 0,\n * then salt is the empty string. */\n var salt;\n if(salt_ === null) {\n salt = prng.getBytesSync(sLen);\n } else {\n salt = salt_.bytes();\n }\n\n /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 6. Let H = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h = hash.digest().getBytes();\n\n /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2\n * zero octets. The length of PS may be 0. */\n var ps = new forge.util.ByteBuffer();\n ps.fillWithByte(0, emLen - sLen - hLen - 2);\n\n /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length\n * emLen - hLen - 1. */\n ps.putByte(0x01);\n ps.putBytes(salt);\n var db = ps.getBytes();\n\n /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */\n var maskLen = emLen - hLen - 1;\n var dbMask = mgf.generate(h, maskLen);\n\n /* 10. Let maskedDB = DB \\xor dbMask. */\n var maskedDB = '';\n for(i = 0; i < maskLen; i++) {\n maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB to zero. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +\n maskedDB.substr(1);\n\n /* 12. Let EM = maskedDB || H || 0xbc.\n * 13. Output EM. */\n return maskedDB + h + String.fromCharCode(0xbc);\n };\n\n /**\n * Verifies a PSS signature.\n *\n * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.\n *\n * @param mHash the message digest hash, as a binary-encoded string, to\n * compare against the signature.\n * @param em the encoded message, as a binary-encoded string\n * (RSA decryption result).\n * @param modsBits the length of the RSA modulus in bits.\n *\n * @return true if the signature was verified, false if not.\n */\n pssobj.verify = function(mHash, em, modBits) {\n var i;\n var emBits = modBits - 1;\n var emLen = Math.ceil(emBits / 8);\n\n /* c. Convert the message representative m to an encoded message EM\n * of length emLen = ceil((modBits - 1) / 8) octets, where modBits\n * is the length in bits of the RSA modulus n */\n em = em.substr(-emLen);\n\n /* 3. If emLen < hLen + sLen + 2, output \"inconsistent\" and stop. */\n if(emLen < hLen + sLen + 2) {\n throw new Error('Inconsistent parameters to PSS signature verification.');\n }\n\n /* 4. If the rightmost octet of EM does not have hexadecimal value\n * 0xbc, output \"inconsistent\" and stop. */\n if(em.charCodeAt(emLen - 1) !== 0xbc) {\n throw new Error('Encoded message does not end in 0xBC.');\n }\n\n /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and\n * let H be the next hLen octets. */\n var maskLen = emLen - hLen - 1;\n var maskedDB = em.substr(0, maskLen);\n var h = em.substr(maskLen, hLen);\n\n /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in\n * maskedDB are not all equal to zero, output \"inconsistent\" and stop. */\n var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;\n if((maskedDB.charCodeAt(0) & mask) !== 0) {\n throw new Error('Bits beyond keysize not zero as expected.');\n }\n\n /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */\n var dbMask = mgf.generate(h, maskLen);\n\n /* 8. Let DB = maskedDB \\xor dbMask. */\n var db = '';\n for(i = 0; i < maskLen; i++) {\n db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));\n }\n\n /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet\n * in DB to zero. */\n db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);\n\n /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero\n * or if the octet at position emLen - hLen - sLen - 1 (the leftmost\n * position is \"position 1\") does not have hexadecimal value 0x01,\n * output \"inconsistent\" and stop. */\n var checkLen = emLen - hLen - sLen - 2;\n for(i = 0; i < checkLen; i++) {\n if(db.charCodeAt(i) !== 0x00) {\n throw new Error('Leftmost octets not zero as expected');\n }\n }\n\n if(db.charCodeAt(checkLen) !== 0x01) {\n throw new Error('Inconsistent PSS signature, 0x01 marker not found');\n }\n\n /* 11. Let salt be the last sLen octets of DB. */\n var salt = db.substr(-sLen);\n\n /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */\n var m_ = new forge.util.ByteBuffer();\n m_.fillWithByte(0, 8);\n m_.putBytes(mHash);\n m_.putBytes(salt);\n\n /* 13. Let H' = Hash(M'), an octet string of length hLen. */\n hash.start();\n hash.update(m_.getBytes());\n var h_ = hash.digest().getBytes();\n\n /* 14. If H = H', output \"consistent.\" Otherwise, output \"inconsistent.\" */\n return h === h_;\n };\n\n return pssobj;\n};\n","/**\n * Javascript implementation of X.509 and related components (such as\n * Certification Signing Requests) of a Public Key Infrastructure.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n *\n * The ASN.1 representation of an X.509v3 certificate is as follows\n * (see RFC 2459):\n *\n * Certificate ::= SEQUENCE {\n * tbsCertificate TBSCertificate,\n * signatureAlgorithm AlgorithmIdentifier,\n * signatureValue BIT STRING\n * }\n *\n * TBSCertificate ::= SEQUENCE {\n * version [0] EXPLICIT Version DEFAULT v1,\n * serialNumber CertificateSerialNumber,\n * signature AlgorithmIdentifier,\n * issuer Name,\n * validity Validity,\n * subject Name,\n * subjectPublicKeyInfo SubjectPublicKeyInfo,\n * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,\n * -- If present, version shall be v2 or v3\n * extensions [3] EXPLICIT Extensions OPTIONAL\n * -- If present, version shall be v3\n * }\n *\n * Version ::= INTEGER { v1(0), v2(1), v3(2) }\n *\n * CertificateSerialNumber ::= INTEGER\n *\n * Name ::= CHOICE {\n * // only one possible choice for now\n * RDNSequence\n * }\n *\n * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName\n *\n * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue\n *\n * AttributeTypeAndValue ::= SEQUENCE {\n * type AttributeType,\n * value AttributeValue\n * }\n * AttributeType ::= OBJECT IDENTIFIER\n * AttributeValue ::= ANY DEFINED BY AttributeType\n *\n * Validity ::= SEQUENCE {\n * notBefore Time,\n * notAfter Time\n * }\n *\n * Time ::= CHOICE {\n * utcTime UTCTime,\n * generalTime GeneralizedTime\n * }\n *\n * UniqueIdentifier ::= BIT STRING\n *\n * SubjectPublicKeyInfo ::= SEQUENCE {\n * algorithm AlgorithmIdentifier,\n * subjectPublicKey BIT STRING\n * }\n *\n * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension\n *\n * Extension ::= SEQUENCE {\n * extnID OBJECT IDENTIFIER,\n * critical BOOLEAN DEFAULT FALSE,\n * extnValue OCTET STRING\n * }\n *\n * The only key algorithm currently supported for PKI is RSA.\n *\n * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.\n *\n * PKCS#10 v1.7 describes certificate signing requests:\n *\n * CertificationRequestInfo:\n *\n * CertificationRequestInfo ::= SEQUENCE {\n * version INTEGER { v1(0) } (v1,...),\n * subject Name,\n * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},\n * attributes [0] Attributes{{ CRIAttributes }}\n * }\n *\n * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}\n *\n * CRIAttributes ATTRIBUTE ::= {\n * ... -- add any locally defined attributes here -- }\n *\n * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {\n * type ATTRIBUTE.&id({IOSet}),\n * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})\n * }\n *\n * CertificationRequest ::= SEQUENCE {\n * certificationRequestInfo CertificationRequestInfo,\n * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},\n * signature BIT STRING\n * }\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./md');\nrequire('./mgf');\nrequire('./oids');\nrequire('./pem');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\nvar oids = pki.oids;\n\n// short name OID mappings\nvar _shortNames = {};\n_shortNames['CN'] = oids['commonName'];\n_shortNames['commonName'] = 'CN';\n_shortNames['C'] = oids['countryName'];\n_shortNames['countryName'] = 'C';\n_shortNames['L'] = oids['localityName'];\n_shortNames['localityName'] = 'L';\n_shortNames['ST'] = oids['stateOrProvinceName'];\n_shortNames['stateOrProvinceName'] = 'ST';\n_shortNames['O'] = oids['organizationName'];\n_shortNames['organizationName'] = 'O';\n_shortNames['OU'] = oids['organizationalUnitName'];\n_shortNames['organizationalUnitName'] = 'OU';\n_shortNames['E'] = oids['emailAddress'];\n_shortNames['emailAddress'] = 'E';\n\n// validator for an SubjectPublicKeyInfo structure\n// Note: Currently only works with an RSA public key\nvar publicKeyValidator = forge.pki.rsa.publicKeyValidator;\n\n// validator for an X.509v3 certificate\nvar x509CertificateValidator = {\n name: 'Certificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'tbsCertificate',\n value: [{\n name: 'Certificate.TBSCertificate.version',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.version.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certVersion'\n }]\n }, {\n name: 'Certificate.TBSCertificate.serialNumber',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certSerialNumber'\n }, {\n name: 'Certificate.TBSCertificate.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Certificate.TBSCertificate.signature.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certinfoSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certinfoSignatureParams'\n }]\n }, {\n name: 'Certificate.TBSCertificate.issuer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certIssuer'\n }, {\n name: 'Certificate.TBSCertificate.validity',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n // Note: UTC and generalized times may both appear so the capture\n // names are based on their detected order, the names used below\n // are only for the common case, which validity time really means\n // \"notBefore\" and which means \"notAfter\" will be determined by order\n value: [{\n // notBefore (Time) (UTC time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity1UTCTime'\n }, {\n // notBefore (Time) (generalized time case)\n name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity2GeneralizedTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (utc)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.UTCTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity3UTCTime'\n }, {\n // notAfter (Time) (only UTC time is supported)\n name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.GENERALIZEDTIME,\n constructed: false,\n optional: true,\n capture: 'certValidity4GeneralizedTime'\n }]\n }, {\n // Name (subject) (RDNSequence)\n name: 'Certificate.TBSCertificate.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n // issuerUniqueID (optional)\n name: 'Certificate.TBSCertificate.issuerUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.issuerUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certIssuerUniqueId'\n }]\n }, {\n // subjectUniqueID (optional)\n name: 'Certificate.TBSCertificate.subjectUniqueID',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n constructed: true,\n optional: true,\n value: [{\n name: 'Certificate.TBSCertificate.subjectUniqueID.id',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n // TODO: support arbitrary bit length ids\n captureBitStringValue: 'certSubjectUniqueId'\n }]\n }, {\n // Extensions (optional)\n name: 'Certificate.TBSCertificate.extensions',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n constructed: true,\n captureAsn1: 'certExtensions',\n optional: true\n }]\n }, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'Certificate.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'Certificate.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certSignatureOid'\n }, {\n name: 'Certificate.TBSCertificate.signature.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'certSignatureParams'\n }]\n }, {\n // SignatureValue\n name: 'Certificate.signatureValue',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'certSignature'\n }]\n};\n\nvar rsassaPssParameterValidator = {\n name: 'rsapss',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'hashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }, {\n name: 'rsapss.maskGenAlgorithm',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 1,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.SEQUENCE,\n constructed: true,\n optional: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenOid'\n }, {\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'maskGenHashOid'\n /* parameter block omitted, for SHA1 NULL anyhow. */\n }]\n }]\n }]\n }, {\n name: 'rsapss.saltLength',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 2,\n optional: true,\n value: [{\n name: 'rsapss.saltLength.saltLength',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'saltLength'\n }]\n }, {\n name: 'rsapss.trailerField',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 3,\n optional: true,\n value: [{\n name: 'rsapss.trailer.trailer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.INTEGER,\n constructed: false,\n capture: 'trailer'\n }]\n }]\n};\n\n// validator for a CertificationRequestInfo structure\nvar certificationRequestInfoValidator = {\n name: 'CertificationRequestInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfo',\n value: [{\n name: 'CertificationRequestInfo.integer',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'certificationRequestInfoVersion'\n }, {\n // Name (subject) (RDNSequence)\n name: 'CertificationRequestInfo.subject',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'certificationRequestInfoSubject'\n },\n // SubjectPublicKeyInfo\n publicKeyValidator,\n {\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n type: 0,\n constructed: true,\n optional: true,\n capture: 'certificationRequestInfoAttributes',\n value: [{\n name: 'CertificationRequestInfo.attributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertificationRequestInfo.attributes.type',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false\n }, {\n name: 'CertificationRequestInfo.attributes.value',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true\n }]\n }]\n }]\n};\n\n// validator for a CertificationRequest structure\nvar certificationRequestValidator = {\n name: 'CertificationRequest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'csr',\n value: [\n certificationRequestInfoValidator, {\n // AlgorithmIdentifier (signature algorithm)\n name: 'CertificationRequest.signatureAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // algorithm\n name: 'CertificationRequest.signatureAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'csrSignatureOid'\n }, {\n name: 'CertificationRequest.signatureAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n optional: true,\n captureAsn1: 'csrSignatureParams'\n }]\n }, {\n // signature\n name: 'CertificationRequest.signature',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n captureBitStringValue: 'csrSignature'\n }\n ]\n};\n\n/**\n * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName\n * sets into an array with objects that have type and value properties.\n *\n * @param rdn the RDNSequence to convert.\n * @param md a message digest to append type and value to if provided.\n */\npki.RDNAttributesAsArray = function(rdn, md) {\n var rval = [];\n\n // each value in 'rdn' in is a SET of RelativeDistinguishedName\n var set, attr, obj;\n for(var si = 0; si < rdn.value.length; ++si) {\n // get the RelativeDistinguishedName set\n set = rdn.value[si];\n\n // each value in the SET is an AttributeTypeAndValue sequence\n // containing first a type (an OID) and second a value (defined by\n // the OID)\n for(var i = 0; i < set.value.length; ++i) {\n obj = {};\n attr = set.value[i];\n obj.type = asn1.derToOid(attr.value[0].value);\n obj.value = attr.value[1].value;\n obj.valueTagClass = attr.value[1].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n if(md) {\n md.update(obj.type);\n md.update(obj.value);\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Converts ASN.1 CRIAttributes into an array with objects that have type and\n * value properties.\n *\n * @param attributes the CRIAttributes to convert.\n */\npki.CRIAttributesAsArray = function(attributes) {\n var rval = [];\n\n // each value in 'attributes' in is a SEQUENCE with an OID and a SET\n for(var si = 0; si < attributes.length; ++si) {\n // get the attribute sequence\n var seq = attributes[si];\n\n // each value in the SEQUENCE containing first a type (an OID) and\n // second a set of values (defined by the OID)\n var type = asn1.derToOid(seq.value[0].value);\n var values = seq.value[1].value;\n for(var vi = 0; vi < values.length; ++vi) {\n var obj = {};\n obj.type = type;\n obj.value = values[vi].value;\n obj.valueTagClass = values[vi].type;\n // if the OID is known, get its name and short name\n if(obj.type in oids) {\n obj.name = oids[obj.type];\n if(obj.name in _shortNames) {\n obj.shortName = _shortNames[obj.name];\n }\n }\n // parse extensions\n if(obj.type === oids.extensionRequest) {\n obj.extensions = [];\n for(var ei = 0; ei < obj.value.length; ++ei) {\n obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));\n }\n }\n rval.push(obj);\n }\n }\n\n return rval;\n};\n\n/**\n * Gets an issuer or subject attribute from its name, type, or short name.\n *\n * @param obj the issuer or subject object.\n * @param options a short name string or an object with:\n * shortName the short name for the attribute.\n * name the name for the attribute.\n * type the type for the attribute.\n *\n * @return the attribute.\n */\nfunction _getAttribute(obj, options) {\n if(typeof options === 'string') {\n options = {shortName: options};\n }\n\n var rval = null;\n var attr;\n for(var i = 0; rval === null && i < obj.attributes.length; ++i) {\n attr = obj.attributes[i];\n if(options.type && options.type === attr.type) {\n rval = attr;\n } else if(options.name && options.name === attr.name) {\n rval = attr;\n } else if(options.shortName && options.shortName === attr.shortName) {\n rval = attr;\n }\n }\n return rval;\n}\n\n/**\n * Converts signature parameters from ASN.1 structure.\n *\n * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had\n * no parameters.\n *\n * RSASSA-PSS-params ::= SEQUENCE {\n * hashAlgorithm [0] HashAlgorithm DEFAULT\n * sha1Identifier,\n * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT\n * mgf1SHA1Identifier,\n * saltLength [2] INTEGER DEFAULT 20,\n * trailerField [3] INTEGER DEFAULT 1\n * }\n *\n * HashAlgorithm ::= AlgorithmIdentifier\n *\n * MaskGenAlgorithm ::= AlgorithmIdentifier\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * @param oid The OID specifying the signature algorithm\n * @param obj The ASN.1 structure holding the parameters\n * @param fillDefaults Whether to use return default values where omitted\n * @return signature parameter object\n */\nvar _readSignatureParameters = function(oid, obj, fillDefaults) {\n var params = {};\n\n if(oid !== oids['RSASSA-PSS']) {\n return params;\n }\n\n if(fillDefaults) {\n params = {\n hash: {\n algorithmOid: oids['sha1']\n },\n mgf: {\n algorithmOid: oids['mgf1'],\n hash: {\n algorithmOid: oids['sha1']\n }\n },\n saltLength: 20\n };\n }\n\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {\n var error = new Error('Cannot read RSASSA-PSS parameter block.');\n error.errors = errors;\n throw error;\n }\n\n if(capture.hashOid !== undefined) {\n params.hash = params.hash || {};\n params.hash.algorithmOid = asn1.derToOid(capture.hashOid);\n }\n\n if(capture.maskGenOid !== undefined) {\n params.mgf = params.mgf || {};\n params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);\n params.mgf.hash = params.mgf.hash || {};\n params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);\n }\n\n if(capture.saltLength !== undefined) {\n params.saltLength = capture.saltLength.charCodeAt(0);\n }\n\n return params;\n};\n\n/**\n * Converts an X.509 certificate from PEM format.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. This will scan the TBSCertificate part of the ASN.1\n * object while it is converted so it doesn't need to be converted back\n * to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certificate.\n */\npki.certificateFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error(\n 'Could not convert certificate from PEM; PEM header type ' +\n 'is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or \"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error(\n 'Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificateFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts an X.509 certificate to PEM format.\n *\n * @param cert the certificate.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certificate.\n */\npki.certificateToPem = function(cert, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE',\n body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key from PEM format.\n *\n * @param pem the PEM-formatted public key.\n *\n * @return the public key.\n */\npki.publicKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {\n var error = new Error('Could not convert public key from PEM; PEM header ' +\n 'type is not \"PUBLIC KEY\" or \"RSA PUBLIC KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert public key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.publicKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts an RSA public key to PEM format (using an RSAPublicKey).\n *\n * @param key the public key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted public key.\n */\npki.publicKeyToRSAPublicKeyPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PUBLIC KEY',\n body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Gets a fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.sha1).\n * [type] the type of fingerprint, such as 'RSAPublicKey',\n * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\npki.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.sha1.create();\n var type = options.type || 'RSAPublicKey';\n\n var bytes;\n switch(type) {\n case 'RSAPublicKey':\n bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();\n break;\n case 'SubjectPublicKeyInfo':\n bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();\n break;\n default:\n throw new Error('Unknown fingerprint type \"' + options.type + '\".');\n }\n\n // hash public key bytes\n md.start();\n md.update(bytes);\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from PEM format.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. This will scan the CertificationRequestInfo part of\n * the ASN.1 object while it is converted so it doesn't need to be converted\n * back to ASN.1-DER-encoding later.\n *\n * @param pem the PEM-formatted certificate.\n * @param computeHash true to compute the hash for verification.\n * @param strict true to be strict when checking ASN.1 value lengths, false to\n * allow truncated values (default: true).\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromPem = function(pem, computeHash, strict) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'CERTIFICATE REQUEST') {\n var error = new Error('Could not convert certification request from PEM; ' +\n 'PEM header type is not \"CERTIFICATE REQUEST\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certification request from PEM; ' +\n 'PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body, strict);\n\n return pki.certificationRequestFromAsn1(obj, computeHash);\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) to PEM format.\n *\n * @param csr the certification request.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted certification request.\n */\npki.certificationRequestToPem = function(csr, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'CERTIFICATE REQUEST',\n body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Creates an empty X.509v3 RSA certificate.\n *\n * @return the certificate.\n */\npki.createCertificate = function() {\n var cert = {};\n cert.version = 0x02;\n cert.serialNumber = '00';\n cert.signatureOid = null;\n cert.signature = null;\n cert.siginfo = {};\n cert.siginfo.algorithmOid = null;\n cert.validity = {};\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n\n cert.issuer = {};\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = [];\n cert.issuer.hash = null;\n\n cert.subject = {};\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = [];\n cert.subject.hash = null;\n\n cert.extensions = [];\n cert.publicKey = null;\n cert.md = null;\n\n /**\n * Sets the subject of this certificate.\n *\n * @param attrs the array of subject attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setSubject = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.subject.attributes = attrs;\n delete cert.subject.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.subject.uniqueId = uniqueId;\n }\n cert.subject.hash = null;\n };\n\n /**\n * Sets the issuer of this certificate.\n *\n * @param attrs the array of issuer attributes to use.\n * @param uniqueId an optional a unique ID to use.\n */\n cert.setIssuer = function(attrs, uniqueId) {\n // set new attributes, clear hash\n _fillMissingFields(attrs);\n cert.issuer.attributes = attrs;\n delete cert.issuer.uniqueId;\n if(uniqueId) {\n // TODO: support arbitrary bit length ids\n cert.issuer.uniqueId = uniqueId;\n }\n cert.issuer.hash = null;\n };\n\n /**\n * Sets the extensions of this certificate.\n *\n * @param exts the array of extensions to use.\n */\n cert.setExtensions = function(exts) {\n for(var i = 0; i < exts.length; ++i) {\n _fillMissingExtensionFields(exts[i], {cert: cert});\n }\n // set new extensions\n cert.extensions = exts;\n };\n\n /**\n * Gets an extension by its name or id.\n *\n * @param options the name to use or an object with:\n * name the name to use.\n * id the id to use.\n *\n * @return the extension or null if not found.\n */\n cert.getExtension = function(options) {\n if(typeof options === 'string') {\n options = {name: options};\n }\n\n var rval = null;\n var ext;\n for(var i = 0; rval === null && i < cert.extensions.length; ++i) {\n ext = cert.extensions[i];\n if(options.id && ext.id === options.id) {\n rval = ext;\n } else if(options.name && ext.name === options.name) {\n rval = ext;\n }\n }\n return rval;\n };\n\n /**\n * Signs this certificate using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n cert.sign = function(key, md) {\n // TODO: get signature OID from private key\n cert.md = md || forge.md.sha1.create();\n var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = cert.md.algorithm;\n throw error;\n }\n cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;\n\n // get TBSCertificate, convert to DER\n cert.tbsCertificate = pki.getTBSCertificate(cert);\n var bytes = asn1.toDer(cert.tbsCertificate);\n\n // digest and sign\n cert.md.update(bytes.getBytes());\n cert.signature = key.sign(cert.md);\n };\n\n /**\n * Attempts verify the signature on the passed certificate using this\n * certificate's public key.\n *\n * @param child the certificate to verify.\n *\n * @return true if verified, false if not.\n */\n cert.verify = function(child) {\n var rval = false;\n\n if(!cert.issued(child)) {\n var issuer = child.issuer;\n var subject = cert.subject;\n var error = new Error(\n 'The parent certificate did not issue the given child ' +\n 'certificate; the child certificate\\'s issuer does not match the ' +\n 'parent\\'s subject.');\n error.expectedIssuer = issuer.attributes;\n error.actualIssuer = subject.attributes;\n throw error;\n }\n\n var md = child.md;\n if(md === null) {\n // check signature OID for supported signature types\n if(child.signatureOid in oids) {\n var oid = oids[child.signatureOid];\n switch(oid) {\n case 'sha1WithRSAEncryption':\n md = forge.md.sha1.create();\n break;\n case 'md5WithRSAEncryption':\n md = forge.md.md5.create();\n break;\n case 'sha256WithRSAEncryption':\n md = forge.md.sha256.create();\n break;\n case 'sha384WithRSAEncryption':\n md = forge.md.sha384.create();\n break;\n case 'sha512WithRSAEncryption':\n md = forge.md.sha512.create();\n break;\n case 'RSASSA-PSS':\n md = forge.md.sha256.create();\n break;\n }\n }\n if(md === null) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = child.signatureOid;\n throw error;\n }\n\n // produce DER formatted TBSCertificate and digest it\n var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);\n var bytes = asn1.toDer(tbsCertificate);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n var scheme;\n\n switch(child.signatureOid) {\n case oids.sha1WithRSAEncryption:\n scheme = undefined; /* use PKCS#1 v1.5 padding scheme */\n break;\n case oids['RSASSA-PSS']:\n var hash, mgf;\n\n /* initialize mgf */\n hash = oids[child.signatureParameters.mgf.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported MGF hash function.');\n error.oid = child.signatureParameters.mgf.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n mgf = oids[child.signatureParameters.mgf.algorithmOid];\n if(mgf === undefined || forge.mgf[mgf] === undefined) {\n var error = new Error('Unsupported MGF function.');\n error.oid = child.signatureParameters.mgf.algorithmOid;\n error.name = mgf;\n throw error;\n }\n\n mgf = forge.mgf[mgf].create(forge.md[hash].create());\n\n /* initialize hash function */\n hash = oids[child.signatureParameters.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n throw {\n message: 'Unsupported RSASSA-PSS hash function.',\n oid: child.signatureParameters.hash.algorithmOid,\n name: hash\n };\n }\n\n scheme = forge.pss.create(forge.md[hash].create(), mgf,\n child.signatureParameters.saltLength);\n break;\n }\n\n // verify signature on cert using public key\n rval = cert.publicKey.verify(\n md.digest().getBytes(), child.signature, scheme);\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's issuer matches the passed\n * certificate's subject. Note that no signature check is performed.\n *\n * @param parent the certificate to check.\n *\n * @return true if this certificate's issuer matches the passed certificate's\n * subject.\n */\n cert.isIssuer = function(parent) {\n var rval = false;\n\n var i = cert.issuer;\n var s = parent.subject;\n\n // compare hashes if present\n if(i.hash && s.hash) {\n rval = (i.hash === s.hash);\n } else if(i.attributes.length === s.attributes.length) {\n // all attributes are the same so issuer matches subject\n rval = true;\n var iattr, sattr;\n for(var n = 0; rval && n < i.attributes.length; ++n) {\n iattr = i.attributes[n];\n sattr = s.attributes[n];\n if(iattr.type !== sattr.type || iattr.value !== sattr.value) {\n // attribute mismatch\n rval = false;\n }\n }\n }\n\n return rval;\n };\n\n /**\n * Returns true if this certificate's subject matches the issuer of the\n * given certificate). Note that not signature check is performed.\n *\n * @param child the certificate to check.\n *\n * @return true if this certificate's subject matches the passed\n * certificate's issuer.\n */\n cert.issued = function(child) {\n return child.isIssuer(cert);\n };\n\n /**\n * Generates the subjectKeyIdentifier for this certificate as byte buffer.\n *\n * @return the subjectKeyIdentifier for this certificate as byte buffer.\n */\n cert.generateSubjectKeyIdentifier = function() {\n /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:\n\n (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the\n value of the BIT STRING subjectPublicKey (excluding the tag,\n length, and number of unused bits).\n\n (2) The keyIdentifier is composed of a four bit type field with\n the value 0100 followed by the least significant 60 bits of the\n SHA-1 hash of the value of the BIT STRING subjectPublicKey\n (excluding the tag, length, and number of unused bit string bits).\n */\n\n // skipping the tag, length, and number of unused bits is the same\n // as just using the RSAPublicKey (for RSA keys, which are the\n // only ones supported)\n return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});\n };\n\n /**\n * Verifies the subjectKeyIdentifier extension value for this certificate\n * against its public key. If no extension is found, false will be\n * returned.\n *\n * @return true if verified, false if not.\n */\n cert.verifySubjectKeyIdentifier = function() {\n var oid = oids['subjectKeyIdentifier'];\n for(var i = 0; i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.id === oid) {\n var ski = cert.generateSubjectKeyIdentifier().getBytes();\n return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);\n }\n }\n return false;\n };\n\n return cert;\n};\n\n/**\n * Converts an X.509v3 RSA certificate from an ASN.1 object.\n *\n * Note: If the certificate is to be verified then compute hash should\n * be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1\n * object needs to be scanned before the cert object is created.\n *\n * @param obj the asn1 representation of an X.509v3 RSA certificate.\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certificate.\n */\npki.certificateFromAsn1 = function(obj, computeHash) {\n // validate certificate and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {\n var error = new Error('Cannot read X.509 certificate. ' +\n 'ASN.1 object is not an X509v3 Certificate.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certificate\n var cert = pki.createCertificate();\n cert.version = capture.certVersion ?\n capture.certVersion.charCodeAt(0) : 0;\n var serial = forge.util.createBuffer(capture.certSerialNumber);\n cert.serialNumber = serial.toHex();\n cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);\n cert.signatureParameters = _readSignatureParameters(\n cert.signatureOid, capture.certSignatureParams, true);\n cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);\n cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,\n capture.certinfoSignatureParams, false);\n cert.signature = capture.certSignature;\n\n var validity = [];\n if(capture.certValidity1UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));\n }\n if(capture.certValidity2GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity2GeneralizedTime));\n }\n if(capture.certValidity3UTCTime !== undefined) {\n validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));\n }\n if(capture.certValidity4GeneralizedTime !== undefined) {\n validity.push(asn1.generalizedTimeToDate(\n capture.certValidity4GeneralizedTime));\n }\n if(validity.length > 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; more ' +\n 'than two times were provided in the certificate.');\n }\n if(validity.length < 2) {\n throw new Error('Cannot read notBefore/notAfter validity times; they ' +\n 'were not provided as either UTCTime or GeneralizedTime.');\n }\n cert.validity.notBefore = validity[0];\n cert.validity.notAfter = validity[1];\n\n // keep TBSCertificate to preserve signature when exporting\n cert.tbsCertificate = capture.tbsCertificate;\n\n if(computeHash) {\n // check signature OID for supported signature types\n cert.md = null;\n if(cert.signatureOid in oids) {\n var oid = oids[cert.signatureOid];\n switch(oid) {\n case 'sha1WithRSAEncryption':\n cert.md = forge.md.sha1.create();\n break;\n case 'md5WithRSAEncryption':\n cert.md = forge.md.md5.create();\n break;\n case 'sha256WithRSAEncryption':\n cert.md = forge.md.sha256.create();\n break;\n case 'sha384WithRSAEncryption':\n cert.md = forge.md.sha384.create();\n break;\n case 'sha512WithRSAEncryption':\n cert.md = forge.md.sha512.create();\n break;\n case 'RSASSA-PSS':\n cert.md = forge.md.sha256.create();\n break;\n }\n }\n if(cert.md === null) {\n var error = new Error('Could not compute certificate digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = cert.signatureOid;\n throw error;\n }\n\n // produce DER formatted TBSCertificate and digest it\n var bytes = asn1.toDer(cert.tbsCertificate);\n cert.md.update(bytes.getBytes());\n }\n\n // handle issuer, build issuer message digest\n var imd = forge.md.sha1.create();\n cert.issuer.getField = function(sn) {\n return _getAttribute(cert.issuer, sn);\n };\n cert.issuer.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.issuer.attributes.push(attr);\n };\n cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer, imd);\n if(capture.certIssuerUniqueId) {\n cert.issuer.uniqueId = capture.certIssuerUniqueId;\n }\n cert.issuer.hash = imd.digest().toHex();\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n cert.subject.getField = function(sn) {\n return _getAttribute(cert.subject, sn);\n };\n cert.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n cert.subject.attributes.push(attr);\n };\n cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject, smd);\n if(capture.certSubjectUniqueId) {\n cert.subject.uniqueId = capture.certSubjectUniqueId;\n }\n cert.subject.hash = smd.digest().toHex();\n\n // handle extensions\n if(capture.certExtensions) {\n cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);\n } else {\n cert.extensions = [];\n }\n\n // convert RSA public key from ASN.1\n cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n return cert;\n};\n\n/**\n * Converts an ASN.1 extensions object (with extension sequences as its\n * values) into an array of extension objects with types and values.\n *\n * Supported extensions:\n *\n * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }\n * KeyUsage ::= BIT STRING {\n * digitalSignature (0),\n * nonRepudiation (1),\n * keyEncipherment (2),\n * dataEncipherment (3),\n * keyAgreement (4),\n * keyCertSign (5),\n * cRLSign (6),\n * encipherOnly (7),\n * decipherOnly (8)\n * }\n *\n * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }\n * BasicConstraints ::= SEQUENCE {\n * cA BOOLEAN DEFAULT FALSE,\n * pathLenConstraint INTEGER (0..MAX) OPTIONAL\n * }\n *\n * subjectAltName EXTENSION ::= {\n * SYNTAX GeneralNames\n * IDENTIFIED BY id-ce-subjectAltName\n * }\n *\n * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName\n *\n * GeneralName ::= CHOICE {\n * otherName [0] INSTANCE OF OTHER-NAME,\n * rfc822Name [1] IA5String,\n * dNSName [2] IA5String,\n * x400Address [3] ORAddress,\n * directoryName [4] Name,\n * ediPartyName [5] EDIPartyName,\n * uniformResourceIdentifier [6] IA5String,\n * IPAddress [7] OCTET STRING,\n * registeredID [8] OBJECT IDENTIFIER\n * }\n *\n * OTHER-NAME ::= TYPE-IDENTIFIER\n *\n * EDIPartyName ::= SEQUENCE {\n * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,\n * partyName [1] DirectoryString {ub-name}\n * }\n *\n * @param exts the extensions ASN.1 with extension sequences to parse.\n *\n * @return the array.\n */\npki.certificateExtensionsFromAsn1 = function(exts) {\n var rval = [];\n for(var i = 0; i < exts.value.length; ++i) {\n // get extension sequence\n var extseq = exts.value[i];\n for(var ei = 0; ei < extseq.value.length; ++ei) {\n rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));\n }\n }\n\n return rval;\n};\n\n/**\n * Parses a single certificate extension from ASN.1.\n *\n * @param ext the extension in ASN.1 format.\n *\n * @return the parsed extension as an object.\n */\npki.certificateExtensionFromAsn1 = function(ext) {\n // an extension has:\n // [0] extnID OBJECT IDENTIFIER\n // [1] critical BOOLEAN DEFAULT FALSE\n // [2] extnValue OCTET STRING\n var e = {};\n e.id = asn1.derToOid(ext.value[0].value);\n e.critical = false;\n if(ext.value[1].type === asn1.Type.BOOLEAN) {\n e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);\n e.value = ext.value[2].value;\n } else {\n e.value = ext.value[1].value;\n }\n // if the oid is known, get its name\n if(e.id in oids) {\n e.name = oids[e.id];\n\n // handle key usage\n if(e.name === 'keyUsage') {\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n var b3 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;\n }\n // set flags\n e.digitalSignature = (b2 & 0x80) === 0x80;\n e.nonRepudiation = (b2 & 0x40) === 0x40;\n e.keyEncipherment = (b2 & 0x20) === 0x20;\n e.dataEncipherment = (b2 & 0x10) === 0x10;\n e.keyAgreement = (b2 & 0x08) === 0x08;\n e.keyCertSign = (b2 & 0x04) === 0x04;\n e.cRLSign = (b2 & 0x02) === 0x02;\n e.encipherOnly = (b2 & 0x01) === 0x01;\n e.decipherOnly = (b3 & 0x80) === 0x80;\n } else if(e.name === 'basicConstraints') {\n // handle basic constraints\n // get value as SEQUENCE\n var ev = asn1.fromDer(e.value);\n // get cA BOOLEAN flag (defaults to false)\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {\n e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);\n } else {\n e.cA = false;\n }\n // get path length constraint\n var value = null;\n if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {\n value = ev.value[0].value;\n } else if(ev.value.length > 1) {\n value = ev.value[1].value;\n }\n if(value !== null) {\n e.pathLenConstraint = asn1.derToInteger(value);\n }\n } else if(e.name === 'extKeyUsage') {\n // handle extKeyUsage\n // value is a SEQUENCE of OIDs\n var ev = asn1.fromDer(e.value);\n for(var vi = 0; vi < ev.value.length; ++vi) {\n var oid = asn1.derToOid(ev.value[vi].value);\n if(oid in oids) {\n e[oids[oid]] = true;\n } else {\n e[oid] = true;\n }\n }\n } else if(e.name === 'nsCertType') {\n // handle nsCertType\n // get value as BIT STRING\n var ev = asn1.fromDer(e.value);\n var b2 = 0x00;\n if(ev.value.length > 1) {\n // skip first byte, just indicates unused bits which\n // will be padded with 0s anyway\n // get bytes with flag bits\n b2 = ev.value.charCodeAt(1);\n }\n // set flags\n e.client = (b2 & 0x80) === 0x80;\n e.server = (b2 & 0x40) === 0x40;\n e.email = (b2 & 0x20) === 0x20;\n e.objsign = (b2 & 0x10) === 0x10;\n e.reserved = (b2 & 0x08) === 0x08;\n e.sslCA = (b2 & 0x04) === 0x04;\n e.emailCA = (b2 & 0x02) === 0x02;\n e.objCA = (b2 & 0x01) === 0x01;\n } else if(\n e.name === 'subjectAltName' ||\n e.name === 'issuerAltName') {\n // handle subjectAltName/issuerAltName\n e.altNames = [];\n\n // ev is a SYNTAX SEQUENCE\n var gn;\n var ev = asn1.fromDer(e.value);\n for(var n = 0; n < ev.value.length; ++n) {\n // get GeneralName\n gn = ev.value[n];\n\n var altName = {\n type: gn.type,\n value: gn.value\n };\n e.altNames.push(altName);\n\n // Note: Support for types 1,2,6,7,8\n switch(gn.type) {\n // rfc822Name\n case 1:\n // dNSName\n case 2:\n // uniformResourceIdentifier (URI)\n case 6:\n break;\n // IPAddress\n case 7:\n // convert to IPv4/IPv6 string representation\n altName.ip = forge.util.bytesToIP(gn.value);\n break;\n // registeredID\n case 8:\n altName.oid = asn1.derToOid(gn.value);\n break;\n default:\n // unsupported\n }\n }\n } else if(e.name === 'subjectKeyIdentifier') {\n // value is an OCTETSTRING w/the hash of the key-type specific\n // public key structure (eg: RSAPublicKey)\n var ev = asn1.fromDer(e.value);\n e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);\n }\n }\n return e;\n};\n\n/**\n * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.\n *\n * Note: If the certification request is to be verified then compute hash\n * should be set to true. There is currently no implementation for converting\n * a certificate back to ASN.1 so the CertificationRequestInfo part of the\n * ASN.1 object needs to be scanned before the csr object is created.\n *\n * @param obj the asn1 representation of a PKCS#10 certification request (CSR).\n * @param computeHash true to compute the hash for verification.\n *\n * @return the certification request (CSR).\n */\npki.certificationRequestFromAsn1 = function(obj, computeHash) {\n // validate certification request and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#10 certificate request. ' +\n 'ASN.1 object is not a PKCS#10 CertificationRequest.');\n error.errors = errors;\n throw error;\n }\n\n // get oid\n var oid = asn1.derToOid(capture.publicKeyOid);\n if(oid !== pki.oids.rsaEncryption) {\n throw new Error('Cannot read public key. OID is not RSA.');\n }\n\n // create certification request\n var csr = pki.createCertificationRequest();\n csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;\n csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.signatureParameters = _readSignatureParameters(\n csr.signatureOid, capture.csrSignatureParams, true);\n csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);\n csr.siginfo.parameters = _readSignatureParameters(\n csr.siginfo.algorithmOid, capture.csrSignatureParams, false);\n csr.signature = capture.csrSignature;\n\n // keep CertificationRequestInfo to preserve signature when exporting\n csr.certificationRequestInfo = capture.certificationRequestInfo;\n\n if(computeHash) {\n // check signature OID for supported signature types\n csr.md = null;\n if(csr.signatureOid in oids) {\n var oid = oids[csr.signatureOid];\n switch(oid) {\n case 'sha1WithRSAEncryption':\n csr.md = forge.md.sha1.create();\n break;\n case 'md5WithRSAEncryption':\n csr.md = forge.md.md5.create();\n break;\n case 'sha256WithRSAEncryption':\n csr.md = forge.md.sha256.create();\n break;\n case 'sha384WithRSAEncryption':\n csr.md = forge.md.sha384.create();\n break;\n case 'sha512WithRSAEncryption':\n csr.md = forge.md.sha512.create();\n break;\n case 'RSASSA-PSS':\n csr.md = forge.md.sha256.create();\n break;\n }\n }\n if(csr.md === null) {\n var error = new Error('Could not compute certification request digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = csr.signatureOid;\n throw error;\n }\n\n // produce DER formatted CertificationRequestInfo and digest it\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n csr.md.update(bytes.getBytes());\n }\n\n // handle subject, build subject message digest\n var smd = forge.md.sha1.create();\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = pki.RDNAttributesAsArray(\n capture.certificationRequestInfoSubject, smd);\n csr.subject.hash = smd.digest().toHex();\n\n // convert RSA public key from ASN.1\n csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);\n\n // convert attributes from ASN.1\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.attributes = pki.CRIAttributesAsArray(\n capture.certificationRequestInfoAttributes || []);\n\n return csr;\n};\n\n/**\n * Creates an empty certification request (a CSR or certificate signing\n * request). Once created, its public key and attributes can be set and then\n * it can be signed.\n *\n * @return the empty certification request.\n */\npki.createCertificationRequest = function() {\n var csr = {};\n csr.version = 0x00;\n csr.signatureOid = null;\n csr.signature = null;\n csr.siginfo = {};\n csr.siginfo.algorithmOid = null;\n\n csr.subject = {};\n csr.subject.getField = function(sn) {\n return _getAttribute(csr.subject, sn);\n };\n csr.subject.addField = function(attr) {\n _fillMissingFields([attr]);\n csr.subject.attributes.push(attr);\n };\n csr.subject.attributes = [];\n csr.subject.hash = null;\n\n csr.publicKey = null;\n csr.attributes = [];\n csr.getAttribute = function(sn) {\n return _getAttribute(csr, sn);\n };\n csr.addAttribute = function(attr) {\n _fillMissingFields([attr]);\n csr.attributes.push(attr);\n };\n csr.md = null;\n\n /**\n * Sets the subject of this certification request.\n *\n * @param attrs the array of subject attributes to use.\n */\n csr.setSubject = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.subject.attributes = attrs;\n csr.subject.hash = null;\n };\n\n /**\n * Sets the attributes of this certification request.\n *\n * @param attrs the array of attributes to use.\n */\n csr.setAttributes = function(attrs) {\n // set new attributes\n _fillMissingFields(attrs);\n csr.attributes = attrs;\n };\n\n /**\n * Signs this certification request using the given private key.\n *\n * @param key the private key to sign with.\n * @param md the message digest object to use (defaults to forge.md.sha1).\n */\n csr.sign = function(key, md) {\n // TODO: get signature OID from private key\n csr.md = md || forge.md.sha1.create();\n var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];\n if(!algorithmOid) {\n var error = new Error('Could not compute certification request digest. ' +\n 'Unknown message digest algorithm OID.');\n error.algorithm = csr.md.algorithm;\n throw error;\n }\n csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;\n\n // get CertificationRequestInfo, convert to DER\n csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(csr.certificationRequestInfo);\n\n // digest and sign\n csr.md.update(bytes.getBytes());\n csr.signature = key.sign(csr.md);\n };\n\n /**\n * Attempts verify the signature on the passed certification request using\n * its public key.\n *\n * A CSR that has been exported to a file in PEM format can be verified using\n * OpenSSL using this command:\n *\n * openssl req -in -verify -noout -text\n *\n * @return true if verified, false if not.\n */\n csr.verify = function() {\n var rval = false;\n\n var md = csr.md;\n if(md === null) {\n // check signature OID for supported signature types\n if(csr.signatureOid in oids) {\n // TODO: create DRY `OID to md` function\n var oid = oids[csr.signatureOid];\n switch(oid) {\n case 'sha1WithRSAEncryption':\n md = forge.md.sha1.create();\n break;\n case 'md5WithRSAEncryption':\n md = forge.md.md5.create();\n break;\n case 'sha256WithRSAEncryption':\n md = forge.md.sha256.create();\n break;\n case 'sha384WithRSAEncryption':\n md = forge.md.sha384.create();\n break;\n case 'sha512WithRSAEncryption':\n md = forge.md.sha512.create();\n break;\n case 'RSASSA-PSS':\n md = forge.md.sha256.create();\n break;\n }\n }\n if(md === null) {\n var error = new Error(\n 'Could not compute certification request digest. ' +\n 'Unknown signature OID.');\n error.signatureOid = csr.signatureOid;\n throw error;\n }\n\n // produce DER formatted CertificationRequestInfo and digest it\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n var bytes = asn1.toDer(cri);\n md.update(bytes.getBytes());\n }\n\n if(md !== null) {\n var scheme;\n\n switch(csr.signatureOid) {\n case oids.sha1WithRSAEncryption:\n /* use PKCS#1 v1.5 padding scheme */\n break;\n case oids['RSASSA-PSS']:\n var hash, mgf;\n\n /* initialize mgf */\n hash = oids[csr.signatureParameters.mgf.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported MGF hash function.');\n error.oid = csr.signatureParameters.mgf.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n mgf = oids[csr.signatureParameters.mgf.algorithmOid];\n if(mgf === undefined || forge.mgf[mgf] === undefined) {\n var error = new Error('Unsupported MGF function.');\n error.oid = csr.signatureParameters.mgf.algorithmOid;\n error.name = mgf;\n throw error;\n }\n\n mgf = forge.mgf[mgf].create(forge.md[hash].create());\n\n /* initialize hash function */\n hash = oids[csr.signatureParameters.hash.algorithmOid];\n if(hash === undefined || forge.md[hash] === undefined) {\n var error = new Error('Unsupported RSASSA-PSS hash function.');\n error.oid = csr.signatureParameters.hash.algorithmOid;\n error.name = hash;\n throw error;\n }\n\n scheme = forge.pss.create(forge.md[hash].create(), mgf,\n csr.signatureParameters.saltLength);\n break;\n }\n\n // verify signature on csr using its public key\n rval = csr.publicKey.verify(\n md.digest().getBytes(), csr.signature, scheme);\n }\n\n return rval;\n };\n\n return csr;\n};\n\n/**\n * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.\n *\n * @param obj the subject or issuer (distinguished name).\n *\n * @return the ASN.1 RDNSequence.\n */\nfunction _dnToAsn1(obj) {\n // create an empty RDNSequence\n var rval = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // iterate over attributes\n var attr, set;\n var attrs = obj.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.PRINTABLESTRING;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n // FIXME: handle more encodings\n }\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n // AttributeValue\n asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)\n ])\n ]);\n rval.value.push(set);\n }\n\n return rval;\n}\n\n/**\n * Gets all printable attributes (typically of an issuer or subject) in a\n * simplified JSON format for display.\n *\n * @param attrs the attributes.\n *\n * @return the JSON for display.\n */\nfunction _getAttributesAsJson(attrs) {\n var rval = {};\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n if(attr.shortName && (\n attr.valueTagClass === asn1.Type.UTF8 ||\n attr.valueTagClass === asn1.Type.PRINTABLESTRING ||\n attr.valueTagClass === asn1.Type.IA5STRING)) {\n var value = attr.value;\n if(attr.valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(attr.value);\n }\n if(!(attr.shortName in rval)) {\n rval[attr.shortName] = value;\n } else if(forge.util.isArray(rval[attr.shortName])) {\n rval[attr.shortName].push(value);\n } else {\n rval[attr.shortName] = [rval[attr.shortName], value];\n }\n }\n }\n return rval;\n}\n\n/**\n * Fills in missing fields in attributes.\n *\n * @param attrs the attributes to fill missing fields in.\n */\nfunction _fillMissingFields(attrs) {\n var attr;\n for(var i = 0; i < attrs.length; ++i) {\n attr = attrs[i];\n\n // populate missing name\n if(typeof attr.name === 'undefined') {\n if(attr.type && attr.type in pki.oids) {\n attr.name = pki.oids[attr.type];\n } else if(attr.shortName && attr.shortName in _shortNames) {\n attr.name = pki.oids[_shortNames[attr.shortName]];\n }\n }\n\n // populate missing type (OID)\n if(typeof attr.type === 'undefined') {\n if(attr.name && attr.name in pki.oids) {\n attr.type = pki.oids[attr.name];\n } else {\n var error = new Error('Attribute type not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n\n // populate missing shortname\n if(typeof attr.shortName === 'undefined') {\n if(attr.name && attr.name in _shortNames) {\n attr.shortName = _shortNames[attr.name];\n }\n }\n\n // convert extensions to value\n if(attr.type === oids.extensionRequest) {\n attr.valueConstructed = true;\n attr.valueTagClass = asn1.Type.SEQUENCE;\n if(!attr.value && attr.extensions) {\n attr.value = [];\n for(var ei = 0; ei < attr.extensions.length; ++ei) {\n attr.value.push(pki.certificateExtensionToAsn1(\n _fillMissingExtensionFields(attr.extensions[ei])));\n }\n }\n }\n\n if(typeof attr.value === 'undefined') {\n var error = new Error('Attribute value not specified.');\n error.attribute = attr;\n throw error;\n }\n }\n}\n\n/**\n * Fills in missing fields in certificate extensions.\n *\n * @param e the extension.\n * @param [options] the options to use.\n * [cert] the certificate the extensions are for.\n *\n * @return the extension.\n */\nfunction _fillMissingExtensionFields(e, options) {\n options = options || {};\n\n // populate missing name\n if(typeof e.name === 'undefined') {\n if(e.id && e.id in pki.oids) {\n e.name = pki.oids[e.id];\n }\n }\n\n // populate missing id\n if(typeof e.id === 'undefined') {\n if(e.name && e.name in pki.oids) {\n e.id = pki.oids[e.name];\n } else {\n var error = new Error('Extension ID not specified.');\n error.extension = e;\n throw error;\n }\n }\n\n if(typeof e.value !== 'undefined') {\n return e;\n }\n\n // handle missing value:\n\n // value is a BIT STRING\n if(e.name === 'keyUsage') {\n // build flags\n var unused = 0;\n var b2 = 0x00;\n var b3 = 0x00;\n if(e.digitalSignature) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.nonRepudiation) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.keyEncipherment) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.dataEncipherment) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.keyAgreement) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.keyCertSign) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.cRLSign) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.encipherOnly) {\n b2 |= 0x01;\n unused = 0;\n }\n if(e.decipherOnly) {\n b3 |= 0x80;\n unused = 7;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b3 !== 0) {\n value += String.fromCharCode(b2) + String.fromCharCode(b3);\n } else if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'basicConstraints') {\n // basicConstraints is a SEQUENCE\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n // cA BOOLEAN flag defaults to false\n if(e.cA) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n if('pathLenConstraint' in e) {\n e.value.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(e.pathLenConstraint).getBytes()));\n }\n } else if(e.name === 'extKeyUsage') {\n // extKeyUsage is a SEQUENCE of OIDs\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n for(var key in e) {\n if(e[key] !== true) {\n continue;\n }\n // key is name in OID map\n if(key in oids) {\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(oids[key]).getBytes()));\n } else if(key.indexOf('.') !== -1) {\n // assume key is an OID\n seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,\n false, asn1.oidToDer(key).getBytes()));\n }\n }\n } else if(e.name === 'nsCertType') {\n // nsCertType is a BIT STRING\n // build flags\n var unused = 0;\n var b2 = 0x00;\n\n if(e.client) {\n b2 |= 0x80;\n unused = 7;\n }\n if(e.server) {\n b2 |= 0x40;\n unused = 6;\n }\n if(e.email) {\n b2 |= 0x20;\n unused = 5;\n }\n if(e.objsign) {\n b2 |= 0x10;\n unused = 4;\n }\n if(e.reserved) {\n b2 |= 0x08;\n unused = 3;\n }\n if(e.sslCA) {\n b2 |= 0x04;\n unused = 2;\n }\n if(e.emailCA) {\n b2 |= 0x02;\n unused = 1;\n }\n if(e.objCA) {\n b2 |= 0x01;\n unused = 0;\n }\n\n // create bit string\n var value = String.fromCharCode(unused);\n if(b2 !== 0) {\n value += String.fromCharCode(b2);\n }\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);\n } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n e.value.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n } else if(e.name === 'nsComment' && options.cert) {\n // sanity check value is ASCII (req'd) and not too big\n if(!(/^[\\x00-\\x7F]*$/.test(e.comment)) ||\n (e.comment.length < 1) || (e.comment.length > 128)) {\n throw new Error('Invalid \"nsComment\" content.');\n }\n // IA5STRING opaque comment\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);\n } else if(e.name === 'subjectKeyIdentifier' && options.cert) {\n var ski = options.cert.generateSubjectKeyIdentifier();\n e.subjectKeyIdentifier = ski.toHex();\n // OCTETSTRING w/digest\n e.value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());\n } else if(e.name === 'authorityKeyIdentifier' && options.cert) {\n // SYNTAX SEQUENCE\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n if(e.keyIdentifier) {\n var keyIdentifier = (e.keyIdentifier === true ?\n options.cert.generateSubjectKeyIdentifier().getBytes() :\n e.keyIdentifier);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));\n }\n\n if(e.authorityCertIssuer) {\n var authorityCertIssuer = [\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [\n _dnToAsn1(e.authorityCertIssuer === true ?\n options.cert.issuer : e.authorityCertIssuer)\n ])\n ];\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));\n }\n\n if(e.serialNumber) {\n var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?\n options.cert.serialNumber : e.serialNumber);\n seq.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));\n }\n } else if(e.name === 'cRLDistributionPoints') {\n e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n var seq = e.value.value;\n\n // Create sub SEQUENCE of DistributionPointName\n var subSeq = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // Create fullName CHOICE\n var fullNameGeneralNames = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n var altName;\n for(var n = 0; n < e.altNames.length; ++n) {\n altName = e.altNames[n];\n var value = altName.value;\n // handle IP\n if(altName.type === 7 && altName.ip) {\n value = forge.util.bytesFromIP(altName.ip);\n if(value === null) {\n var error = new Error(\n 'Extension \"ip\" value is not a valid IPv4 or IPv6 address.');\n error.extension = e;\n throw error;\n }\n } else if(altName.type === 8) {\n // handle OID\n if(altName.oid) {\n value = asn1.oidToDer(asn1.oidToDer(altName.oid));\n } else {\n // deprecated ... convert value to OID\n value = asn1.oidToDer(value);\n }\n }\n fullNameGeneralNames.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, altName.type, false,\n value));\n }\n\n // Add to the parent SEQUENCE\n subSeq.value.push(asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));\n seq.push(subSeq);\n }\n\n // ensure value has been defined by now\n if(typeof e.value === 'undefined') {\n var error = new Error('Extension value not specified.');\n error.extension = e;\n throw error;\n }\n\n return e;\n}\n\n/**\n * Convert signature parameters object to ASN.1\n *\n * @param {String} oid Signature algorithm OID\n * @param params The signature parametrs object\n * @return ASN.1 object representing signature parameters\n */\nfunction _signatureParametersToAsn1(oid, params) {\n switch(oid) {\n case oids['RSASSA-PSS']:\n var parts = [];\n\n if(params.hash.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]));\n }\n\n if(params.mgf.algorithmOid !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ])\n ]));\n }\n\n if(params.saltLength !== undefined) {\n parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(params.saltLength).getBytes())\n ]));\n }\n\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);\n\n default:\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');\n }\n}\n\n/**\n * Converts a certification request's attributes to an ASN.1 set of\n * CRIAttributes.\n *\n * @param csr certification request.\n *\n * @return the ASN.1 set of CRIAttributes.\n */\nfunction _CRIAttributesToAsn1(csr) {\n // create an empty context-specific container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // no attributes, return empty container\n if(csr.attributes.length === 0) {\n return rval;\n }\n\n // each attribute has a sequence with a type and a set of values\n var attrs = csr.attributes;\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n var value = attr.value;\n\n // reuse tag class for attribute value if available\n var valueTagClass = asn1.Type.UTF8;\n if('valueTagClass' in attr) {\n valueTagClass = attr.valueTagClass;\n }\n if(valueTagClass === asn1.Type.UTF8) {\n value = forge.util.encodeUtf8(value);\n }\n var valueConstructed = false;\n if('valueConstructed' in attr) {\n valueConstructed = attr.valueConstructed;\n }\n // FIXME: handle more encodings\n\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n asn1.create(\n asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)\n ])\n ]);\n rval.value.push(seq);\n }\n\n return rval;\n}\n\nvar jan_1_1950 = new Date('1950-01-01T00:00:00Z');\nvar jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n\n/**\n * Converts a Date object to ASN.1\n * Handles the different format before and after 1st January 2050\n *\n * @param date date object.\n *\n * @return the ASN.1 object representing the date.\n */\nfunction _dateToAsn1(date) {\n if(date >= jan_1_1950 && date < jan_1_2050) {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n}\n\n/**\n * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.\n *\n * @param cert the certificate.\n *\n * @return the asn1 TBSCertificate.\n */\npki.getTBSCertificate = function(cert) {\n // TBSCertificate\n var notBefore = _dateToAsn1(cert.validity.notBefore);\n var notAfter = _dateToAsn1(cert.validity.notAfter);\n var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // integer\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(cert.version).getBytes())\n ]),\n // serialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(cert.serialNumber)),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(\n cert.siginfo.algorithmOid, cert.siginfo.parameters)\n ]),\n // issuer\n _dnToAsn1(cert.issuer),\n // validity\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n notBefore,\n notAfter\n ]),\n // subject\n _dnToAsn1(cert.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(cert.publicKey)\n ]);\n\n if(cert.issuer.uniqueId) {\n // issuerUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.issuer.uniqueId\n )\n ])\n );\n }\n if(cert.subject.uniqueId) {\n // subjectUniqueID (optional)\n tbs.value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n // TODO: support arbitrary bit length ids\n String.fromCharCode(0x00) +\n cert.subject.uniqueId\n )\n ])\n );\n }\n\n if(cert.extensions.length > 0) {\n // extensions (optional)\n tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));\n }\n\n return tbs;\n};\n\n/**\n * Gets the ASN.1 CertificationRequestInfo part of a\n * PKCS#10 CertificationRequest.\n *\n * @param csr the certification request.\n *\n * @return the asn1 CertificationRequestInfo.\n */\npki.getCertificationRequestInfo = function(csr) {\n // CertificationRequestInfo\n var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(csr.version).getBytes()),\n // subject\n _dnToAsn1(csr.subject),\n // SubjectPublicKeyInfo\n pki.publicKeyToAsn1(csr.publicKey),\n // attributes\n _CRIAttributesToAsn1(csr)\n ]);\n\n return cri;\n};\n\n/**\n * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.\n *\n * @param dn the DistinguishedName.\n *\n * @return the asn1 representation of a DistinguishedName.\n */\npki.distinguishedNameToAsn1 = function(dn) {\n return _dnToAsn1(dn);\n};\n\n/**\n * Converts an X.509v3 RSA certificate to an ASN.1 object.\n *\n * @param cert the certificate.\n *\n * @return the asn1 representation of an X.509v3 RSA certificate.\n */\npki.certificateToAsn1 = function(cert) {\n // prefer cached TBSCertificate over generating one\n var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // TBSCertificate\n tbsCertificate,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(cert.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)\n ]),\n // SignatureValue\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + cert.signature)\n ]);\n};\n\n/**\n * Converts X.509v3 certificate extensions to ASN.1.\n *\n * @param exts the extensions to convert.\n *\n * @return the extensions in ASN.1 format.\n */\npki.certificateExtensionsToAsn1 = function(exts) {\n // create top-level extension container\n var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);\n\n // create extension sequence (stores a sequence for each extension)\n var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n rval.value.push(seq);\n\n for(var i = 0; i < exts.length; ++i) {\n seq.value.push(pki.certificateExtensionToAsn1(exts[i]));\n }\n\n return rval;\n};\n\n/**\n * Converts a single certificate extension to ASN.1.\n *\n * @param ext the extension to convert.\n *\n * @return the extension in ASN.1 format.\n */\npki.certificateExtensionToAsn1 = function(ext) {\n // create a sequence for each extension\n var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);\n\n // extnID (OID)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ext.id).getBytes()));\n\n // critical defaults to false\n if(ext.critical) {\n // critical BOOLEAN DEFAULT FALSE\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,\n String.fromCharCode(0xFF)));\n }\n\n var value = ext.value;\n if(typeof ext.value !== 'string') {\n // value is asn.1\n value = asn1.toDer(value).getBytes();\n }\n\n // extnValue (OCTET STRING)\n extseq.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));\n\n return extseq;\n};\n\n/**\n * Converts a PKCS#10 certification request to an ASN.1 object.\n *\n * @param csr the certification request.\n *\n * @return the asn1 representation of a certification request.\n */\npki.certificationRequestToAsn1 = function(csr) {\n // prefer cached CertificationRequestInfo over generating one\n var cri = csr.certificationRequestInfo ||\n pki.getCertificationRequestInfo(csr);\n\n // Certificate\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // CertificationRequestInfo\n cri,\n // AlgorithmIdentifier (signature algorithm)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(csr.signatureOid).getBytes()),\n // parameters\n _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)\n ]),\n // signature\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,\n String.fromCharCode(0x00) + csr.signature)\n ]);\n};\n\n/**\n * Creates a CA store.\n *\n * @param certs an optional array of certificate objects or PEM-formatted\n * certificate strings to add to the CA store.\n *\n * @return the CA store.\n */\npki.createCaStore = function(certs) {\n // create CA store\n var caStore = {\n // stored certificates\n certs: {}\n };\n\n /**\n * Gets the certificate that issued the passed certificate or its\n * 'parent'.\n *\n * @param cert the certificate to get the parent for.\n *\n * @return the parent certificate or null if none was found.\n */\n caStore.getIssuer = function(cert) {\n var rval = getBySubject(cert.issuer);\n\n // see if there are multiple matches\n /*if(forge.util.isArray(rval)) {\n // TODO: resolve multiple matches by checking\n // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.\n // FIXME: or alternatively do authority key mapping\n // if possible (X.509v1 certs can't work?)\n throw new Error('Resolving multiple issuer matches not implemented yet.');\n }*/\n\n return rval;\n };\n\n /**\n * Adds a trusted certificate to the store.\n *\n * @param cert the certificate to add as a trusted certificate (either a\n * pki.certificate object or a PEM-formatted certificate).\n */\n caStore.addCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n ensureSubjectHasHash(cert.subject);\n\n if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store\n if(cert.subject.hash in caStore.certs) {\n // subject hash already exists, append to array\n var tmp = caStore.certs[cert.subject.hash];\n if(!forge.util.isArray(tmp)) {\n tmp = [tmp];\n }\n tmp.push(cert);\n caStore.certs[cert.subject.hash] = tmp;\n } else {\n caStore.certs[cert.subject.hash] = cert;\n }\n }\n };\n\n /**\n * Checks to see if the given certificate is in the store.\n *\n * @param cert the certificate to check (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return true if the certificate is in the store, false if not.\n */\n caStore.hasCertificate = function(cert) {\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n\n var match = getBySubject(cert.subject);\n if(!match) {\n return false;\n }\n if(!forge.util.isArray(match)) {\n match = [match];\n }\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n return true;\n }\n }\n return false;\n };\n\n /**\n * Lists all of the certificates kept in the store.\n *\n * @return an array of all of the pki.certificate objects in the store.\n */\n caStore.listAllCertificates = function() {\n var certList = [];\n\n for(var hash in caStore.certs) {\n if(caStore.certs.hasOwnProperty(hash)) {\n var value = caStore.certs[hash];\n if(!forge.util.isArray(value)) {\n certList.push(value);\n } else {\n for(var i = 0; i < value.length; ++i) {\n certList.push(value[i]);\n }\n }\n }\n }\n\n return certList;\n };\n\n /**\n * Removes a certificate from the store.\n *\n * @param cert the certificate to remove (either a pki.certificate or a\n * PEM-formatted certificate).\n *\n * @return the certificate that was removed or null if the certificate\n * wasn't in store.\n */\n caStore.removeCertificate = function(cert) {\n var result;\n\n // convert from pem if necessary\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n ensureSubjectHasHash(cert.subject);\n if(!caStore.hasCertificate(cert)) {\n return null;\n }\n\n var match = getBySubject(cert.subject);\n\n if(!forge.util.isArray(match)) {\n result = caStore.certs[cert.subject.hash];\n delete caStore.certs[cert.subject.hash];\n return result;\n }\n\n // compare DER-encoding of certificates\n var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();\n for(var i = 0; i < match.length; ++i) {\n var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();\n if(der1 === der2) {\n result = match[i];\n match.splice(i, 1);\n }\n }\n if(match.length === 0) {\n delete caStore.certs[cert.subject.hash];\n }\n\n return result;\n };\n\n function getBySubject(subject) {\n ensureSubjectHasHash(subject);\n return caStore.certs[subject.hash] || null;\n }\n\n function ensureSubjectHasHash(subject) {\n // produce subject hash if it doesn't exist\n if(!subject.hash) {\n var md = forge.md.sha1.create();\n subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);\n subject.hash = md.digest().toHex();\n }\n }\n\n // auto-add passed in certs\n if(certs) {\n // parse PEM-formatted certificates as necessary\n for(var i = 0; i < certs.length; ++i) {\n var cert = certs[i];\n caStore.addCertificate(cert);\n }\n }\n\n return caStore;\n};\n\n/**\n * Certificate verification errors, based on TLS.\n */\npki.certificateError = {\n bad_certificate: 'forge.pki.BadCertificate',\n unsupported_certificate: 'forge.pki.UnsupportedCertificate',\n certificate_revoked: 'forge.pki.CertificateRevoked',\n certificate_expired: 'forge.pki.CertificateExpired',\n certificate_unknown: 'forge.pki.CertificateUnknown',\n unknown_ca: 'forge.pki.UnknownCertificateAuthority'\n};\n\n/**\n * Verifies a certificate chain against the given Certificate Authority store\n * with an optional custom verify callback.\n *\n * @param caStore a certificate store to verify against.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end (an array of certificates).\n * @param options a callback to be called for every certificate in the chain or\n * an object with:\n * verify a callback to be called for every certificate in the\n * chain\n * validityCheckDate the date against which the certificate\n * validity period should be checked. Pass null to not check\n * the validity period. By default, the current date is used.\n *\n * The verify callback has the following signature:\n *\n * verified - Set to true if certificate was verified, otherwise the\n * pki.certificateError for why the certificate failed.\n * depth - The current index in the chain, where 0 is the end point's cert.\n * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous\n * end point.\n *\n * The function returns true on success and on failure either the appropriate\n * pki.certificateError or an object with 'error' set to the appropriate\n * pki.certificateError and 'message' set to a custom error message.\n *\n * @return true if successful, error thrown if not.\n */\npki.verifyCertificateChain = function(caStore, chain, options) {\n /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate\n Section 6: Certification Path Validation\n See inline parentheticals related to this particular implementation.\n\n The primary goal of path validation is to verify the binding between\n a subject distinguished name or a subject alternative name and subject\n public key, as represented in the end entity certificate, based on the\n public key of the trust anchor. This requires obtaining a sequence of\n certificates that support that binding. That sequence should be provided\n in the passed 'chain'. The trust anchor should be in the given CA\n store. The 'end entity' certificate is the certificate provided by the\n end point (typically a server) and is the first in the chain.\n\n To meet this goal, the path validation process verifies, among other\n things, that a prospective certification path (a sequence of n\n certificates or a 'chain') satisfies the following conditions:\n\n (a) for all x in {1, ..., n-1}, the subject of certificate x is\n the issuer of certificate x+1;\n\n (b) certificate 1 is issued by the trust anchor;\n\n (c) certificate n is the certificate to be validated; and\n\n (d) for all x in {1, ..., n}, the certificate was valid at the\n time in question.\n\n Note that here 'n' is index 0 in the chain and 1 is the last certificate\n in the chain and it must be signed by a certificate in the connection's\n CA store.\n\n The path validation process also determines the set of certificate\n policies that are valid for this path, based on the certificate policies\n extension, policy mapping extension, policy constraints extension, and\n inhibit any-policy extension.\n\n Note: Policy mapping extension not supported (Not Required).\n\n Note: If the certificate has an unsupported critical extension, then it\n must be rejected.\n\n Note: A certificate is self-issued if the DNs that appear in the subject\n and issuer fields are identical and are not empty.\n\n The path validation algorithm assumes the following seven inputs are\n provided to the path processing logic. What this specific implementation\n will use is provided parenthetically:\n\n (a) a prospective certification path of length n (the 'chain')\n (b) the current date/time: ('now').\n (c) user-initial-policy-set: A set of certificate policy identifiers\n naming the policies that are acceptable to the certificate user.\n The user-initial-policy-set contains the special value any-policy\n if the user is not concerned about certificate policy\n (Not implemented. Any policy is accepted).\n (d) trust anchor information, describing a CA that serves as a trust\n anchor for the certification path. The trust anchor information\n includes:\n\n (1) the trusted issuer name,\n (2) the trusted public key algorithm,\n (3) the trusted public key, and\n (4) optionally, the trusted public key parameters associated\n with the public key.\n\n (Trust anchors are provided via certificates in the CA store).\n\n The trust anchor information may be provided to the path processing\n procedure in the form of a self-signed certificate. The trusted anchor\n information is trusted because it was delivered to the path processing\n procedure by some trustworthy out-of-band procedure. If the trusted\n public key algorithm requires parameters, then the parameters are\n provided along with the trusted public key (No parameters used in this\n implementation).\n\n (e) initial-policy-mapping-inhibit, which indicates if policy mapping is\n allowed in the certification path.\n (Not implemented, no policy checking)\n\n (f) initial-explicit-policy, which indicates if the path must be valid\n for at least one of the certificate policies in the user-initial-\n policy-set.\n (Not implemented, no policy checking)\n\n (g) initial-any-policy-inhibit, which indicates whether the\n anyPolicy OID should be processed if it is included in a\n certificate.\n (Not implemented, so any policy is valid provided that it is\n not marked as critical) */\n\n /* Basic Path Processing:\n\n For each certificate in the 'chain', the following is checked:\n\n 1. The certificate validity period includes the current time.\n 2. The certificate was signed by its parent (where the parent is either\n the next in the chain or from the CA store). Allow processing to\n continue to the next step if no parent is found but the certificate is\n in the CA store.\n 3. TODO: The certificate has not been revoked.\n 4. The certificate issuer name matches the parent's subject name.\n 5. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is within one of the permitted subtrees of X.500 distinguished names\n and that each of the alternative names in the subjectAltName extension\n (critical or non-critical) is within one of the permitted subtrees for\n that name type.\n 6. TODO: If the certificate is self-issued and not the final certificate\n in the chain, skip this step, otherwise verify that the subject name\n is not within one of the excluded subtrees for X.500 distinguished\n names and none of the subjectAltName extension names are excluded for\n that name type.\n 7. The other steps in the algorithm for basic path processing involve\n handling the policy extension which is not presently supported in this\n implementation. Instead, if a critical policy extension is found, the\n certificate is rejected as not supported.\n 8. If the certificate is not the first or if its the only certificate in\n the chain (having no parent from the CA store or is self-signed) and it\n has a critical key usage extension, verify that the keyCertSign bit is\n set. If the key usage extension exists, verify that the basic\n constraints extension exists. If the basic constraints extension exists,\n verify that the cA flag is set. If pathLenConstraint is set, ensure that\n the number of certificates that precede in the chain (come earlier\n in the chain as implemented below), excluding the very first in the\n chain (typically the end-entity one), isn't greater than the\n pathLenConstraint. This constraint limits the number of intermediate\n CAs that may appear below a CA before only end-entity certificates\n may be issued. */\n\n // if a verify callback is passed as the third parameter, package it within\n // the options object. This is to support a legacy function signature that\n // expected the verify callback as the third parameter.\n if(typeof options === 'function') {\n options = {verify: options};\n }\n options = options || {};\n\n // copy cert chain references to another array to protect against changes\n // in verify callback\n chain = chain.slice(0);\n var certs = chain.slice(0);\n\n var validityCheckDate = options.validityCheckDate;\n // if no validityCheckDate is specified, default to the current date. Make\n // sure to maintain the value null because it indicates that the validity\n // period should not be checked.\n if(typeof validityCheckDate === 'undefined') {\n validityCheckDate = new Date();\n }\n\n // verify each cert in the chain using its parent, where the parent\n // is either the next in the chain or from the CA store\n var first = true;\n var error = null;\n var depth = 0;\n do {\n var cert = chain.shift();\n var parent = null;\n var selfSigned = false;\n\n if(validityCheckDate) {\n // 1. check valid time\n if(validityCheckDate < cert.validity.notBefore ||\n validityCheckDate > cert.validity.notAfter) {\n error = {\n message: 'Certificate is not valid yet or has expired.',\n error: pki.certificateError.certificate_expired,\n notBefore: cert.validity.notBefore,\n notAfter: cert.validity.notAfter,\n // TODO: we might want to reconsider renaming 'now' to\n // 'validityCheckDate' should this API be changed in the future.\n now: validityCheckDate\n };\n }\n }\n\n // 2. verify with parent from chain or CA store\n if(error === null) {\n parent = chain[0] || caStore.getIssuer(cert);\n if(parent === null) {\n // check for self-signed cert\n if(cert.isIssuer(cert)) {\n selfSigned = true;\n parent = cert;\n }\n }\n\n if(parent) {\n // FIXME: current CA store implementation might have multiple\n // certificates where the issuer can't be determined from the\n // certificate (happens rarely with, eg: old certificates) so normalize\n // by always putting parents into an array\n // TODO: there's may be an extreme degenerate case currently uncovered\n // where an old intermediate certificate seems to have a matching parent\n // but none of the parents actually verify ... but the intermediate\n // is in the CA and it should pass this check; needs investigation\n var parents = parent;\n if(!forge.util.isArray(parents)) {\n parents = [parents];\n }\n\n // try to verify with each possible parent (typically only one)\n var verified = false;\n while(!verified && parents.length > 0) {\n parent = parents.shift();\n try {\n verified = parent.verify(cert);\n } catch(ex) {\n // failure to verify, don't care why, try next one\n }\n }\n\n if(!verified) {\n error = {\n message: 'Certificate signature is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n\n if(error === null && (!parent || selfSigned) &&\n !caStore.hasCertificate(cert)) {\n // no parent issuer and certificate itself is not trusted\n error = {\n message: 'Certificate is not trusted.',\n error: pki.certificateError.unknown_ca\n };\n }\n }\n\n // TODO: 3. check revoked\n\n // 4. check for matching issuer/subject\n if(error === null && parent && !cert.isIssuer(parent)) {\n // parent is not issuer\n error = {\n message: 'Certificate issuer is invalid.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // 5. TODO: check names with permitted names tree\n\n // 6. TODO: check names against excluded names tree\n\n // 7. check for unsupported critical extensions\n if(error === null) {\n // supported extensions\n var se = {\n keyUsage: true,\n basicConstraints: true\n };\n for(var i = 0; error === null && i < cert.extensions.length; ++i) {\n var ext = cert.extensions[i];\n if(ext.critical && !(ext.name in se)) {\n error = {\n message:\n 'Certificate has an unsupported critical extension.',\n error: pki.certificateError.unsupported_certificate\n };\n }\n }\n }\n\n // 8. check for CA if cert is not first or is the only certificate\n // remaining in chain with no parent or is self-signed\n if(error === null &&\n (!first || (chain.length === 0 && (!parent || selfSigned)))) {\n // first check keyUsage extension and then basic constraints\n var bcExt = cert.getExtension('basicConstraints');\n var keyUsageExt = cert.getExtension('keyUsage');\n if(keyUsageExt !== null) {\n // keyCertSign must be true and there must be a basic\n // constraints extension\n if(!keyUsageExt.keyCertSign || bcExt === null) {\n // bad certificate\n error = {\n message:\n 'Certificate keyUsage or basicConstraints conflict ' +\n 'or indicate that the certificate is not a CA. ' +\n 'If the certificate is the only one in the chain or ' +\n 'isn\\'t the first then the certificate must be a ' +\n 'valid CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n // basic constraints cA flag must be set\n if(error === null && bcExt !== null && !bcExt.cA) {\n // bad certificate\n error = {\n message:\n 'Certificate basicConstraints indicates the certificate ' +\n 'is not a CA.',\n error: pki.certificateError.bad_certificate\n };\n }\n // if error is not null and keyUsage is available, then we know it\n // has keyCertSign and there is a basic constraints extension too,\n // which means we can check pathLenConstraint (if it exists)\n if(error === null && keyUsageExt !== null &&\n 'pathLenConstraint' in bcExt) {\n // pathLen is the maximum # of intermediate CA certs that can be\n // found between the current certificate and the end-entity (depth 0)\n // certificate; this number does not include the end-entity (depth 0,\n // last in the chain) even if it happens to be a CA certificate itself\n var pathLen = depth - 1;\n if(pathLen > bcExt.pathLenConstraint) {\n // pathLenConstraint violated, bad certificate\n error = {\n message:\n 'Certificate basicConstraints pathLenConstraint violated.',\n error: pki.certificateError.bad_certificate\n };\n }\n }\n }\n\n // call application callback\n var vfd = (error === null) ? true : error.error;\n var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;\n if(ret === true) {\n // clear any set error\n error = null;\n } else {\n // if passed basic tests, set default message and alert\n if(vfd === true) {\n error = {\n message: 'The application rejected the certificate.',\n error: pki.certificateError.bad_certificate\n };\n }\n\n // check for custom error info\n if(ret || ret === 0) {\n // set custom message and error\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.error) {\n error.error = ret.error;\n }\n } else if(typeof ret === 'string') {\n // set custom error\n error.error = ret;\n }\n }\n\n // throw error\n throw error;\n }\n\n // no longer first cert in chain\n first = false;\n ++depth;\n } while(chain.length > 0);\n\n return true;\n};\n","/**\n * Javascript implementation of PKCS#12.\n *\n * @author Dave Longley\n * @author Stefan Siegl \n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n * Copyright (c) 2012 Stefan Siegl \n *\n * The ASN.1 representation of PKCS#12 is as follows\n * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details)\n *\n * PFX ::= SEQUENCE {\n * version INTEGER {v3(3)}(v3,...),\n * authSafe ContentInfo,\n * macData MacData OPTIONAL\n * }\n *\n * MacData ::= SEQUENCE {\n * mac DigestInfo,\n * macSalt OCTET STRING,\n * iterations INTEGER DEFAULT 1\n * }\n * Note: The iterations default is for historical reasons and its use is\n * deprecated. A higher value, like 1024, is recommended.\n *\n * DigestInfo is defined in PKCS#7 as follows:\n *\n * DigestInfo ::= SEQUENCE {\n * digestAlgorithm DigestAlgorithmIdentifier,\n * digest Digest\n * }\n *\n * DigestAlgorithmIdentifier ::= AlgorithmIdentifier\n *\n * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters\n * for the algorithm, if any. In the case of SHA1 there is none.\n *\n * AlgorithmIdentifer ::= SEQUENCE {\n * algorithm OBJECT IDENTIFIER,\n * parameters ANY DEFINED BY algorithm OPTIONAL\n * }\n *\n * Digest ::= OCTET STRING\n *\n *\n * ContentInfo ::= SEQUENCE {\n * contentType ContentType,\n * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n * }\n *\n * ContentType ::= OBJECT IDENTIFIER\n *\n * AuthenticatedSafe ::= SEQUENCE OF ContentInfo\n * -- Data if unencrypted\n * -- EncryptedData if password-encrypted\n * -- EnvelopedData if public key-encrypted\n *\n *\n * SafeContents ::= SEQUENCE OF SafeBag\n *\n * SafeBag ::= SEQUENCE {\n * bagId BAG-TYPE.&id ({PKCS12BagSet})\n * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),\n * bagAttributes SET OF PKCS12Attribute OPTIONAL\n * }\n *\n * PKCS12Attribute ::= SEQUENCE {\n * attrId ATTRIBUTE.&id ({PKCS12AttrSet}),\n * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})\n * } -- This type is compatible with the X.500 type 'Attribute'\n *\n * PKCS12AttrSet ATTRIBUTE ::= {\n * friendlyName | -- from PKCS #9\n * localKeyId, -- from PKCS #9\n * ... -- Other attributes are allowed\n * }\n *\n * CertBag ::= SEQUENCE {\n * certId BAG-TYPE.&id ({CertTypes}),\n * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})\n * }\n *\n * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}}\n * -- DER-encoded X.509 certificate stored in OCTET STRING\n *\n * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}}\n * -- Base64-encoded SDSI certificate stored in IA5String\n *\n * CertTypes BAG-TYPE ::= {\n * x509Certificate |\n * sdsiCertificate,\n * ... -- For future extensions\n * }\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./oids');\nrequire('./pkcs7asn1');\nrequire('./pbe');\nrequire('./random');\nrequire('./rsa');\nrequire('./sha1');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 & PKI API\nvar asn1 = forge.asn1;\nvar pki = forge.pki;\n\n// shortcut for PKCS#12 API\nvar p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {};\n\nvar contentInfoValidator = {\n name: 'ContentInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // a ContentInfo\n constructed: true,\n value: [{\n name: 'ContentInfo.contentType',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'contentType'\n }, {\n name: 'ContentInfo.content',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'content'\n }]\n};\n\nvar pfxValidator = {\n name: 'PFX',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'PFX.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'version'\n },\n contentInfoValidator, {\n name: 'PFX.macData',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'mac',\n value: [{\n name: 'PFX.macData.mac',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestInfo\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier\n constructed: true,\n value: [{\n name: 'PFX.macData.mac.digestAlgorithm.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'macAlgorithm'\n }, {\n name: 'PFX.macData.mac.digestAlgorithm.parameters',\n tagClass: asn1.Class.UNIVERSAL,\n captureAsn1: 'macAlgorithmParameters'\n }]\n }, {\n name: 'PFX.macData.mac.digest',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macDigest'\n }]\n }, {\n name: 'PFX.macData.macSalt',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'macSalt'\n }, {\n name: 'PFX.macData.iterations',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n optional: true,\n capture: 'macIterations'\n }]\n }]\n};\n\nvar safeBagValidator = {\n name: 'SafeBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'SafeBag.bagId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'bagId'\n }, {\n name: 'SafeBag.bagValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n captureAsn1: 'bagValue'\n }, {\n name: 'SafeBag.bagAttributes',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n optional: true,\n capture: 'bagAttributes'\n }]\n};\n\nvar attributeValidator = {\n name: 'Attribute',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'Attribute.attrId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'oid'\n }, {\n name: 'Attribute.attrValues',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SET,\n constructed: true,\n capture: 'values'\n }]\n};\n\nvar certBagValidator = {\n name: 'CertBag',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'CertBag.certId',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'certId'\n }, {\n name: 'CertBag.certValue',\n tagClass: asn1.Class.CONTEXT_SPECIFIC,\n constructed: true,\n /* So far we only support X.509 certificates (which are wrapped in\n an OCTET STRING, hence hard code that here). */\n value: [{\n name: 'CertBag.certValue[0]',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Class.OCTETSTRING,\n constructed: false,\n capture: 'cert'\n }]\n }]\n};\n\n/**\n * Search SafeContents structure for bags with matching attributes.\n *\n * The search can optionally be narrowed by a certain bag type.\n *\n * @param safeContents the SafeContents structure to search in.\n * @param attrName the name of the attribute to compare against.\n * @param attrValue the attribute value to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of matching bags.\n */\nfunction _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {\n var result = [];\n\n for(var i = 0; i < safeContents.length; i++) {\n for(var j = 0; j < safeContents[i].safeBags.length; j++) {\n var bag = safeContents[i].safeBags[j];\n if(bagType !== undefined && bag.type !== bagType) {\n continue;\n }\n // only filter by bag type, no attribute specified\n if(attrName === null) {\n result.push(bag);\n continue;\n }\n if(bag.attributes[attrName] !== undefined &&\n bag.attributes[attrName].indexOf(attrValue) >= 0) {\n result.push(bag);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object.\n *\n * @param obj The PKCS#12 PFX in ASN.1 notation.\n * @param strict true to use strict DER decoding, false not to (default: true).\n * @param {String} password Password to decrypt with (optional).\n *\n * @return PKCS#12 PFX object.\n */\np12.pkcs12FromAsn1 = function(obj, strict, password) {\n // handle args\n if(typeof strict === 'string') {\n password = strict;\n strict = true;\n } else if(strict === undefined) {\n strict = true;\n }\n\n // validate PFX and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, pfxValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 PFX. ' +\n 'ASN.1 object is not an PKCS#12 PFX.');\n error.errors = error;\n throw error;\n }\n\n var pfx = {\n version: capture.version.charCodeAt(0),\n safeContents: [],\n\n /**\n * Gets bags with matching attributes.\n *\n * @param filter the attributes to filter by:\n * [localKeyId] the localKeyId to search for.\n * [localKeyIdHex] the localKeyId in hex to search for.\n * [friendlyName] the friendly name to search for.\n * [bagType] bag type to narrow each attribute search by.\n *\n * @return a map of attribute type to an array of matching bags or, if no\n * attribute was given but a bag type, the map key will be the\n * bag type.\n */\n getBags: function(filter) {\n var rval = {};\n\n var localKeyId;\n if('localKeyId' in filter) {\n localKeyId = filter.localKeyId;\n } else if('localKeyIdHex' in filter) {\n localKeyId = forge.util.hexToBytes(filter.localKeyIdHex);\n }\n\n // filter on bagType only\n if(localKeyId === undefined && !('friendlyName' in filter) &&\n 'bagType' in filter) {\n rval[filter.bagType] = _getBagsByAttribute(\n pfx.safeContents, null, null, filter.bagType);\n }\n\n if(localKeyId !== undefined) {\n rval.localKeyId = _getBagsByAttribute(\n pfx.safeContents, 'localKeyId',\n localKeyId, filter.bagType);\n }\n if('friendlyName' in filter) {\n rval.friendlyName = _getBagsByAttribute(\n pfx.safeContents, 'friendlyName',\n filter.friendlyName, filter.bagType);\n }\n\n return rval;\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching friendlyName attribute.\n *\n * @param friendlyName the friendly name to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching friendlyName attribute.\n */\n getBagsByFriendlyName: function(friendlyName, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'friendlyName', friendlyName, bagType);\n },\n\n /**\n * DEPRECATED: use getBags() instead.\n *\n * Get bags with matching localKeyId attribute.\n *\n * @param localKeyId the localKeyId to search for.\n * @param [bagType] bag type to narrow search by.\n *\n * @return an array of bags with matching localKeyId attribute.\n */\n getBagsByLocalKeyId: function(localKeyId, bagType) {\n return _getBagsByAttribute(\n pfx.safeContents, 'localKeyId', localKeyId, bagType);\n }\n };\n\n if(capture.version.charCodeAt(0) !== 3) {\n var error = new Error('PKCS#12 PFX of version other than 3 not supported.');\n error.version = capture.version.charCodeAt(0);\n throw error;\n }\n\n if(asn1.derToOid(capture.contentType) !== pki.oids.data) {\n var error = new Error('Only PKCS#12 PFX in password integrity mode supported.');\n error.oid = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n var data = capture.content.value[0];\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.');\n }\n data = _decodePkcs7Data(data);\n\n // check for MAC\n if(capture.mac) {\n var md = null;\n var macKeyBytes = 0;\n var macAlgorithm = asn1.derToOid(capture.macAlgorithm);\n switch(macAlgorithm) {\n case pki.oids.sha1:\n md = forge.md.sha1.create();\n macKeyBytes = 20;\n break;\n case pki.oids.sha256:\n md = forge.md.sha256.create();\n macKeyBytes = 32;\n break;\n case pki.oids.sha384:\n md = forge.md.sha384.create();\n macKeyBytes = 48;\n break;\n case pki.oids.sha512:\n md = forge.md.sha512.create();\n macKeyBytes = 64;\n break;\n case pki.oids.md5:\n md = forge.md.md5.create();\n macKeyBytes = 16;\n break;\n }\n if(md === null) {\n throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm);\n }\n\n // verify MAC (iterations default to 1)\n var macSalt = new forge.util.ByteBuffer(capture.macSalt);\n var macIterations = (('macIterations' in capture) ?\n parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1);\n var macKey = p12.generateKey(\n password, macSalt, 3, macIterations, macKeyBytes, md);\n var mac = forge.hmac.create();\n mac.start(md, macKey);\n mac.update(data.value);\n var macValue = mac.getMac();\n if(macValue.getBytes() !== capture.macDigest) {\n throw new Error('PKCS#12 MAC could not be verified. Invalid password?');\n }\n }\n\n _decodeAuthenticatedSafe(pfx, data.value, strict, password);\n return pfx;\n};\n\n/**\n * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines \"Data\" as an OCTET STRING,\n * but it is sometimes an OCTET STRING that is composed/constructed of chunks,\n * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This\n * function transforms this corner-case into the usual simple,\n * non-composed/constructed OCTET STRING.\n *\n * This function may be moved to ASN.1 at some point to better deal with\n * more BER-encoding issues, should they arise.\n *\n * @param data the ASN.1 Data object to transform.\n */\nfunction _decodePkcs7Data(data) {\n // handle special case of \"chunked\" data content: an octet string composed\n // of other octet strings\n if(data.composed || data.constructed) {\n var value = forge.util.createBuffer();\n for(var i = 0; i < data.value.length; ++i) {\n value.putBytes(data.value[i].value);\n }\n data.composed = data.constructed = false;\n data.value = value.getBytes();\n }\n return data;\n}\n\n/**\n * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object.\n *\n * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo.\n *\n * @param pfx The PKCS#12 PFX object to fill.\n * @param {String} authSafe BER-encoded AuthenticatedSafe.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n */\nfunction _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {\n authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */\n\n if(authSafe.tagClass !== asn1.Class.UNIVERSAL ||\n authSafe.type !== asn1.Type.SEQUENCE ||\n authSafe.constructed !== true) {\n throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' +\n 'SEQUENCE OF ContentInfo');\n }\n\n for(var i = 0; i < authSafe.value.length; i++) {\n var contentInfo = authSafe.value[i];\n\n // validate contentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var obj = {\n encrypted: false\n };\n var safeContents = null;\n var data = capture.content.value[0];\n switch(asn1.derToOid(capture.contentType)) {\n case pki.oids.data:\n if(data.tagClass !== asn1.Class.UNIVERSAL ||\n data.type !== asn1.Type.OCTETSTRING) {\n throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.');\n }\n safeContents = _decodePkcs7Data(data).value;\n break;\n case pki.oids.encryptedData:\n safeContents = _decryptSafeContents(data, password);\n obj.encrypted = true;\n break;\n default:\n var error = new Error('Unsupported PKCS#12 contentType.');\n error.contentType = asn1.derToOid(capture.contentType);\n throw error;\n }\n\n obj.safeBags = _decodeSafeContents(safeContents, strict, password);\n pfx.safeContents.push(obj);\n }\n}\n\n/**\n * Decrypt PKCS#7 EncryptedData structure.\n *\n * @param data ASN.1 encoded EncryptedContentInfo object.\n * @param password The user-provided password.\n *\n * @return The decrypted SafeContents (ASN.1 object).\n */\nfunction _decryptSafeContents(data, password) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(\n data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) {\n var error = new Error('Cannot read EncryptedContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.contentType);\n if(oid !== pki.oids.data) {\n var error = new Error(\n 'PKCS#12 EncryptedContentInfo ContentType is not Data.');\n error.oid = oid;\n throw error;\n }\n\n // get cipher\n oid = asn1.derToOid(capture.encAlgorithm);\n var cipher = pki.pbe.getCipher(oid, capture.encParameter, password);\n\n // get encrypted data\n var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);\n var encrypted = forge.util.createBuffer(encryptedContentAsn1.value);\n\n cipher.update(encrypted);\n if(!cipher.finish()) {\n throw new Error('Failed to decrypt PKCS#12 SafeContents.');\n }\n\n return cipher.output.getBytes();\n}\n\n/**\n * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects.\n *\n * The safeContents is a BER-encoded SEQUENCE OF SafeBag.\n *\n * @param {String} safeContents BER-encoded safeContents.\n * @param strict true to use strict DER decoding, false not to.\n * @param {String} password Password to decrypt with (optional).\n *\n * @return {Array} Array of Bag objects.\n */\nfunction _decodeSafeContents(safeContents, strict, password) {\n // if strict and no safe contents, return empty safes\n if(!strict && safeContents.length === 0) {\n return [];\n }\n\n // actually it's BER-encoded\n safeContents = asn1.fromDer(safeContents, strict);\n\n if(safeContents.tagClass !== asn1.Class.UNIVERSAL ||\n safeContents.type !== asn1.Type.SEQUENCE ||\n safeContents.constructed !== true) {\n throw new Error(\n 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.');\n }\n\n var res = [];\n for(var i = 0; i < safeContents.value.length; i++) {\n var safeBag = safeContents.value[i];\n\n // validate SafeBag and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) {\n var error = new Error('Cannot read SafeBag.');\n error.errors = errors;\n throw error;\n }\n\n /* Create bag object and push to result array. */\n var bag = {\n type: asn1.derToOid(capture.bagId),\n attributes: _decodeBagAttributes(capture.bagAttributes)\n };\n res.push(bag);\n\n var validator, decoder;\n var bagAsn1 = capture.bagValue.value[0];\n switch(bag.type) {\n case pki.oids.pkcs8ShroudedKeyBag:\n /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt.\n Afterwards we can handle it like a keyBag,\n which is a PrivateKeyInfo. */\n bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password);\n if(bagAsn1 === null) {\n throw new Error(\n 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?');\n }\n\n /* fall through */\n case pki.oids.keyBag:\n /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our\n PKI module, hence we don't have to do validation/capturing here,\n just pass what we already got. */\n try {\n bag.key = pki.privateKeyFromAsn1(bagAsn1);\n } catch(e) {\n // ignore unknown key type, pass asn1 value\n bag.key = null;\n bag.asn1 = bagAsn1;\n }\n continue; /* Nothing more to do. */\n\n case pki.oids.certBag:\n /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates.\n Therefore put the SafeBag content through another validator to\n capture the fields. Afterwards check & store the results. */\n validator = certBagValidator;\n decoder = function() {\n if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) {\n var error = new Error(\n 'Unsupported certificate type, only X.509 supported.');\n error.oid = asn1.derToOid(capture.certId);\n throw error;\n }\n\n // true=produce cert hash\n var certAsn1 = asn1.fromDer(capture.cert, strict);\n try {\n bag.cert = pki.certificateFromAsn1(certAsn1, true);\n } catch(e) {\n // ignore unknown cert type, pass asn1 value\n bag.cert = null;\n bag.asn1 = certAsn1;\n }\n };\n break;\n\n default:\n var error = new Error('Unsupported PKCS#12 SafeBag type.');\n error.oid = bag.type;\n throw error;\n }\n\n /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */\n if(validator !== undefined &&\n !asn1.validate(bagAsn1, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 ' + validator.name);\n error.errors = errors;\n throw error;\n }\n\n /* Call decoder function from above to store the results. */\n decoder();\n }\n\n return res;\n}\n\n/**\n * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object.\n *\n * @param attributes SET OF PKCS12Attribute (ASN.1 object).\n *\n * @return the decoded attributes.\n */\nfunction _decodeBagAttributes(attributes) {\n var decodedAttrs = {};\n\n if(attributes !== undefined) {\n for(var i = 0; i < attributes.length; ++i) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#12 BagAttribute.');\n error.errors = errors;\n throw error;\n }\n\n var oid = asn1.derToOid(capture.oid);\n if(pki.oids[oid] === undefined) {\n // unsupported attribute type, ignore.\n continue;\n }\n\n decodedAttrs[pki.oids[oid]] = [];\n for(var j = 0; j < capture.values.length; ++j) {\n decodedAttrs[pki.oids[oid]].push(capture.values[j].value);\n }\n }\n }\n\n return decodedAttrs;\n}\n\n/**\n * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a\n * password is provided then the private key will be encrypted.\n *\n * An entire certificate chain may also be included. To do this, pass\n * an array for the \"cert\" parameter where the first certificate is\n * the one that is paired with the private key and each subsequent one\n * verifies the previous one. The certificates may be in PEM format or\n * have been already parsed by Forge.\n *\n * @todo implement password-based-encryption for the whole package\n *\n * @param key the private key.\n * @param cert the certificate (may be an array of certificates in order\n * to specify a certificate chain).\n * @param password the password to use, null for none.\n * @param options:\n * algorithm the encryption algorithm to use\n * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.\n * count the iteration count to use.\n * saltSize the salt size to use.\n * useMac true to include a MAC, false not to, defaults to true.\n * localKeyId the local key ID to use, in hex.\n * friendlyName the friendly name to use.\n * generateLocalKeyId true to generate a random local key ID,\n * false not to, defaults to true.\n *\n * @return the PKCS#12 PFX ASN.1 object.\n */\np12.toPkcs12Asn1 = function(key, cert, password, options) {\n // set default options\n options = options || {};\n options.saltSize = options.saltSize || 8;\n options.count = options.count || 2048;\n options.algorithm = options.algorithm || options.encAlgorithm || 'aes128';\n if(!('useMac' in options)) {\n options.useMac = true;\n }\n if(!('localKeyId' in options)) {\n options.localKeyId = null;\n }\n if(!('generateLocalKeyId' in options)) {\n options.generateLocalKeyId = true;\n }\n\n var localKeyId = options.localKeyId;\n var bagAttrs;\n if(localKeyId !== null) {\n localKeyId = forge.util.hexToBytes(localKeyId);\n } else if(options.generateLocalKeyId) {\n // use SHA-1 of paired cert, if available\n if(cert) {\n var pairedCert = forge.util.isArray(cert) ? cert[0] : cert;\n if(typeof pairedCert === 'string') {\n pairedCert = pki.certificateFromPem(pairedCert);\n }\n var sha1 = forge.md.sha1.create();\n sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());\n localKeyId = sha1.digest().getBytes();\n } else {\n // FIXME: consider using SHA-1 of public key (which can be generated\n // from private key components), see: cert.generateSubjectKeyIdentifier\n // generate random bytes\n localKeyId = forge.random.getBytes(20);\n }\n }\n\n var attrs = [];\n if(localKeyId !== null) {\n attrs.push(\n // localKeyID\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.localKeyId).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n localKeyId)\n ])\n ]));\n }\n if('friendlyName' in options) {\n attrs.push(\n // friendlyName\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // attrId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.friendlyName).getBytes()),\n // attrValues\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false,\n options.friendlyName)\n ])\n ]));\n }\n\n if(attrs.length > 0) {\n bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs);\n }\n\n // collect contents for AuthenticatedSafe\n var contents = [];\n\n // create safe bag(s) for certificate chain\n var chain = [];\n if(cert !== null) {\n if(forge.util.isArray(cert)) {\n chain = cert;\n } else {\n chain = [cert];\n }\n }\n\n var certSafeBags = [];\n for(var i = 0; i < chain.length; ++i) {\n // convert cert from PEM as necessary\n cert = chain[i];\n if(typeof cert === 'string') {\n cert = pki.certificateFromPem(cert);\n }\n\n // SafeBag\n var certBagAttrs = (i === 0) ? bagAttrs : undefined;\n var certAsn1 = pki.certificateToAsn1(cert);\n var certSafeBag =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.certBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // CertBag\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // certId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.x509Certificate).getBytes()),\n // certValue (x509Certificate)\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certAsn1).getBytes())\n ])])]),\n // bagAttributes (OPTIONAL)\n certBagAttrs\n ]);\n certSafeBags.push(certSafeBag);\n }\n\n if(certSafeBags.length > 0) {\n // SafeContents\n var certSafeContents = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags);\n\n // ContentInfo\n var certCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(certSafeContents).getBytes())\n ])\n ]);\n contents.push(certCI);\n }\n\n // create safe contents for private key\n var keyBag = null;\n if(key !== null) {\n // SafeBag\n var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));\n if(password === null) {\n // no encryption\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.keyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // PrivateKeyInfo\n pkAsn1\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n } else {\n // encrypted PrivateKeyInfo\n keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // bagId\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),\n // bagValue\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n // EncryptedPrivateKeyInfo\n pki.encryptPrivateKeyInfo(pkAsn1, password, options)\n ]),\n // bagAttributes (OPTIONAL)\n bagAttrs\n ]);\n }\n\n // SafeContents\n var keySafeContents =\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]);\n\n // ContentInfo\n var keyCI =\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(keySafeContents).getBytes())\n ])\n ]);\n contents.push(keyCI);\n }\n\n // create AuthenticatedSafe by stringing together the contents\n var safe = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents);\n\n var macData;\n if(options.useMac) {\n // MacData\n var sha1 = forge.md.sha1.create();\n var macSalt = new forge.util.ByteBuffer(\n forge.random.getBytes(options.saltSize));\n var count = options.count;\n // 160-bit key\n var key = p12.generateKey(password, macSalt, 3, count, 20);\n var mac = forge.hmac.create();\n mac.start(sha1, key);\n mac.update(asn1.toDer(safe).getBytes());\n var macValue = mac.getMac();\n macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // mac DigestInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm = SHA-1\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(pki.oids.sha1).getBytes()),\n // parameters = Null\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // digest\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,\n false, macValue.getBytes())\n ]),\n // macSalt OCTET STRING\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()),\n // iterations INTEGER (XXX: Only support count < 65536)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(count).getBytes()\n )\n ]);\n }\n\n // PFX\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version (3)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(3).getBytes()),\n // PKCS#7 ContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // contentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n // OID for the content type is 'data'\n asn1.oidToDer(pki.oids.data).getBytes()),\n // content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n asn1.toDer(safe).getBytes())\n ])\n ]),\n macData\n ]);\n};\n\n/**\n * Derives a PKCS#12 key.\n *\n * @param password the password to derive the key material from, null or\n * undefined for none.\n * @param salt the salt, as a ByteBuffer, to use.\n * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).\n * @param iter the iteration count.\n * @param n the number of bytes to derive from the password.\n * @param md the message digest to use, defaults to SHA-1.\n *\n * @return a ByteBuffer with the bytes derived from the password.\n */\np12.generateKey = forge.pbe.generatePkcs12Key;\n","/**\n * Javascript implementation of a basic Public Key Infrastructure, including\n * support for RSA public and private keys.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./oids');\nrequire('./pbe');\nrequire('./pem');\nrequire('./pbkdf2');\nrequire('./pkcs12');\nrequire('./pss');\nrequire('./rsa');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for asn.1 API\nvar asn1 = forge.asn1;\n\n/* Public Key Infrastructure (PKI) implementation. */\nvar pki = module.exports = forge.pki = forge.pki || {};\n\n/**\n * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead.\n *\n * Converts PEM-formatted data to DER.\n *\n * @param pem the PEM-formatted data.\n *\n * @return the DER-formatted data.\n */\npki.pemToDer = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PEM to DER; PEM is encrypted.');\n }\n return forge.util.createBuffer(msg.body);\n};\n\n/**\n * Converts an RSA private key from PEM format.\n *\n * @param pem the PEM-formatted private key.\n *\n * @return the private key.\n */\npki.privateKeyFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') {\n var error = new Error('Could not convert private key from PEM; PEM ' +\n 'header type is not \"PRIVATE KEY\" or \"RSA PRIVATE KEY\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert private key from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return pki.privateKeyFromAsn1(obj);\n};\n\n/**\n * Converts an RSA private key to PEM format.\n *\n * @param key the private key.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyToPem = function(key, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var msg = {\n type: 'RSA PRIVATE KEY',\n body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n\n/**\n * Converts a PrivateKeyInfo to PEM format.\n *\n * @param pki the PrivateKeyInfo.\n * @param maxline the maximum characters per line, defaults to 64.\n *\n * @return the PEM-formatted private key.\n */\npki.privateKeyInfoToPem = function(pki, maxline) {\n // convert to DER, then PEM-encode\n var msg = {\n type: 'PRIVATE KEY',\n body: asn1.toDer(pki).getBytes()\n };\n return forge.pem.encode(msg, {maxline: maxline});\n};\n","/**\n * A Javascript implementation of Transport Layer Security (TLS).\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2014 Digital Bazaar, Inc.\n *\n * The TLS Handshake Protocol involves the following steps:\n *\n * - Exchange hello messages to agree on algorithms, exchange random values,\n * and check for session resumption.\n *\n * - Exchange the necessary cryptographic parameters to allow the client and\n * server to agree on a premaster secret.\n *\n * - Exchange certificates and cryptographic information to allow the client\n * and server to authenticate themselves.\n *\n * - Generate a master secret from the premaster secret and exchanged random\n * values.\n *\n * - Provide security parameters to the record layer.\n *\n * - Allow the client and server to verify that their peer has calculated the\n * same security parameters and that the handshake occurred without tampering\n * by an attacker.\n *\n * Up to 4 different messages may be sent during a key exchange. The server\n * certificate, the server key exchange, the client certificate, and the\n * client key exchange.\n *\n * A typical handshake (from the client's perspective).\n *\n * 1. Client sends ClientHello.\n * 2. Client receives ServerHello.\n * 3. Client receives optional Certificate.\n * 4. Client receives optional ServerKeyExchange.\n * 5. Client receives ServerHelloDone.\n * 6. Client sends optional Certificate.\n * 7. Client sends ClientKeyExchange.\n * 8. Client sends optional CertificateVerify.\n * 9. Client sends ChangeCipherSpec.\n * 10. Client sends Finished.\n * 11. Client receives ChangeCipherSpec.\n * 12. Client receives Finished.\n * 13. Client sends/receives application data.\n *\n * To reuse an existing session:\n *\n * 1. Client sends ClientHello with session ID for reuse.\n * 2. Client receives ServerHello with same session ID if reusing.\n * 3. Client receives ChangeCipherSpec message if reusing.\n * 4. Client receives Finished.\n * 5. Client sends ChangeCipherSpec.\n * 6. Client sends Finished.\n *\n * Note: Client ignores HelloRequest if in the middle of a handshake.\n *\n * Record Layer:\n *\n * The record layer fragments information blocks into TLSPlaintext records\n * carrying data in chunks of 2^14 bytes or less. Client message boundaries are\n * not preserved in the record layer (i.e., multiple client messages of the\n * same ContentType MAY be coalesced into a single TLSPlaintext record, or a\n * single message MAY be fragmented across several records).\n *\n * struct {\n * uint8 major;\n * uint8 minor;\n * } ProtocolVersion;\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * opaque fragment[TLSPlaintext.length];\n * } TLSPlaintext;\n *\n * type:\n * The higher-level protocol used to process the enclosed fragment.\n *\n * version:\n * The version of the protocol being employed. TLS Version 1.2 uses version\n * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that\n * supports multiple versions of TLS may not know what version will be\n * employed before it receives the ServerHello.\n *\n * length:\n * The length (in bytes) of the following TLSPlaintext.fragment. The length\n * MUST NOT exceed 2^14 = 16384 bytes.\n *\n * fragment:\n * The application data. This data is transparent and treated as an\n * independent block to be dealt with by the higher-level protocol specified\n * by the type field.\n *\n * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or\n * ChangeCipherSpec content types. Zero-length fragments of Application data\n * MAY be sent as they are potentially useful as a traffic analysis\n * countermeasure.\n *\n * Note: Data of different TLS record layer content types MAY be interleaved.\n * Application data is generally of lower precedence for transmission than\n * other content types. However, records MUST be delivered to the network in\n * the same order as they are protected by the record layer. Recipients MUST\n * receive and process interleaved application layer traffic during handshakes\n * subsequent to the first one on a connection.\n *\n * struct {\n * ContentType type; // same as TLSPlaintext.type\n * ProtocolVersion version;// same as TLSPlaintext.version\n * uint16 length;\n * opaque fragment[TLSCompressed.length];\n * } TLSCompressed;\n *\n * length:\n * The length (in bytes) of the following TLSCompressed.fragment.\n * The length MUST NOT exceed 2^14 + 1024.\n *\n * fragment:\n * The compressed form of TLSPlaintext.fragment.\n *\n * Note: A CompressionMethod.null operation is an identity operation; no fields\n * are altered. In this implementation, since no compression is supported,\n * uncompressed records are always the same as compressed records.\n *\n * Encryption Information:\n *\n * The encryption and MAC functions translate a TLSCompressed structure into a\n * TLSCiphertext. The decryption functions reverse the process. The MAC of the\n * record also includes a sequence number so that missing, extra, or repeated\n * messages are detectable.\n *\n * struct {\n * ContentType type;\n * ProtocolVersion version;\n * uint16 length;\n * select (SecurityParameters.cipher_type) {\n * case stream: GenericStreamCipher;\n * case block: GenericBlockCipher;\n * case aead: GenericAEADCipher;\n * } fragment;\n * } TLSCiphertext;\n *\n * type:\n * The type field is identical to TLSCompressed.type.\n *\n * version:\n * The version field is identical to TLSCompressed.version.\n *\n * length:\n * The length (in bytes) of the following TLSCiphertext.fragment.\n * The length MUST NOT exceed 2^14 + 2048.\n *\n * fragment:\n * The encrypted form of TLSCompressed.fragment, with the MAC.\n *\n * Note: Only CBC Block Ciphers are supported by this implementation.\n *\n * The TLSCompressed.fragment structures are converted to/from block\n * TLSCiphertext.fragment structures.\n *\n * struct {\n * opaque IV[SecurityParameters.record_iv_length];\n * block-ciphered struct {\n * opaque content[TLSCompressed.length];\n * opaque MAC[SecurityParameters.mac_length];\n * uint8 padding[GenericBlockCipher.padding_length];\n * uint8 padding_length;\n * };\n * } GenericBlockCipher;\n *\n * The MAC is generated as described in Section 6.2.3.1.\n *\n * IV:\n * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be\n * unpredictable. Note that in versions of TLS prior to 1.1, there was no\n * IV field, and the last ciphertext block of the previous record (the \"CBC\n * residue\") was used as the IV. This was changed to prevent the attacks\n * described in [CBCATT]. For block ciphers, the IV length is of length\n * SecurityParameters.record_iv_length, which is equal to the\n * SecurityParameters.block_size.\n *\n * padding:\n * Padding that is added to force the length of the plaintext to be an\n * integral multiple of the block cipher's block length. The padding MAY be\n * any length up to 255 bytes, as long as it results in the\n * TLSCiphertext.length being an integral multiple of the block length.\n * Lengths longer than necessary might be desirable to frustrate attacks on\n * a protocol that are based on analysis of the lengths of exchanged\n * messages. Each uint8 in the padding data vector MUST be filled with the\n * padding length value. The receiver MUST check this padding and MUST use\n * the bad_record_mac alert to indicate padding errors.\n *\n * padding_length:\n * The padding length MUST be such that the total size of the\n * GenericBlockCipher structure is a multiple of the cipher's block length.\n * Legal values range from zero to 255, inclusive. This length specifies the\n * length of the padding field exclusive of the padding_length field itself.\n *\n * The encrypted data length (TLSCiphertext.length) is one more than the sum of\n * SecurityParameters.block_length, TLSCompressed.length,\n * SecurityParameters.mac_length, and padding_length.\n *\n * Example: If the block length is 8 bytes, the content length\n * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the\n * length before padding is 82 bytes (this does not include the IV. Thus, the\n * padding length modulo 8 must be equal to 6 in order to make the total length\n * an even multiple of 8 bytes (the block length). The padding length can be\n * 6, 14, 22, and so on, through 254. If the padding length were the minimum\n * necessary, 6, the padding would be 6 bytes, each containing the value 6.\n * Thus, the last 8 octets of the GenericBlockCipher before block encryption\n * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC.\n *\n * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical\n * that the entire plaintext of the record be known before any ciphertext is\n * transmitted. Otherwise, it is possible for the attacker to mount the attack\n * described in [CBCATT].\n *\n * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing\n * attack on CBC padding based on the time required to compute the MAC. In\n * order to defend against this attack, implementations MUST ensure that\n * record processing time is essentially the same whether or not the padding\n * is correct. In general, the best way to do this is to compute the MAC even\n * if the padding is incorrect, and only then reject the packet. For instance,\n * if the pad appears to be incorrect, the implementation might assume a\n * zero-length pad and then compute the MAC. This leaves a small timing\n * channel, since MAC performance depends, to some extent, on the size of the\n * data fragment, but it is not believed to be large enough to be exploitable,\n * due to the large block size of existing MACs and the small size of the\n * timing signal.\n */\nvar forge = require('./forge');\nrequire('./asn1');\nrequire('./hmac');\nrequire('./md5');\nrequire('./pem');\nrequire('./pki');\nrequire('./random');\nrequire('./sha1');\nrequire('./util');\n\n/**\n * Generates pseudo random bytes by mixing the result of two hash functions,\n * MD5 and SHA-1.\n *\n * prf_TLS1(secret, label, seed) =\n * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);\n *\n * Each P_hash function functions as follows:\n *\n * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +\n * HMAC_hash(secret, A(2) + seed) +\n * HMAC_hash(secret, A(3) + seed) + ...\n * A() is defined as:\n * A(0) = seed\n * A(i) = HMAC_hash(secret, A(i-1))\n *\n * The '+' operator denotes concatenation.\n *\n * As many iterations A(N) as are needed are performed to generate enough\n * pseudo random byte output. If an iteration creates more data than is\n * necessary, then it is truncated.\n *\n * Therefore:\n * A(1) = HMAC_hash(secret, A(0))\n * = HMAC_hash(secret, seed)\n * A(2) = HMAC_hash(secret, A(1))\n * = HMAC_hash(secret, HMAC_hash(secret, seed))\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) +\n * ...\n *\n * Therefore:\n * P_hash(secret, seed) =\n * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) +\n * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) +\n * ...\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_TLS1 = function(secret, label, seed, length) {\n var rval = forge.util.createBuffer();\n\n /* For TLS 1.0, the secret is split in half, into two secrets of equal\n length. If the secret has an odd length then the last byte of the first\n half will be the same as the first byte of the second. The length of the\n two secrets is half of the secret rounded up. */\n var idx = (secret.length >> 1);\n var slen = idx + (secret.length & 1);\n var s1 = secret.substr(0, slen);\n var s2 = secret.substr(idx, slen);\n var ai = forge.util.createBuffer();\n var hmac = forge.hmac.create();\n seed = label + seed;\n\n // determine the number of iterations that must be performed to generate\n // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20\n var md5itr = Math.ceil(length / 16);\n var sha1itr = Math.ceil(length / 20);\n\n // do md5 iterations\n hmac.start('MD5', s1);\n var md5bytes = forge.util.createBuffer();\n ai.putBytes(seed);\n for(var i = 0; i < md5itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n md5bytes.putBuffer(hmac.digest());\n }\n\n // do sha1 iterations\n hmac.start('SHA1', s2);\n var sha1bytes = forge.util.createBuffer();\n ai.clear();\n ai.putBytes(seed);\n for(var i = 0; i < sha1itr; ++i) {\n // HMAC_hash(secret, A(i-1))\n hmac.start(null, null);\n hmac.update(ai.getBytes());\n ai.putBuffer(hmac.digest());\n\n // HMAC_hash(secret, A(i) + seed)\n hmac.start(null, null);\n hmac.update(ai.bytes() + seed);\n sha1bytes.putBuffer(hmac.digest());\n }\n\n // XOR the md5 bytes with the sha1 bytes\n rval.putBytes(forge.util.xorBytes(\n md5bytes.getBytes(), sha1bytes.getBytes(), length));\n\n return rval;\n};\n\n/**\n * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2.\n *\n * @param secret the secret to use.\n * @param label the label to use.\n * @param seed the seed value to use.\n * @param length the number of bytes to generate.\n *\n * @return the pseudo random bytes in a byte buffer.\n */\nvar prf_sha256 = function(secret, label, seed, length) {\n // FIXME: implement me for TLS 1.2\n};\n\n/**\n * Gets a MAC for a record using the SHA-1 hash algorithm.\n *\n * @param key the mac key.\n * @param state the sequence number (array of two 32-bit integers).\n * @param record the record.\n *\n * @return the sha-1 hash (20 bytes) for the given record.\n */\nvar hmac_sha1 = function(key, seqNum, record) {\n /* MAC is computed like so:\n HMAC_hash(\n key, seqNum +\n TLSCompressed.type +\n TLSCompressed.version +\n TLSCompressed.length +\n TLSCompressed.fragment)\n */\n var hmac = forge.hmac.create();\n hmac.start('SHA1', key);\n var b = forge.util.createBuffer();\n b.putInt32(seqNum[0]);\n b.putInt32(seqNum[1]);\n b.putByte(record.type);\n b.putByte(record.version.major);\n b.putByte(record.version.minor);\n b.putInt16(record.length);\n b.putBytes(record.fragment.bytes());\n hmac.update(b.getBytes());\n return hmac.digest().getBytes();\n};\n\n/**\n * Compresses the TLSPlaintext record into a TLSCompressed record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSPlaintext record to compress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar deflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.deflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // deflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Decompresses the TLSCompressed record into a TLSPlaintext record using the\n * deflate algorithm.\n *\n * @param c the TLS connection.\n * @param record the TLSCompressed record to decompress.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nvar inflate = function(c, record, s) {\n var rval = false;\n\n try {\n var bytes = c.inflate(record.fragment.getBytes());\n record.fragment = forge.util.createBuffer(bytes);\n record.length = bytes.length;\n rval = true;\n } catch(ex) {\n // inflate error, fail out\n }\n\n return rval;\n};\n\n/**\n * Reads a TLS variable-length vector from a byte buffer.\n *\n * Variable-length vectors are defined by specifying a subrange of legal\n * lengths, inclusively, using the notation . When these are\n * encoded, the actual length precedes the vector's contents in the byte\n * stream. The length will be in the form of a number consuming as many bytes\n * as required to hold the vector's specified maximum (ceiling) length. A\n * variable-length vector with an actual length field of zero is referred to\n * as an empty vector.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n *\n * @return the resulting byte buffer.\n */\nvar readVector = function(b, lenBytes) {\n var len = 0;\n switch(lenBytes) {\n case 1:\n len = b.getByte();\n break;\n case 2:\n len = b.getInt16();\n break;\n case 3:\n len = b.getInt24();\n break;\n case 4:\n len = b.getInt32();\n break;\n }\n\n // read vector bytes into a new buffer\n return forge.util.createBuffer(b.getBytes(len));\n};\n\n/**\n * Writes a TLS variable-length vector to a byte buffer.\n *\n * @param b the byte buffer.\n * @param lenBytes the number of bytes required to store the length.\n * @param v the byte buffer vector.\n */\nvar writeVector = function(b, lenBytes, v) {\n // encode length at the start of the vector, where the number of bytes for\n // the length is the maximum number of bytes it would take to encode the\n // vector's ceiling\n b.putInt(v.length(), lenBytes << 3);\n b.putBuffer(v);\n};\n\n/**\n * The tls implementation.\n */\nvar tls = {};\n\n/**\n * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and\n * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time\n * of this implementation so TLS 1.0 was implemented instead.\n */\ntls.Versions = {\n TLS_1_0: {major: 3, minor: 1},\n TLS_1_1: {major: 3, minor: 2},\n TLS_1_2: {major: 3, minor: 3}\n};\ntls.SupportedVersions = [\n tls.Versions.TLS_1_1,\n tls.Versions.TLS_1_0\n];\ntls.Version = tls.SupportedVersions[0];\n\n/**\n * Maximum fragment size. True maximum is 16384, but we fragment before that\n * to allow for unusual small increases during compression.\n */\ntls.MaxFragment = 16384 - 1024;\n\n/**\n * Whether this entity is considered the \"client\" or \"server\".\n * enum { server, client } ConnectionEnd;\n */\ntls.ConnectionEnd = {\n server: 0,\n client: 1\n};\n\n/**\n * Pseudo-random function algorithm used to generate keys from the master\n * secret.\n * enum { tls_prf_sha256 } PRFAlgorithm;\n */\ntls.PRFAlgorithm = {\n tls_prf_sha256: 0\n};\n\n/**\n * Bulk encryption algorithms.\n * enum { null, rc4, des3, aes } BulkCipherAlgorithm;\n */\ntls.BulkCipherAlgorithm = {\n none: null,\n rc4: 0,\n des3: 1,\n aes: 2\n};\n\n/**\n * Cipher types.\n * enum { stream, block, aead } CipherType;\n */\ntls.CipherType = {\n stream: 0,\n block: 1,\n aead: 2\n};\n\n/**\n * MAC (Message Authentication Code) algorithms.\n * enum { null, hmac_md5, hmac_sha1, hmac_sha256,\n * hmac_sha384, hmac_sha512} MACAlgorithm;\n */\ntls.MACAlgorithm = {\n none: null,\n hmac_md5: 0,\n hmac_sha1: 1,\n hmac_sha256: 2,\n hmac_sha384: 3,\n hmac_sha512: 4\n};\n\n/**\n * Compression algorithms.\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n */\ntls.CompressionMethod = {\n none: 0,\n deflate: 1\n};\n\n/**\n * TLS record content types.\n * enum {\n * change_cipher_spec(20), alert(21), handshake(22),\n * application_data(23), (255)\n * } ContentType;\n */\ntls.ContentType = {\n change_cipher_spec: 20,\n alert: 21,\n handshake: 22,\n application_data: 23,\n heartbeat: 24\n};\n\n/**\n * TLS handshake types.\n * enum {\n * hello_request(0), client_hello(1), server_hello(2),\n * certificate(11), server_key_exchange (12),\n * certificate_request(13), server_hello_done(14),\n * certificate_verify(15), client_key_exchange(16),\n * finished(20), (255)\n * } HandshakeType;\n */\ntls.HandshakeType = {\n hello_request: 0,\n client_hello: 1,\n server_hello: 2,\n certificate: 11,\n server_key_exchange: 12,\n certificate_request: 13,\n server_hello_done: 14,\n certificate_verify: 15,\n client_key_exchange: 16,\n finished: 20\n};\n\n/**\n * TLS Alert Protocol.\n *\n * enum { warning(1), fatal(2), (255) } AlertLevel;\n *\n * enum {\n * close_notify(0),\n * unexpected_message(10),\n * bad_record_mac(20),\n * decryption_failed(21),\n * record_overflow(22),\n * decompression_failure(30),\n * handshake_failure(40),\n * bad_certificate(42),\n * unsupported_certificate(43),\n * certificate_revoked(44),\n * certificate_expired(45),\n * certificate_unknown(46),\n * illegal_parameter(47),\n * unknown_ca(48),\n * access_denied(49),\n * decode_error(50),\n * decrypt_error(51),\n * export_restriction(60),\n * protocol_version(70),\n * insufficient_security(71),\n * internal_error(80),\n * user_canceled(90),\n * no_renegotiation(100),\n * (255)\n * } AlertDescription;\n *\n * struct {\n * AlertLevel level;\n * AlertDescription description;\n * } Alert;\n */\ntls.Alert = {};\ntls.Alert.Level = {\n warning: 1,\n fatal: 2\n};\ntls.Alert.Description = {\n close_notify: 0,\n unexpected_message: 10,\n bad_record_mac: 20,\n decryption_failed: 21,\n record_overflow: 22,\n decompression_failure: 30,\n handshake_failure: 40,\n bad_certificate: 42,\n unsupported_certificate: 43,\n certificate_revoked: 44,\n certificate_expired: 45,\n certificate_unknown: 46,\n illegal_parameter: 47,\n unknown_ca: 48,\n access_denied: 49,\n decode_error: 50,\n decrypt_error: 51,\n export_restriction: 60,\n protocol_version: 70,\n insufficient_security: 71,\n internal_error: 80,\n user_canceled: 90,\n no_renegotiation: 100\n};\n\n/**\n * TLS Heartbeat Message types.\n * enum {\n * heartbeat_request(1),\n * heartbeat_response(2),\n * (255)\n * } HeartbeatMessageType;\n */\ntls.HeartbeatMessageType = {\n heartbeat_request: 1,\n heartbeat_response: 2\n};\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites = {};\n\n/**\n * Gets a supported cipher suite from its 2 byte ID.\n *\n * @param twoBytes two bytes in a string.\n *\n * @return the matching supported cipher suite or null.\n */\ntls.getCipherSuite = function(twoBytes) {\n var rval = null;\n for(var key in tls.CipherSuites) {\n var cs = tls.CipherSuites[key];\n if(cs.id[0] === twoBytes.charCodeAt(0) &&\n cs.id[1] === twoBytes.charCodeAt(1)) {\n rval = cs;\n break;\n }\n }\n return rval;\n};\n\n/**\n * Called when an unexpected record is encountered.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleUnexpected = function(c, record) {\n // if connection is client and closed, ignore unexpected messages\n var ignore = (!c.open && c.entity === tls.ConnectionEnd.client);\n if(!ignore) {\n c.error(c, {\n message: 'Unexpected message. Received TLS record out of order.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unexpected_message\n }\n });\n }\n};\n\n/**\n * Called when a client receives a HelloRequest record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleHelloRequest = function(c, record, length) {\n // ignore renegotiation requests from the server during a handshake, but\n // if handshaking, send a warning alert that renegotation is denied\n if(!c.handshaking && c.handshakes > 0) {\n // send alert warning\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.no_renegotiation\n }));\n tls.flush(c);\n }\n\n // continue\n c.process();\n};\n\n/**\n * Parses a hello message from a ClientHello or ServerHello record.\n *\n * @param record the record to parse.\n *\n * @return the parsed message.\n */\ntls.parseHelloMessage = function(c, record, length) {\n var msg = null;\n\n var client = (c.entity === tls.ConnectionEnd.client);\n\n // minimum of 38 bytes in message\n if(length < 38) {\n c.error(c, {\n message: client ?\n 'Invalid ServerHello message. Message too short.' :\n 'Invalid ClientHello message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else {\n // use 'remaining' to calculate # of remaining bytes in the message\n var b = record.fragment;\n var remaining = b.length();\n msg = {\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n random: forge.util.createBuffer(b.getBytes(32)),\n session_id: readVector(b, 1),\n extensions: []\n };\n if(client) {\n msg.cipher_suite = b.getBytes(2);\n msg.compression_method = b.getByte();\n } else {\n msg.cipher_suites = readVector(b, 2);\n msg.compression_methods = readVector(b, 1);\n }\n\n // read extensions if there are any bytes left in the message\n remaining = length - (remaining - b.length());\n if(remaining > 0) {\n // parse extensions\n var exts = readVector(b, 2);\n while(exts.length() > 0) {\n msg.extensions.push({\n type: [exts.getByte(), exts.getByte()],\n data: readVector(exts, 2)\n });\n }\n\n // TODO: make extension support modular\n if(!client) {\n for(var i = 0; i < msg.extensions.length; ++i) {\n var ext = msg.extensions[i];\n\n // support SNI extension\n if(ext.type[0] === 0x00 && ext.type[1] === 0x00) {\n // get server name list\n var snl = readVector(ext.data, 2);\n while(snl.length() > 0) {\n // read server name type\n var snType = snl.getByte();\n\n // only HostName type (0x00) is known, break out if\n // another type is detected\n if(snType !== 0x00) {\n break;\n }\n\n // add host name to server name list\n c.session.extensions.server_name.serverNameList.push(\n readVector(snl, 2).getBytes());\n }\n }\n }\n }\n }\n\n // version already set, do not allow version change\n if(c.session.version) {\n if(msg.version.major !== c.session.version.major ||\n msg.version.minor !== c.session.version.minor) {\n return c.error(c, {\n message: 'TLS version change is disallowed during renegotiation.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n // get the chosen (ServerHello) cipher suite\n if(client) {\n // FIXME: should be checking configured acceptable cipher suites\n c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite);\n } else {\n // get a supported preferred (ClientHello) cipher suite\n // choose the first supported cipher suite\n var tmp = forge.util.createBuffer(msg.cipher_suites.bytes());\n while(tmp.length() > 0) {\n // FIXME: should be checking configured acceptable suites\n // cipher suites take up 2 bytes\n c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2));\n if(c.session.cipherSuite !== null) {\n break;\n }\n }\n }\n\n // cipher suite not supported\n if(c.session.cipherSuite === null) {\n return c.error(c, {\n message: 'No cipher suites in common.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n },\n cipherSuite: forge.util.bytesToHex(msg.cipher_suite)\n });\n }\n\n // TODO: handle compression methods\n if(client) {\n c.session.compressionMethod = msg.compression_method;\n } else {\n // no compression\n c.session.compressionMethod = tls.CompressionMethod.none;\n }\n }\n\n return msg;\n};\n\n/**\n * Creates security parameters for the given connection based on the given\n * hello message.\n *\n * @param c the TLS connection.\n * @param msg the hello message.\n */\ntls.createSecurityParameters = function(c, msg) {\n /* Note: security params are from TLS 1.2, some values like prf_algorithm\n are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is\n used. */\n\n // TODO: handle other options from server when more supported\n\n // get client and server randoms\n var client = (c.entity === tls.ConnectionEnd.client);\n var msgRandom = msg.random.bytes();\n var cRandom = client ? c.session.sp.client_random : msgRandom;\n var sRandom = client ? msgRandom : tls.createRandom().getBytes();\n\n // create new security parameters\n c.session.sp = {\n entity: c.entity,\n prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256,\n bulk_cipher_algorithm: null,\n cipher_type: null,\n enc_key_length: null,\n block_length: null,\n fixed_iv_length: null,\n record_iv_length: null,\n mac_algorithm: null,\n mac_length: null,\n mac_key_length: null,\n compression_algorithm: c.session.compressionMethod,\n pre_master_secret: null,\n master_secret: null,\n client_random: cRandom,\n server_random: sRandom\n };\n};\n\n/**\n * Called when a client receives a ServerHello record.\n *\n * When a ServerHello message will be sent:\n * The server will send this message in response to a client hello message\n * when it was able to find an acceptable set of algorithms. If it cannot\n * find such a match, it will respond with a handshake failure alert.\n *\n * uint24 length;\n * struct {\n * ProtocolVersion server_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suite;\n * CompressionMethod compression_method;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ServerHello;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // ensure server version is compatible\n if(msg.version.minor <= c.version.minor) {\n c.version.minor = msg.version.minor;\n } else {\n return c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n\n // indicate session version has been set\n c.session.version = c.version;\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // if the session ID is not blank and matches the cached one, resume\n // the session\n if(sessionId.length > 0 && sessionId === c.session.id) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = SCC;\n c.session.resuming = true;\n\n // get new server random\n c.session.sp.server_random = msg.random.bytes();\n } else {\n // not resuming, expect a server Certificate message next\n c.expect = SCE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // set new session ID\n c.session.id = sessionId;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a ClientHello record.\n *\n * When a ClientHello message will be sent:\n * When a client first connects to a server it is required to send the\n * client hello as its first message. The client can also send a client\n * hello in response to a hello request or on its own initiative in order\n * to renegotiate the security parameters in an existing connection.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientHello = function(c, record, length) {\n var msg = tls.parseHelloMessage(c, record, length);\n if(c.fail) {\n return;\n }\n\n // get the session ID from the message\n var sessionId = msg.session_id.bytes();\n\n // see if the given session ID is in the cache\n var session = null;\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n if(session === null) {\n // session ID not found\n sessionId = '';\n } else if(session.version.major !== msg.version.major ||\n session.version.minor > msg.version.minor) {\n // if session version is incompatible with client version, do not resume\n session = null;\n sessionId = '';\n }\n }\n\n // no session found to resume, generate a new session ID\n if(sessionId.length === 0) {\n sessionId = forge.random.getBytes(32);\n }\n\n // update session\n c.session.id = sessionId;\n c.session.clientHelloVersion = msg.version;\n c.session.sp = {};\n if(session) {\n // use version and security parameters from resumed session\n c.version = c.session.version = session.version;\n c.session.sp = session.sp;\n } else {\n // use highest compatible minor version\n var version;\n for(var i = 1; i < tls.SupportedVersions.length; ++i) {\n version = tls.SupportedVersions[i];\n if(version.minor <= msg.version.minor) {\n break;\n }\n }\n c.version = {major: version.major, minor: version.minor};\n c.session.version = c.version;\n }\n\n // if a session is set, resume it\n if(session !== null) {\n // resuming session, expect a ChangeCipherSpec next\n c.expect = CCC;\n c.session.resuming = true;\n\n // get new client random\n c.session.sp.client_random = msg.random.bytes();\n } else {\n // not resuming, expect a Certificate or ClientKeyExchange\n c.expect = (c.verifyClient !== false) ? CCE : CKE;\n c.session.resuming = false;\n\n // create new security parameters\n tls.createSecurityParameters(c, msg);\n }\n\n // connection now open\n c.open = true;\n\n // queue server hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHello(c)\n }));\n\n if(c.session.resuming) {\n // queue change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // queue finished\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n } else {\n // queue server certificate\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n }));\n\n if(!c.fail) {\n // queue server key exchange\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerKeyExchange(c)\n }));\n\n // request client certificate if set\n if(c.verifyClient !== false) {\n // queue certificate request\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateRequest(c)\n }));\n }\n\n // queue server hello done\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createServerHelloDone(c)\n }));\n }\n }\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a Certificate record.\n *\n * When this message will be sent:\n * The server must send a certificate whenever the agreed-upon key exchange\n * method is not an anonymous one. This message will always immediately\n * follow the server hello message.\n *\n * Meaning of this message:\n * The certificate type must be appropriate for the selected cipher suite's\n * key exchange algorithm, and is generally an X.509v3 certificate. It must\n * contain a key which matches the key exchange method, as follows. Unless\n * otherwise specified, the signing algorithm for the certificate must be\n * the same as the algorithm for the certificate key. Unless otherwise\n * specified, the public key may be of any length.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n * struct {\n * ASN.1Cert certificate_list<1..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificate = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid Certificate message. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n certificate_list: readVector(b, 3)\n };\n\n /* The sender's certificate will be first in the list (chain), each\n subsequent one that follows will certify the previous one, but root\n certificates (self-signed) that specify the certificate authority may\n be omitted under the assumption that clients must already possess it. */\n var cert, asn1;\n var certs = [];\n try {\n while(msg.certificate_list.length() > 0) {\n // each entry in msg.certificate_list is a vector with 3 len bytes\n cert = readVector(msg.certificate_list, 3);\n asn1 = forge.asn1.fromDer(cert);\n cert = forge.pki.certificateFromAsn1(asn1, true);\n certs.push(cert);\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not parse certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n\n // ensure at least 1 certificate was provided if in client-mode\n // or if verifyClient was set to true to require a certificate\n // (as opposed to 'optional')\n var client = (c.entity === tls.ConnectionEnd.client);\n if((client || c.verifyClient === true) && certs.length === 0) {\n // error, no certificate\n c.error(c, {\n message: client ?\n 'No server certificate provided.' :\n 'No client certificate provided.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n } else if(certs.length === 0) {\n // no certs to verify\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n } else {\n // save certificate in session\n if(client) {\n c.session.serverCertificate = certs[0];\n } else {\n c.session.clientCertificate = certs[0];\n }\n\n if(tls.verifyCertificateChain(c, certs)) {\n // expect a ServerKeyExchange or ClientKeyExchange message next\n c.expect = client ? SKE : CKE;\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerKeyExchange record.\n *\n * When this message will be sent:\n * This message will be sent immediately after the server certificate\n * message (or the server hello message, if this is an anonymous\n * negotiation).\n *\n * The server key exchange message is sent by the server only when the\n * server certificate message (if sent) does not contain enough data to\n * allow the client to exchange a premaster secret.\n *\n * Meaning of this message:\n * This message conveys cryptographic information to allow the client to\n * communicate the premaster secret: either an RSA public key to encrypt\n * the premaster secret with, or a Diffie-Hellman public key with which the\n * client can complete a key exchange (with the result being the premaster\n * secret.)\n *\n * enum {\n * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa\n * } KeyExchangeAlgorithm;\n *\n * struct {\n * opaque dh_p<1..2^16-1>;\n * opaque dh_g<1..2^16-1>;\n * opaque dh_Ys<1..2^16-1>;\n * } ServerDHParams;\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case dh_anon:\n * ServerDHParams params;\n * case dhe_dss:\n * case dhe_rsa:\n * ServerDHParams params;\n * digitally-signed struct {\n * opaque client_random[32];\n * opaque server_random[32];\n * ServerDHParams params;\n * } signed_params;\n * case rsa:\n * case dh_dss:\n * case dh_rsa:\n * struct {};\n * };\n * } ServerKeyExchange;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length > 0 is invalid\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n // expect an optional CertificateRequest message next\n c.expect = SCR;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ClientKeyExchange record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleClientKeyExchange = function(c, record, length) {\n // this implementation only supports RSA, no Diffie-Hellman support\n // so any length < 48 is invalid\n if(length < 48) {\n return c.error(c, {\n message: 'Invalid key parameters. Only RSA is supported.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.unsupported_certificate\n }\n });\n }\n\n var b = record.fragment;\n var msg = {\n enc_pre_master_secret: readVector(b, 2).getBytes()\n };\n\n // do rsa decryption\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.serverCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n\n if(privateKey === null) {\n return c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n\n try {\n // decrypt 48-byte pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);\n\n // ensure client hello version matches first 2 bytes\n var version = c.session.clientHelloVersion;\n if(version.major !== sp.pre_master_secret.charCodeAt(0) ||\n version.minor !== sp.pre_master_secret.charCodeAt(1)) {\n // error, do not send alert (see BLEI attack below)\n throw new Error('TLS version rollback attack detected.');\n }\n } catch(ex) {\n /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a\n TLS server which is using PKCS#1 encoded RSA, so instead of\n failing here, we generate 48 random bytes and use that as\n the pre-master secret. */\n sp.pre_master_secret = forge.random.getBytes(48);\n }\n\n // expect a CertificateVerify message if a Certificate was received that\n // does not have fixed Diffie-Hellman params, otherwise expect\n // ChangeCipherSpec\n c.expect = CCC;\n if(c.session.clientCertificate !== null) {\n // only RSA support, so expect CertificateVerify\n // TODO: support Diffie-Hellman\n c.expect = CCV;\n }\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a CertificateRequest record.\n *\n * When this message will be sent:\n * A non-anonymous server can optionally request a certificate from the\n * client, if appropriate for the selected cipher suite. This message, if\n * sent, will immediately follow the Server Key Exchange message (if it is\n * sent; otherwise, the Server Certificate message).\n *\n * enum {\n * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),\n * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6),\n * fortezza_dms_RESERVED(20), (255)\n * } ClientCertificateType;\n *\n * opaque DistinguishedName<1..2^16-1>;\n *\n * struct {\n * ClientCertificateType certificate_types<1..2^8-1>;\n * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>;\n * DistinguishedName certificate_authorities<0..2^16-1>;\n * } CertificateRequest;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateRequest = function(c, record, length) {\n // minimum of 3 bytes in message\n if(length < 3) {\n return c.error(c, {\n message: 'Invalid CertificateRequest. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // TODO: TLS 1.2+ has different format including\n // SignatureAndHashAlgorithm after cert types\n var b = record.fragment;\n var msg = {\n certificate_types: readVector(b, 1),\n certificate_authorities: readVector(b, 2)\n };\n\n // save certificate request in session\n c.session.certificateRequest = msg;\n\n // expect a ServerHelloDone message next\n c.expect = SHD;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a server receives a CertificateVerify record.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleCertificateVerify = function(c, record, length) {\n if(length < 2) {\n return c.error(c, {\n message: 'Invalid CertificateVerify. Message too short.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for CertificateVerify messages because\n // they must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n var msg = {\n signature: readVector(b, 2).getBytes()\n };\n\n // TODO: add support for DSA\n\n // generate data to verify\n var verify = forge.util.createBuffer();\n verify.putBuffer(c.session.md5.digest());\n verify.putBuffer(c.session.sha1.digest());\n verify = verify.getBytes();\n\n try {\n var cert = c.session.clientCertificate;\n /*b = forge.pki.rsa.decrypt(\n msg.signature, cert.publicKey, true, verify.length);\n if(b !== verify) {*/\n if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) {\n throw new Error('CertificateVerify signature does not match.');\n }\n\n // digest message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n } catch(ex) {\n return c.error(c, {\n message: 'Bad signature in CertificateVerify.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.handshake_failure\n }\n });\n }\n\n // expect ChangeCipherSpec\n c.expect = CCC;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a client receives a ServerHelloDone record.\n *\n * When this message will be sent:\n * The server hello done message is sent by the server to indicate the end\n * of the server hello and associated messages. After sending this message\n * the server will wait for a client response.\n *\n * Meaning of this message:\n * This message means that the server is done sending messages to support\n * the key exchange, and the client can proceed with its phase of the key\n * exchange.\n *\n * Upon receipt of the server hello done message the client should verify\n * that the server provided a valid certificate if required and check that\n * the server hello parameters are acceptable.\n *\n * struct {} ServerHelloDone;\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleServerHelloDone = function(c, record, length) {\n // len must be 0 bytes\n if(length > 0) {\n return c.error(c, {\n message: 'Invalid ServerHelloDone message. Invalid length.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.record_overflow\n }\n });\n }\n\n if(c.serverCertificate === null) {\n // no server certificate was provided\n var error = {\n message: 'No server certificate provided. Not enough security.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.insufficient_security\n }\n };\n\n // call application callback\n var depth = 0;\n var ret = c.verify(c, error.alert.description, depth, []);\n if(ret !== true) {\n // check for custom alert info\n if(ret || ret === 0) {\n // set custom message and alert description\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n } else if(typeof ret === 'number') {\n // set custom alert description\n error.alert.description = ret;\n }\n }\n\n // send error\n return c.error(c, error);\n }\n }\n\n // create client certificate message if requested\n if(c.session.certificateRequest !== null) {\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificate(c)\n });\n tls.queue(c, record);\n }\n\n // create client key exchange message\n record = tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientKeyExchange(c)\n });\n tls.queue(c, record);\n\n // expect no messages until the following callback has been called\n c.expect = SER;\n\n // create callback to handle client signature (for client-certs)\n var callback = function(c, signature) {\n if(c.session.certificateRequest !== null &&\n c.session.clientCertificate !== null) {\n // create certificate verify message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createCertificateVerify(c, signature)\n }));\n }\n\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // create pending state\n c.state.pending = tls.createConnectionState(c);\n\n // change current write state to pending write state\n c.state.current.write = c.state.pending.write;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n\n // expect a server ChangeCipherSpec message next\n c.expect = SCC;\n\n // send records\n tls.flush(c);\n\n // continue\n c.process();\n };\n\n // if there is no certificate request or no client certificate, do\n // callback immediately\n if(c.session.certificateRequest === null ||\n c.session.clientCertificate === null) {\n return callback(c, null);\n }\n\n // otherwise get the client signature\n tls.getClientSignature(c, callback);\n};\n\n/**\n * Called when a ChangeCipherSpec record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleChangeCipherSpec = function(c, record) {\n if(record.fragment.getByte() !== 0x01) {\n return c.error(c, {\n message: 'Invalid ChangeCipherSpec message received.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.illegal_parameter\n }\n });\n }\n\n // create pending state if:\n // 1. Resuming session in client mode OR\n // 2. NOT resuming session in server mode\n var client = (c.entity === tls.ConnectionEnd.client);\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n c.state.pending = tls.createConnectionState(c);\n }\n\n // change current read state to pending read state\n c.state.current.read = c.state.pending.read;\n\n // clear pending state if:\n // 1. NOT resuming session in client mode OR\n // 2. resuming a session in server mode\n if((!c.session.resuming && client) || (c.session.resuming && !client)) {\n c.state.pending = null;\n }\n\n // expect a Finished record next\n c.expect = client ? SFI : CFI;\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Finished record is received.\n *\n * When this message will be sent:\n * A finished message is always sent immediately after a change\n * cipher spec message to verify that the key exchange and\n * authentication processes were successful. It is essential that a\n * change cipher spec message be received between the other\n * handshake messages and the Finished message.\n *\n * Meaning of this message:\n * The finished message is the first protected with the just-\n * negotiated algorithms, keys, and secrets. Recipients of finished\n * messages must verify that the contents are correct. Once a side\n * has sent its Finished message and received and validated the\n * Finished message from its peer, it may begin to send and receive\n * application data over the connection.\n *\n * struct {\n * opaque verify_data[verify_data_length];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, Hash(handshake_messages))\n * [0..verify_data_length-1];\n *\n * finished_label\n * For Finished messages sent by the client, the string\n * \"client finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * verify_data_length depends on the cipher suite. If it is not specified\n * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used\n * 12 bytes.\n *\n * @param c the connection.\n * @param record the record.\n * @param length the length of the handshake message.\n */\ntls.handleFinished = function(c, record, length) {\n // rewind to get full bytes for message so it can be manually\n // digested below (special case for Finished messages because they\n // must be digested *after* handling as opposed to all others)\n var b = record.fragment;\n b.read -= 4;\n var msgBytes = b.bytes();\n b.read += 4;\n\n // message contains only verify_data\n var vd = record.fragment.getBytes();\n\n // ensure verify data is correct\n b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // set label based on entity type\n var client = (c.entity === tls.ConnectionEnd.client);\n var label = client ? 'server finished' : 'client finished';\n\n // TODO: determine prf function and verify length for TLS 1.2\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n if(b.getBytes() !== vd) {\n return c.error(c, {\n message: 'Invalid verify_data in Finished message.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decrypt_error\n }\n });\n }\n\n // digest finished message now that it has been handled\n c.session.md5.update(msgBytes);\n c.session.sha1.update(msgBytes);\n\n // resuming session as client or NOT resuming session as server\n if((c.session.resuming && client) || (!c.session.resuming && !client)) {\n // create change cipher spec message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.change_cipher_spec,\n data: tls.createChangeCipherSpec()\n }));\n\n // change current write state to pending write state, clear pending\n c.state.current.write = c.state.pending.write;\n c.state.pending = null;\n\n // create finished message\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createFinished(c)\n }));\n }\n\n // expect application data next\n c.expect = client ? SAD : CAD;\n\n // handshake complete\n c.handshaking = false;\n ++c.handshakes;\n\n // save access to peer certificate\n c.peerCertificate = client ?\n c.session.serverCertificate : c.session.clientCertificate;\n\n // send records\n tls.flush(c);\n\n // now connected\n c.isConnected = true;\n c.connected(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when an Alert record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleAlert = function(c, record) {\n // read alert\n var b = record.fragment;\n var alert = {\n level: b.getByte(),\n description: b.getByte()\n };\n\n // TODO: consider using a table?\n // get appropriate message\n var msg;\n switch(alert.description) {\n case tls.Alert.Description.close_notify:\n msg = 'Connection closed.';\n break;\n case tls.Alert.Description.unexpected_message:\n msg = 'Unexpected message.';\n break;\n case tls.Alert.Description.bad_record_mac:\n msg = 'Bad record MAC.';\n break;\n case tls.Alert.Description.decryption_failed:\n msg = 'Decryption failed.';\n break;\n case tls.Alert.Description.record_overflow:\n msg = 'Record overflow.';\n break;\n case tls.Alert.Description.decompression_failure:\n msg = 'Decompression failed.';\n break;\n case tls.Alert.Description.handshake_failure:\n msg = 'Handshake failure.';\n break;\n case tls.Alert.Description.bad_certificate:\n msg = 'Bad certificate.';\n break;\n case tls.Alert.Description.unsupported_certificate:\n msg = 'Unsupported certificate.';\n break;\n case tls.Alert.Description.certificate_revoked:\n msg = 'Certificate revoked.';\n break;\n case tls.Alert.Description.certificate_expired:\n msg = 'Certificate expired.';\n break;\n case tls.Alert.Description.certificate_unknown:\n msg = 'Certificate unknown.';\n break;\n case tls.Alert.Description.illegal_parameter:\n msg = 'Illegal parameter.';\n break;\n case tls.Alert.Description.unknown_ca:\n msg = 'Unknown certificate authority.';\n break;\n case tls.Alert.Description.access_denied:\n msg = 'Access denied.';\n break;\n case tls.Alert.Description.decode_error:\n msg = 'Decode error.';\n break;\n case tls.Alert.Description.decrypt_error:\n msg = 'Decrypt error.';\n break;\n case tls.Alert.Description.export_restriction:\n msg = 'Export restriction.';\n break;\n case tls.Alert.Description.protocol_version:\n msg = 'Unsupported protocol version.';\n break;\n case tls.Alert.Description.insufficient_security:\n msg = 'Insufficient security.';\n break;\n case tls.Alert.Description.internal_error:\n msg = 'Internal error.';\n break;\n case tls.Alert.Description.user_canceled:\n msg = 'User canceled.';\n break;\n case tls.Alert.Description.no_renegotiation:\n msg = 'Renegotiation not supported.';\n break;\n default:\n msg = 'Unknown error.';\n break;\n }\n\n // close connection on close_notify, not an error\n if(alert.description === tls.Alert.Description.close_notify) {\n return c.close();\n }\n\n // call error handler\n c.error(c, {\n message: msg,\n send: false,\n // origin is the opposite end\n origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client',\n alert: alert\n });\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Handshake record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHandshake = function(c, record) {\n // get the handshake type and message length\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt24();\n\n // see if the record fragment doesn't yet contain the full message\n if(length > b.length()) {\n // cache the record, clear its fragment, and reset the buffer read\n // pointer before the type and length were read\n c.fragmented = record;\n record.fragment = forge.util.createBuffer();\n b.read -= 4;\n\n // continue\n return c.process();\n }\n\n // full message now available, clear cache, reset read pointer to\n // before type and length\n c.fragmented = null;\n b.read -= 4;\n\n // save the handshake bytes for digestion after handler is found\n // (include type and length of handshake msg)\n var bytes = b.bytes(length + 4);\n\n // restore read pointer\n b.read += 4;\n\n // handle expected message\n if(type in hsTable[c.entity][c.expect]) {\n // initialize server session\n if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) {\n c.handshaking = true;\n c.session = {\n version: null,\n extensions: {\n server_name: {\n serverNameList: []\n }\n },\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n clientCertificate: null,\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n }\n\n /* Update handshake messages digest. Finished and CertificateVerify\n messages are not digested here. They can't be digested as part of\n the verify_data that they contain. These messages are manually\n digested in their handlers. HelloRequest messages are simply never\n included in the handshake message digest according to spec. */\n if(type !== tls.HandshakeType.hello_request &&\n type !== tls.HandshakeType.certificate_verify &&\n type !== tls.HandshakeType.finished) {\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n }\n\n // handle specific handshake type record\n hsTable[c.entity][c.expect][type](c, record, length);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n};\n\n/**\n * Called when an ApplicationData record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleApplicationData = function(c, record) {\n // buffer data, notify that its ready\n c.data.putBuffer(record.fragment);\n c.dataReady(c);\n\n // continue\n c.process();\n};\n\n/**\n * Called when a Heartbeat record is received.\n *\n * @param c the connection.\n * @param record the record.\n */\ntls.handleHeartbeat = function(c, record) {\n // get the heartbeat type and payload\n var b = record.fragment;\n var type = b.getByte();\n var length = b.getInt16();\n var payload = b.getBytes(length);\n\n if(type === tls.HeartbeatMessageType.heartbeat_request) {\n // discard request during handshake or if length is too large\n if(c.handshaking || length > payload.length) {\n // continue\n return c.process();\n }\n // retransmit payload\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_response, payload)\n }));\n tls.flush(c);\n } else if(type === tls.HeartbeatMessageType.heartbeat_response) {\n // check payload against expected payload, discard heartbeat if no match\n if(payload !== c.expectedHeartbeatPayload) {\n // continue\n return c.process();\n }\n\n // notify that a valid heartbeat was received\n if(c.heartbeatReceived) {\n c.heartbeatReceived(c, forge.util.createBuffer(payload));\n }\n }\n\n // continue\n c.process();\n};\n\n/**\n * The transistional state tables for receiving TLS records. It maps the\n * current TLS engine state and a received record to a function to handle the\n * record and update the state.\n *\n * For instance, if the current state is SHE, then the TLS engine is expecting\n * a ServerHello record. Once a record is received, the handler function is\n * looked up using the state SHE and the record's content type.\n *\n * The resulting function will either be an error handler or a record handler.\n * The function will take whatever action is appropriate and update the state\n * for the next record.\n *\n * The states are all based on possible server record types. Note that the\n * client will never specifically expect to receive a HelloRequest or an alert\n * from the server so there is no state that reflects this. These messages may\n * occur at any time.\n *\n * There are two tables for mapping states because there is a second tier of\n * types for handshake messages. Once a record with a content type of handshake\n * is received, the handshake record handler will look up the handshake type in\n * the secondary map to get its appropriate handler.\n *\n * Valid message orders are as follows:\n *\n * =======================FULL HANDSHAKE======================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * Certificate*\n * ServerKeyExchange*\n * CertificateRequest*\n * <-------- ServerHelloDone\n * Certificate*\n * ClientKeyExchange\n * CertificateVerify*\n * [ChangeCipherSpec]\n * Finished -------->\n * [ChangeCipherSpec]\n * <-------- Finished\n * Application Data <-------> Application Data\n *\n * =====================SESSION RESUMPTION=====================\n * Client Server\n *\n * ClientHello -------->\n * ServerHello\n * [ChangeCipherSpec]\n * <-------- Finished\n * [ChangeCipherSpec]\n * Finished -------->\n * Application Data <-------> Application Data\n */\n// client expect states (indicate which records are expected to be received)\nvar SHE = 0; // rcv server hello\nvar SCE = 1; // rcv server certificate\nvar SKE = 2; // rcv server key exchange\nvar SCR = 3; // rcv certificate request\nvar SHD = 4; // rcv server hello done\nvar SCC = 5; // rcv change cipher spec\nvar SFI = 6; // rcv finished\nvar SAD = 7; // rcv application data\nvar SER = 8; // not expecting any messages at this point\n\n// server expect states\nvar CHE = 0; // rcv client hello\nvar CCE = 1; // rcv client certificate\nvar CKE = 2; // rcv client key exchange\nvar CCV = 3; // rcv certificate verify\nvar CCC = 4; // rcv change cipher spec\nvar CFI = 5; // rcv finished\nvar CAD = 6; // rcv application data\nvar CER = 7; // not expecting any messages at this point\n\n// map client current expect state and content type to function\nvar __ = tls.handleUnexpected;\nvar R0 = tls.handleChangeCipherSpec;\nvar R1 = tls.handleAlert;\nvar R2 = tls.handleHandshake;\nvar R3 = tls.handleApplicationData;\nvar R4 = tls.handleHeartbeat;\nvar ctTable = [];\nctTable[tls.ConnectionEnd.client] = [\n// CC,AL,HS,AD,HB\n/*SHE*/[__,R1,R2,__,R4],\n/*SCE*/[__,R1,R2,__,R4],\n/*SKE*/[__,R1,R2,__,R4],\n/*SCR*/[__,R1,R2,__,R4],\n/*SHD*/[__,R1,R2,__,R4],\n/*SCC*/[R0,R1,__,__,R4],\n/*SFI*/[__,R1,R2,__,R4],\n/*SAD*/[__,R1,R2,R3,R4],\n/*SER*/[__,R1,R2,__,R4]\n];\n\n// map server current expect state and content type to function\nctTable[tls.ConnectionEnd.server] = [\n// CC,AL,HS,AD\n/*CHE*/[__,R1,R2,__,R4],\n/*CCE*/[__,R1,R2,__,R4],\n/*CKE*/[__,R1,R2,__,R4],\n/*CCV*/[__,R1,R2,__,R4],\n/*CCC*/[R0,R1,__,__,R4],\n/*CFI*/[__,R1,R2,__,R4],\n/*CAD*/[__,R1,R2,R3,R4],\n/*CER*/[__,R1,R2,__,R4]\n];\n\n// map client current expect state and handshake type to function\nvar H0 = tls.handleHelloRequest;\nvar H1 = tls.handleServerHello;\nvar H2 = tls.handleCertificate;\nvar H3 = tls.handleServerKeyExchange;\nvar H4 = tls.handleCertificateRequest;\nvar H5 = tls.handleServerHelloDone;\nvar H6 = tls.handleFinished;\nvar hsTable = [];\nhsTable[tls.ConnectionEnd.client] = [\n// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI\n/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],\n/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],\n/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],\n/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],\n/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n// map server current expect state and handshake type to function\n// Note: CAD[CH] does not map to FB because renegotation is prohibited\nvar H7 = tls.handleClientHello;\nvar H8 = tls.handleClientKeyExchange;\nvar H9 = tls.handleCertificateVerify;\nhsTable[tls.ConnectionEnd.server] = [\n// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI\n/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],\n/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],\n/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],\n/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],\n/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],\n/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]\n];\n\n/**\n * Generates the master_secret and keys using the given security parameters.\n *\n * The security parameters for a TLS connection state are defined as such:\n *\n * struct {\n * ConnectionEnd entity;\n * PRFAlgorithm prf_algorithm;\n * BulkCipherAlgorithm bulk_cipher_algorithm;\n * CipherType cipher_type;\n * uint8 enc_key_length;\n * uint8 block_length;\n * uint8 fixed_iv_length;\n * uint8 record_iv_length;\n * MACAlgorithm mac_algorithm;\n * uint8 mac_length;\n * uint8 mac_key_length;\n * CompressionMethod compression_algorithm;\n * opaque master_secret[48];\n * opaque client_random[32];\n * opaque server_random[32];\n * } SecurityParameters;\n *\n * Note that this definition is from TLS 1.2. In TLS 1.0 some of these\n * parameters are ignored because, for instance, the PRFAlgorithm is a\n * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0.\n *\n * The Record Protocol requires an algorithm to generate keys required by the\n * current connection state.\n *\n * The master secret is expanded into a sequence of secure bytes, which is then\n * split to a client write MAC key, a server write MAC key, a client write\n * encryption key, and a server write encryption key. In TLS 1.0 a client write\n * IV and server write IV are also generated. Each of these is generated from\n * the byte sequence in that order. Unused values are empty. In TLS 1.2, some\n * AEAD ciphers may additionally require a client write IV and a server write\n * IV (see Section 6.2.3.3).\n *\n * When keys, MAC keys, and IVs are generated, the master secret is used as an\n * entropy source.\n *\n * To generate the key material, compute:\n *\n * master_secret = PRF(pre_master_secret, \"master secret\",\n * ClientHello.random + ServerHello.random)\n *\n * key_block = PRF(SecurityParameters.master_secret,\n * \"key expansion\",\n * SecurityParameters.server_random +\n * SecurityParameters.client_random);\n *\n * until enough output has been generated. Then, the key_block is\n * partitioned as follows:\n *\n * client_write_MAC_key[SecurityParameters.mac_key_length]\n * server_write_MAC_key[SecurityParameters.mac_key_length]\n * client_write_key[SecurityParameters.enc_key_length]\n * server_write_key[SecurityParameters.enc_key_length]\n * client_write_IV[SecurityParameters.fixed_iv_length]\n * server_write_IV[SecurityParameters.fixed_iv_length]\n *\n * In TLS 1.2, the client_write_IV and server_write_IV are only generated for\n * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This\n * implementation uses TLS 1.0 so IVs are generated.\n *\n * Implementation note: The currently defined cipher suite which requires the\n * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32\n * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also\n * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material.\n *\n * @param c the connection.\n * @param sp the security parameters to use.\n *\n * @return the security keys.\n */\ntls.generateKeys = function(c, sp) {\n // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) &\n // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented\n // at present\n\n // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with\n // TLS 1.0 but we don't care right now because AES is better and we have\n // an implementation for it\n\n // TODO: TLS 1.2 implementation\n /*\n // determine the PRF\n var prf;\n switch(sp.prf_algorithm) {\n case tls.PRFAlgorithm.tls_prf_sha256:\n prf = prf_sha256;\n break;\n default:\n // should never happen\n throw new Error('Invalid PRF');\n }\n */\n\n // TLS 1.0/1.1 implementation\n var prf = prf_TLS1;\n\n // concatenate server and client random\n var random = sp.client_random + sp.server_random;\n\n // only create master secret if session is new\n if(!c.session.resuming) {\n // create master secret, clean up pre-master secret\n sp.master_secret = prf(\n sp.pre_master_secret, 'master secret', random, 48).bytes();\n sp.pre_master_secret = null;\n }\n\n // generate the amount of key material needed\n random = sp.server_random + sp.client_random;\n var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;\n\n // include IV for TLS/1.0\n var tls10 = (c.version.major === tls.Versions.TLS_1_0.major &&\n c.version.minor === tls.Versions.TLS_1_0.minor);\n if(tls10) {\n length += 2 * sp.fixed_iv_length;\n }\n var km = prf(sp.master_secret, 'key expansion', random, length);\n\n // split the key material into the MAC and encryption keys\n var rval = {\n client_write_MAC_key: km.getBytes(sp.mac_key_length),\n server_write_MAC_key: km.getBytes(sp.mac_key_length),\n client_write_key: km.getBytes(sp.enc_key_length),\n server_write_key: km.getBytes(sp.enc_key_length)\n };\n\n // include TLS 1.0 IVs\n if(tls10) {\n rval.client_write_IV = km.getBytes(sp.fixed_iv_length);\n rval.server_write_IV = km.getBytes(sp.fixed_iv_length);\n }\n\n return rval;\n};\n\n/**\n * Creates a new initialized TLS connection state. A connection state has\n * a read mode and a write mode.\n *\n * compression state:\n * The current state of the compression algorithm.\n *\n * cipher state:\n * The current state of the encryption algorithm. This will consist of the\n * scheduled key for that connection. For stream ciphers, this will also\n * contain whatever state information is necessary to allow the stream to\n * continue to encrypt or decrypt data.\n *\n * MAC key:\n * The MAC key for the connection.\n *\n * sequence number:\n * Each connection state contains a sequence number, which is maintained\n * separately for read and write states. The sequence number MUST be set to\n * zero whenever a connection state is made the active state. Sequence\n * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do\n * not wrap. If a TLS implementation would need to wrap a sequence number,\n * it must renegotiate instead. A sequence number is incremented after each\n * record: specifically, the first record transmitted under a particular\n * connection state MUST use sequence number 0.\n *\n * @param c the connection.\n *\n * @return the new initialized TLS connection state.\n */\ntls.createConnectionState = function(c) {\n var client = (c.entity === tls.ConnectionEnd.client);\n\n var createMode = function() {\n var mode = {\n // two 32-bit numbers, first is most significant\n sequenceNumber: [0, 0],\n macKey: null,\n macLength: 0,\n macFunction: null,\n cipherState: null,\n cipherFunction: function(record) {return true;},\n compressionState: null,\n compressFunction: function(record) {return true;},\n updateSequenceNumber: function() {\n if(mode.sequenceNumber[1] === 0xFFFFFFFF) {\n mode.sequenceNumber[1] = 0;\n ++mode.sequenceNumber[0];\n } else {\n ++mode.sequenceNumber[1];\n }\n }\n };\n return mode;\n };\n var state = {\n read: createMode(),\n write: createMode()\n };\n\n // update function in read mode will decrypt then decompress a record\n state.read.update = function(c, record) {\n if(!state.read.cipherFunction(record, state.read)) {\n c.error(c, {\n message: 'Could not decrypt record or bad MAC.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n // doesn't matter if decryption failed or MAC was\n // invalid, return the same error so as not to reveal\n // which one occurred\n description: tls.Alert.Description.bad_record_mac\n }\n });\n } else if(!state.read.compressFunction(c, record, state.read)) {\n c.error(c, {\n message: 'Could not decompress record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.decompression_failure\n }\n });\n }\n return !c.fail;\n };\n\n // update function in write mode will compress then encrypt a record\n state.write.update = function(c, record) {\n if(!state.write.compressFunction(c, record, state.write)) {\n // error, but do not send alert since it would require\n // compression as well\n c.error(c, {\n message: 'Could not compress record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else if(!state.write.cipherFunction(record, state.write)) {\n // error, but do not send alert since it would require\n // encryption as well\n c.error(c, {\n message: 'Could not encrypt record.',\n send: false,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n return !c.fail;\n };\n\n // handle security parameters\n if(c.session) {\n var sp = c.session.sp;\n c.session.cipherSuite.initSecurityParameters(sp);\n\n // generate keys\n sp.keys = tls.generateKeys(c, sp);\n state.read.macKey = client ?\n sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;\n state.write.macKey = client ?\n sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;\n\n // cipher suite setup\n c.session.cipherSuite.initConnectionState(state, c, sp);\n\n // compression setup\n switch(sp.compression_algorithm) {\n case tls.CompressionMethod.none:\n break;\n case tls.CompressionMethod.deflate:\n state.read.compressFunction = inflate;\n state.write.compressFunction = deflate;\n break;\n default:\n throw new Error('Unsupported compression algorithm.');\n }\n }\n\n return state;\n};\n\n/**\n * Creates a Random structure.\n *\n * struct {\n * uint32 gmt_unix_time;\n * opaque random_bytes[28];\n * } Random;\n *\n * gmt_unix_time:\n * The current time and date in standard UNIX 32-bit format (seconds since\n * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according\n * to the sender's internal clock. Clocks are not required to be set\n * correctly by the basic TLS protocol; higher-level or application\n * protocols may define additional requirements. Note that, for historical\n * reasons, the data element is named using GMT, the predecessor of the\n * current worldwide time base, UTC.\n * random_bytes:\n * 28 bytes generated by a secure random number generator.\n *\n * @return the Random structure as a byte array.\n */\ntls.createRandom = function() {\n // get UTC milliseconds\n var d = new Date();\n var utc = +d + d.getTimezoneOffset() * 60000;\n var rval = forge.util.createBuffer();\n rval.putInt32(utc);\n rval.putBytes(forge.random.getBytes(28));\n return rval;\n};\n\n/**\n * Creates a TLS record with the given type and data.\n *\n * @param c the connection.\n * @param options:\n * type: the record type.\n * data: the plain text data in a byte buffer.\n *\n * @return the created record.\n */\ntls.createRecord = function(c, options) {\n if(!options.data) {\n return null;\n }\n var record = {\n type: options.type,\n version: {\n major: c.version.major,\n minor: c.version.minor\n },\n length: options.data.length(),\n fragment: options.data\n };\n return record;\n};\n\n/**\n * Creates a TLS alert record.\n *\n * @param c the connection.\n * @param alert:\n * level: the TLS alert level.\n * description: the TLS alert description.\n *\n * @return the created alert record.\n */\ntls.createAlert = function(c, alert) {\n var b = forge.util.createBuffer();\n b.putByte(alert.level);\n b.putByte(alert.description);\n return tls.createRecord(c, {\n type: tls.ContentType.alert,\n data: b\n });\n};\n\n/* The structure of a TLS handshake message.\n *\n * struct {\n * HandshakeType msg_type; // handshake type\n * uint24 length; // bytes in message\n * select(HandshakeType) {\n * case hello_request: HelloRequest;\n * case client_hello: ClientHello;\n * case server_hello: ServerHello;\n * case certificate: Certificate;\n * case server_key_exchange: ServerKeyExchange;\n * case certificate_request: CertificateRequest;\n * case server_hello_done: ServerHelloDone;\n * case certificate_verify: CertificateVerify;\n * case client_key_exchange: ClientKeyExchange;\n * case finished: Finished;\n * } body;\n * } Handshake;\n */\n\n/**\n * Creates a ClientHello message.\n *\n * opaque SessionID<0..32>;\n * enum { null(0), deflate(1), (255) } CompressionMethod;\n * uint8 CipherSuite[2];\n *\n * struct {\n * ProtocolVersion client_version;\n * Random random;\n * SessionID session_id;\n * CipherSuite cipher_suites<2..2^16-2>;\n * CompressionMethod compression_methods<1..2^8-1>;\n * select(extensions_present) {\n * case false:\n * struct {};\n * case true:\n * Extension extensions<0..2^16-1>;\n * };\n * } ClientHello;\n *\n * The extension format for extended client hellos and server hellos is:\n *\n * struct {\n * ExtensionType extension_type;\n * opaque extension_data<0..2^16-1>;\n * } Extension;\n *\n * Here:\n *\n * - \"extension_type\" identifies the particular extension type.\n * - \"extension_data\" contains information specific to the particular\n * extension type.\n *\n * The extension types defined in this document are:\n *\n * enum {\n * server_name(0), max_fragment_length(1),\n * client_certificate_url(2), trusted_ca_keys(3),\n * truncated_hmac(4), status_request(5), (65535)\n * } ExtensionType;\n *\n * @param c the connection.\n *\n * @return the ClientHello byte buffer.\n */\ntls.createClientHello = function(c) {\n // save hello version\n c.session.clientHelloVersion = {\n major: c.version.major,\n minor: c.version.minor\n };\n\n // create supported cipher suites\n var cipherSuites = forge.util.createBuffer();\n for(var i = 0; i < c.cipherSuites.length; ++i) {\n var cs = c.cipherSuites[i];\n cipherSuites.putByte(cs.id[0]);\n cipherSuites.putByte(cs.id[1]);\n }\n var cSuites = cipherSuites.length();\n\n // create supported compression methods, null always supported, but\n // also support deflate if connection has inflate and deflate methods\n var compressionMethods = forge.util.createBuffer();\n compressionMethods.putByte(tls.CompressionMethod.none);\n // FIXME: deflate support disabled until issues with raw deflate data\n // without zlib headers are resolved\n /*\n if(c.inflate !== null && c.deflate !== null) {\n compressionMethods.putByte(tls.CompressionMethod.deflate);\n }\n */\n var cMethods = compressionMethods.length();\n\n // create TLS SNI (server name indication) extension if virtual host\n // has been specified, see RFC 3546\n var extensions = forge.util.createBuffer();\n if(c.virtualHost) {\n // create extension struct\n var ext = forge.util.createBuffer();\n ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes)\n ext.putByte(0x00);\n\n /* In order to provide the server name, clients MAY include an\n * extension of type \"server_name\" in the (extended) client hello.\n * The \"extension_data\" field of this extension SHALL contain\n * \"ServerNameList\" where:\n *\n * struct {\n * NameType name_type;\n * select(name_type) {\n * case host_name: HostName;\n * } name;\n * } ServerName;\n *\n * enum {\n * host_name(0), (255)\n * } NameType;\n *\n * opaque HostName<1..2^16-1>;\n *\n * struct {\n * ServerName server_name_list<1..2^16-1>\n * } ServerNameList;\n */\n var serverName = forge.util.createBuffer();\n serverName.putByte(0x00); // type host_name\n writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost));\n\n // ServerNameList is in extension_data\n var snList = forge.util.createBuffer();\n writeVector(snList, 2, serverName);\n writeVector(ext, 2, snList);\n extensions.putBuffer(ext);\n }\n var extLength = extensions.length();\n if(extLength > 0) {\n // add extension vector length\n extLength += 2;\n }\n\n // determine length of the handshake message\n // cipher suites and compression methods size will need to be\n // updated if more get added to the list\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + cSuites + // cipher suites vector\n 1 + cMethods + // compression methods vector\n extLength; // extensions vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.client_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n writeVector(rval, 2, cipherSuites);\n writeVector(rval, 1, compressionMethods);\n if(extLength > 0) {\n writeVector(rval, 2, extensions);\n }\n return rval;\n};\n\n/**\n * Creates a ServerHello message.\n *\n * @param c the connection.\n *\n * @return the ServerHello byte buffer.\n */\ntls.createServerHello = function(c) {\n // determine length of the handshake message\n var sessionId = c.session.id;\n var length =\n sessionId.length + 1 + // session ID vector\n 2 + // version (major + minor)\n 4 + 28 + // random time and random bytes\n 2 + // chosen cipher suite\n 1; // chosen compression method\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello);\n rval.putInt24(length); // handshake length\n rval.putByte(c.version.major); // major version\n rval.putByte(c.version.minor); // minor version\n rval.putBytes(c.session.sp.server_random); // random time + bytes\n writeVector(rval, 1, forge.util.createBuffer(sessionId));\n rval.putByte(c.session.cipherSuite.id[0]);\n rval.putByte(c.session.cipherSuite.id[1]);\n rval.putByte(c.session.compressionMethod);\n return rval;\n};\n\n/**\n * Creates a Certificate message.\n *\n * When this message will be sent:\n * This is the first message the client can send after receiving a server\n * hello done message and the first message the server can send after\n * sending a ServerHello. This client message is only sent if the server\n * requests a certificate. If no suitable certificate is available, the\n * client should send a certificate message containing no certificates. If\n * client authentication is required by the server for the handshake to\n * continue, it may respond with a fatal handshake failure alert.\n *\n * opaque ASN.1Cert<1..2^24-1>;\n *\n * struct {\n * ASN.1Cert certificate_list<0..2^24-1>;\n * } Certificate;\n *\n * @param c the connection.\n *\n * @return the Certificate byte buffer.\n */\ntls.createCertificate = function(c) {\n // TODO: check certificate request to ensure types are supported\n\n // get a certificate (a certificate as a PEM string)\n var client = (c.entity === tls.ConnectionEnd.client);\n var cert = null;\n if(c.getCertificate) {\n var hint;\n if(client) {\n hint = c.session.certificateRequest;\n } else {\n hint = c.session.extensions.server_name.serverNameList;\n }\n cert = c.getCertificate(c, hint);\n }\n\n // buffer to hold certificate list\n var certList = forge.util.createBuffer();\n if(cert !== null) {\n try {\n // normalize cert to a chain of certificates\n if(!forge.util.isArray(cert)) {\n cert = [cert];\n }\n var asn1 = null;\n for(var i = 0; i < cert.length; ++i) {\n var msg = forge.pem.decode(cert[i])[0];\n if(msg.type !== 'CERTIFICATE' &&\n msg.type !== 'X509 CERTIFICATE' &&\n msg.type !== 'TRUSTED CERTIFICATE') {\n var error = new Error('Could not convert certificate from PEM; PEM ' +\n 'header type is not \"CERTIFICATE\", \"X509 CERTIFICATE\", or ' +\n '\"TRUSTED CERTIFICATE\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert certificate from PEM; PEM is encrypted.');\n }\n\n var der = forge.util.createBuffer(msg.body);\n if(asn1 === null) {\n asn1 = forge.asn1.fromDer(der.bytes(), false);\n }\n\n // certificate entry is itself a vector with 3 length bytes\n var certBuffer = forge.util.createBuffer();\n writeVector(certBuffer, 3, der);\n\n // add cert vector to cert list vector\n certList.putBuffer(certBuffer);\n }\n\n // save certificate\n cert = forge.pki.certificateFromAsn1(asn1);\n if(client) {\n c.session.clientCertificate = cert;\n } else {\n c.session.serverCertificate = cert;\n }\n } catch(ex) {\n return c.error(c, {\n message: 'Could not send certificate list.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n }\n });\n }\n }\n\n // determine length of the handshake message\n var length = 3 + certList.length(); // cert list vector\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate);\n rval.putInt24(length);\n writeVector(rval, 3, certList);\n return rval;\n};\n\n/**\n * Creates a ClientKeyExchange message.\n *\n * When this message will be sent:\n * This message is always sent by the client. It will immediately follow the\n * client certificate message, if it is sent. Otherwise it will be the first\n * message sent by the client after it receives the server hello done\n * message.\n *\n * Meaning of this message:\n * With this message, the premaster secret is set, either though direct\n * transmission of the RSA-encrypted secret, or by the transmission of\n * Diffie-Hellman parameters which will allow each side to agree upon the\n * same premaster secret. When the key exchange method is DH_RSA or DH_DSS,\n * client certification has been requested, and the client was able to\n * respond with a certificate which contained a Diffie-Hellman public key\n * whose parameters (group and generator) matched those specified by the\n * server in its certificate, this message will not contain any data.\n *\n * Meaning of this message:\n * If RSA is being used for key agreement and authentication, the client\n * generates a 48-byte premaster secret, encrypts it using the public key\n * from the server's certificate or the temporary RSA key provided in a\n * server key exchange message, and sends the result in an encrypted\n * premaster secret message. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * struct {\n * select(KeyExchangeAlgorithm) {\n * case rsa: EncryptedPreMasterSecret;\n * case diffie_hellman: ClientDiffieHellmanPublic;\n * } exchange_keys;\n * } ClientKeyExchange;\n *\n * struct {\n * ProtocolVersion client_version;\n * opaque random[46];\n * } PreMasterSecret;\n *\n * struct {\n * public-key-encrypted PreMasterSecret pre_master_secret;\n * } EncryptedPreMasterSecret;\n *\n * A public-key-encrypted element is encoded as a vector <0..2^16-1>.\n *\n * @param c the connection.\n *\n * @return the ClientKeyExchange byte buffer.\n */\ntls.createClientKeyExchange = function(c) {\n // create buffer to encrypt\n var b = forge.util.createBuffer();\n\n // add highest client-supported protocol to help server avoid version\n // rollback attacks\n b.putByte(c.session.clientHelloVersion.major);\n b.putByte(c.session.clientHelloVersion.minor);\n\n // generate and add 46 random bytes\n b.putBytes(forge.random.getBytes(46));\n\n // save pre-master secret\n var sp = c.session.sp;\n sp.pre_master_secret = b.getBytes();\n\n // RSA-encrypt the pre-master secret\n var key = c.session.serverCertificate.publicKey;\n b = key.encrypt(sp.pre_master_secret);\n\n /* Note: The encrypted pre-master secret will be stored in a\n public-key-encrypted opaque vector that has the length prefixed using\n 2 bytes, so include those 2 bytes in the handshake message length. This\n is done as a minor optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = b.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.client_key_exchange);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(b.length);\n rval.putBytes(b);\n return rval;\n};\n\n/**\n * Creates a ServerKeyExchange message.\n *\n * @param c the connection.\n *\n * @return the ServerKeyExchange byte buffer.\n */\ntls.createServerKeyExchange = function(c) {\n // this implementation only supports RSA, no Diffie-Hellman support,\n // so this record is empty\n\n // determine length of the handshake message\n var length = 0;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n if(length > 0) {\n rval.putByte(tls.HandshakeType.server_key_exchange);\n rval.putInt24(length);\n }\n return rval;\n};\n\n/**\n * Gets the signed data used to verify a client-side certificate. See\n * tls.createCertificateVerify() for details.\n *\n * @param c the connection.\n * @param callback the callback to call once the signed data is ready.\n */\ntls.getClientSignature = function(c, callback) {\n // generate data to RSA encrypt\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n b = b.getBytes();\n\n // create default signing function as necessary\n c.getSignature = c.getSignature || function(c, b, callback) {\n // do rsa encryption, call callback\n var privateKey = null;\n if(c.getPrivateKey) {\n try {\n privateKey = c.getPrivateKey(c, c.session.clientCertificate);\n privateKey = forge.pki.privateKeyFromPem(privateKey);\n } catch(ex) {\n c.error(c, {\n message: 'Could not get private key.',\n cause: ex,\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n }\n }\n if(privateKey === null) {\n c.error(c, {\n message: 'No private key set.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.internal_error\n }\n });\n } else {\n b = privateKey.sign(b, null);\n }\n callback(c, b);\n };\n\n // get client signature\n c.getSignature(c, b, callback);\n};\n\n/**\n * Creates a CertificateVerify message.\n *\n * Meaning of this message:\n * This structure conveys the client's Diffie-Hellman public value\n * (Yc) if it was not already included in the client's certificate.\n * The encoding used for Yc is determined by the enumerated\n * PublicValueEncoding. This structure is a variant of the client\n * key exchange message, not a message in itself.\n *\n * When this message will be sent:\n * This message is used to provide explicit verification of a client\n * certificate. This message is only sent following a client\n * certificate that has signing capability (i.e. all certificates\n * except those containing fixed Diffie-Hellman parameters). When\n * sent, it will immediately follow the client key exchange message.\n *\n * struct {\n * Signature signature;\n * } CertificateVerify;\n *\n * CertificateVerify.signature.md5_hash\n * MD5(handshake_messages);\n *\n * Certificate.signature.sha_hash\n * SHA(handshake_messages);\n *\n * Here handshake_messages refers to all handshake messages sent or\n * received starting at client hello up to but not including this\n * message, including the type and length fields of the handshake\n * messages.\n *\n * select(SignatureAlgorithm) {\n * case anonymous: struct { };\n * case rsa:\n * digitally-signed struct {\n * opaque md5_hash[16];\n * opaque sha_hash[20];\n * };\n * case dsa:\n * digitally-signed struct {\n * opaque sha_hash[20];\n * };\n * } Signature;\n *\n * In digital signing, one-way hash functions are used as input for a\n * signing algorithm. A digitally-signed element is encoded as an opaque\n * vector <0..2^16-1>, where the length is specified by the signing\n * algorithm and key.\n *\n * In RSA signing, a 36-byte structure of two hashes (one SHA and one\n * MD5) is signed (encrypted with the private key). It is encoded with\n * PKCS #1 block type 0 or type 1 as described in [PKCS1].\n *\n * In DSS, the 20 bytes of the SHA hash are run directly through the\n * Digital Signing Algorithm with no additional hashing.\n *\n * @param c the connection.\n * @param signature the signature to include in the message.\n *\n * @return the CertificateVerify byte buffer.\n */\ntls.createCertificateVerify = function(c, signature) {\n /* Note: The signature will be stored in a \"digitally-signed\" opaque\n vector that has the length prefixed using 2 bytes, so include those\n 2 bytes in the handshake message length. This is done as a minor\n optimization instead of calling writeVector(). */\n\n // determine length of the handshake message\n var length = signature.length + 2;\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_verify);\n rval.putInt24(length);\n // add vector length bytes\n rval.putInt16(signature.length);\n rval.putBytes(signature);\n return rval;\n};\n\n/**\n * Creates a CertificateRequest message.\n *\n * @param c the connection.\n *\n * @return the CertificateRequest byte buffer.\n */\ntls.createCertificateRequest = function(c) {\n // TODO: support other certificate types\n var certTypes = forge.util.createBuffer();\n\n // common RSA certificate type\n certTypes.putByte(0x01);\n\n // add distinguished names from CA store\n var cAs = forge.util.createBuffer();\n for(var key in c.caStore.certs) {\n var cert = c.caStore.certs[key];\n var dn = forge.pki.distinguishedNameToAsn1(cert.subject);\n var byteBuffer = forge.asn1.toDer(dn);\n cAs.putInt16(byteBuffer.length());\n cAs.putBuffer(byteBuffer);\n }\n\n // TODO: TLS 1.2+ has a different format\n\n // determine length of the handshake message\n var length =\n 1 + certTypes.length() +\n 2 + cAs.length();\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.certificate_request);\n rval.putInt24(length);\n writeVector(rval, 1, certTypes);\n writeVector(rval, 2, cAs);\n return rval;\n};\n\n/**\n * Creates a ServerHelloDone message.\n *\n * @param c the connection.\n *\n * @return the ServerHelloDone byte buffer.\n */\ntls.createServerHelloDone = function(c) {\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.server_hello_done);\n rval.putInt24(0);\n return rval;\n};\n\n/**\n * Creates a ChangeCipherSpec message.\n *\n * The change cipher spec protocol exists to signal transitions in\n * ciphering strategies. The protocol consists of a single message,\n * which is encrypted and compressed under the current (not the pending)\n * connection state. The message consists of a single byte of value 1.\n *\n * struct {\n * enum { change_cipher_spec(1), (255) } type;\n * } ChangeCipherSpec;\n *\n * @return the ChangeCipherSpec byte buffer.\n */\ntls.createChangeCipherSpec = function() {\n var rval = forge.util.createBuffer();\n rval.putByte(0x01);\n return rval;\n};\n\n/**\n * Creates a Finished message.\n *\n * struct {\n * opaque verify_data[12];\n * } Finished;\n *\n * verify_data\n * PRF(master_secret, finished_label, MD5(handshake_messages) +\n * SHA-1(handshake_messages)) [0..11];\n *\n * finished_label\n * For Finished messages sent by the client, the string \"client\n * finished\". For Finished messages sent by the server, the\n * string \"server finished\".\n *\n * handshake_messages\n * All of the data from all handshake messages up to but not\n * including this message. This is only data visible at the\n * handshake layer and does not include record layer headers.\n * This is the concatenation of all the Handshake structures as\n * defined in 7.4 exchanged thus far.\n *\n * @param c the connection.\n *\n * @return the Finished byte buffer.\n */\ntls.createFinished = function(c) {\n // generate verify_data\n var b = forge.util.createBuffer();\n b.putBuffer(c.session.md5.digest());\n b.putBuffer(c.session.sha1.digest());\n\n // TODO: determine prf function and verify length for TLS 1.2\n var client = (c.entity === tls.ConnectionEnd.client);\n var sp = c.session.sp;\n var vdl = 12;\n var prf = prf_TLS1;\n var label = client ? 'client finished' : 'server finished';\n b = prf(sp.master_secret, label, b.getBytes(), vdl);\n\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(tls.HandshakeType.finished);\n rval.putInt24(b.length());\n rval.putBuffer(b);\n return rval;\n};\n\n/**\n * Creates a HeartbeatMessage (See RFC 6520).\n *\n * struct {\n * HeartbeatMessageType type;\n * uint16 payload_length;\n * opaque payload[HeartbeatMessage.payload_length];\n * opaque padding[padding_length];\n * } HeartbeatMessage;\n *\n * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or\n * max_fragment_length when negotiated as defined in [RFC6066].\n *\n * type: The message type, either heartbeat_request or heartbeat_response.\n *\n * payload_length: The length of the payload.\n *\n * payload: The payload consists of arbitrary content.\n *\n * padding: The padding is random content that MUST be ignored by the\n * receiver. The length of a HeartbeatMessage is TLSPlaintext.length\n * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the\n * length of the type field is 1 byte, and the length of the\n * payload_length is 2. Therefore, the padding_length is\n * TLSPlaintext.length - payload_length - 3 for TLS and\n * DTLSPlaintext.length - payload_length - 3 for DTLS. The\n * padding_length MUST be at least 16.\n *\n * The sender of a HeartbeatMessage MUST use a random padding of at\n * least 16 bytes. The padding of a received HeartbeatMessage message\n * MUST be ignored.\n *\n * If the payload_length of a received HeartbeatMessage is too large,\n * the received HeartbeatMessage MUST be discarded silently.\n *\n * @param c the connection.\n * @param type the tls.HeartbeatMessageType.\n * @param payload the heartbeat data to send as the payload.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return the HeartbeatRequest byte buffer.\n */\ntls.createHeartbeat = function(type, payload, payloadLength) {\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n // build record fragment\n var rval = forge.util.createBuffer();\n rval.putByte(type); // heartbeat message type\n rval.putInt16(payloadLength); // payload length\n rval.putBytes(payload); // payload\n // padding\n var plaintextLength = rval.length();\n var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);\n rval.putBytes(forge.random.getBytes(paddingLength));\n return rval;\n};\n\n/**\n * Fragments, compresses, encrypts, and queues a record for delivery.\n *\n * @param c the connection.\n * @param record the record to queue.\n */\ntls.queue = function(c, record) {\n // error during record creation\n if(!record) {\n return;\n }\n\n if(record.fragment.length() === 0) {\n if(record.type === tls.ContentType.handshake ||\n record.type === tls.ContentType.alert ||\n record.type === tls.ContentType.change_cipher_spec) {\n // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent.\n return;\n }\n }\n\n // if the record is a handshake record, update handshake hashes\n if(record.type === tls.ContentType.handshake) {\n var bytes = record.fragment.bytes();\n c.session.md5.update(bytes);\n c.session.sha1.update(bytes);\n bytes = null;\n }\n\n // handle record fragmentation\n var records;\n if(record.fragment.length() <= tls.MaxFragment) {\n records = [record];\n } else {\n // fragment data as long as it is too long\n records = [];\n var data = record.fragment.bytes();\n while(data.length > tls.MaxFragment) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data.slice(0, tls.MaxFragment))\n }));\n data = data.slice(tls.MaxFragment);\n }\n // add last record\n if(data.length > 0) {\n records.push(tls.createRecord(c, {\n type: record.type,\n data: forge.util.createBuffer(data)\n }));\n }\n }\n\n // compress and encrypt all fragmented records\n for(var i = 0; i < records.length && !c.fail; ++i) {\n // update the record using current write state\n var rec = records[i];\n var s = c.state.current.write;\n if(s.update(c, rec)) {\n // store record\n c.records.push(rec);\n }\n }\n};\n\n/**\n * Flushes all queued records to the output buffer and calls the\n * tlsDataReady() handler on the given connection.\n *\n * @param c the connection.\n *\n * @return true on success, false on failure.\n */\ntls.flush = function(c) {\n for(var i = 0; i < c.records.length; ++i) {\n var record = c.records[i];\n\n // add record header and fragment\n c.tlsData.putByte(record.type);\n c.tlsData.putByte(record.version.major);\n c.tlsData.putByte(record.version.minor);\n c.tlsData.putInt16(record.fragment.length());\n c.tlsData.putBuffer(c.records[i].fragment);\n }\n c.records = [];\n return c.tlsDataReady(c);\n};\n\n/**\n * Maps a pki.certificateError to a tls.Alert.Description.\n *\n * @param error the error to map.\n *\n * @return the alert description.\n */\nvar _certErrorToAlertDesc = function(error) {\n switch(error) {\n case true:\n return true;\n case forge.pki.certificateError.bad_certificate:\n return tls.Alert.Description.bad_certificate;\n case forge.pki.certificateError.unsupported_certificate:\n return tls.Alert.Description.unsupported_certificate;\n case forge.pki.certificateError.certificate_revoked:\n return tls.Alert.Description.certificate_revoked;\n case forge.pki.certificateError.certificate_expired:\n return tls.Alert.Description.certificate_expired;\n case forge.pki.certificateError.certificate_unknown:\n return tls.Alert.Description.certificate_unknown;\n case forge.pki.certificateError.unknown_ca:\n return tls.Alert.Description.unknown_ca;\n default:\n return tls.Alert.Description.bad_certificate;\n }\n};\n\n/**\n * Maps a tls.Alert.Description to a pki.certificateError.\n *\n * @param desc the alert description.\n *\n * @return the certificate error.\n */\nvar _alertDescToCertError = function(desc) {\n switch(desc) {\n case true:\n return true;\n case tls.Alert.Description.bad_certificate:\n return forge.pki.certificateError.bad_certificate;\n case tls.Alert.Description.unsupported_certificate:\n return forge.pki.certificateError.unsupported_certificate;\n case tls.Alert.Description.certificate_revoked:\n return forge.pki.certificateError.certificate_revoked;\n case tls.Alert.Description.certificate_expired:\n return forge.pki.certificateError.certificate_expired;\n case tls.Alert.Description.certificate_unknown:\n return forge.pki.certificateError.certificate_unknown;\n case tls.Alert.Description.unknown_ca:\n return forge.pki.certificateError.unknown_ca;\n default:\n return forge.pki.certificateError.bad_certificate;\n }\n};\n\n/**\n * Verifies a certificate chain against the given connection's\n * Certificate Authority store.\n *\n * @param c the TLS connection.\n * @param chain the certificate chain to verify, with the root or highest\n * authority at the end.\n *\n * @return true if successful, false if not.\n */\ntls.verifyCertificateChain = function(c, chain) {\n try {\n // Make a copy of c.verifyOptions so that we can modify options.verify\n // without modifying c.verifyOptions.\n var options = {};\n for (var key in c.verifyOptions) {\n options[key] = c.verifyOptions[key];\n }\n\n options.verify = function(vfd, depth, chain) {\n // convert pki.certificateError to tls alert description\n var desc = _certErrorToAlertDesc(vfd);\n\n // call application callback\n var ret = c.verify(c, vfd, depth, chain);\n if(ret !== true) {\n if(typeof ret === 'object' && !forge.util.isArray(ret)) {\n // throw custom error\n var error = new Error('The application rejected the certificate.');\n error.send = true;\n error.alert = {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.bad_certificate\n };\n if(ret.message) {\n error.message = ret.message;\n }\n if(ret.alert) {\n error.alert.description = ret.alert;\n }\n throw error;\n }\n\n // convert tls alert description to pki.certificateError\n if(ret !== vfd) {\n ret = _alertDescToCertError(ret);\n }\n }\n\n return ret;\n };\n\n // verify chain\n forge.pki.verifyCertificateChain(c.caStore, chain, options);\n } catch(ex) {\n // build tls error if not already customized\n var err = ex;\n if(typeof err !== 'object' || forge.util.isArray(err)) {\n err = {\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(ex)\n }\n };\n }\n if(!('send' in err)) {\n err.send = true;\n }\n if(!('alert' in err)) {\n err.alert = {\n level: tls.Alert.Level.fatal,\n description: _certErrorToAlertDesc(err.error)\n };\n }\n\n // send error\n c.error(c, err);\n }\n\n return !c.fail;\n};\n\n/**\n * Creates a new TLS session cache.\n *\n * @param cache optional map of session ID to cached session.\n * @param capacity the maximum size for the cache (default: 100).\n *\n * @return the new TLS session cache.\n */\ntls.createSessionCache = function(cache, capacity) {\n var rval = null;\n\n // assume input is already a session cache object\n if(cache && cache.getSession && cache.setSession && cache.order) {\n rval = cache;\n } else {\n // create cache\n rval = {};\n rval.cache = cache || {};\n rval.capacity = Math.max(capacity || 100, 1);\n rval.order = [];\n\n // store order for sessions, delete session overflow\n for(var key in cache) {\n if(rval.order.length <= capacity) {\n rval.order.push(key);\n } else {\n delete cache[key];\n }\n }\n\n // get a session from a session ID (or get any session)\n rval.getSession = function(sessionId) {\n var session = null;\n var key = null;\n\n // if session ID provided, use it\n if(sessionId) {\n key = forge.util.bytesToHex(sessionId);\n } else if(rval.order.length > 0) {\n // get first session from cache\n key = rval.order[0];\n }\n\n if(key !== null && key in rval.cache) {\n // get cached session and remove from cache\n session = rval.cache[key];\n delete rval.cache[key];\n for(var i in rval.order) {\n if(rval.order[i] === key) {\n rval.order.splice(i, 1);\n break;\n }\n }\n }\n\n return session;\n };\n\n // set a session in the cache\n rval.setSession = function(sessionId, session) {\n // remove session from cache if at capacity\n if(rval.order.length === rval.capacity) {\n var key = rval.order.shift();\n delete rval.cache[key];\n }\n // add session to cache\n var key = forge.util.bytesToHex(sessionId);\n rval.order.push(key);\n rval.cache[key] = session;\n };\n }\n\n return rval;\n};\n\n/**\n * Creates a new TLS connection.\n *\n * See public createConnection() docs for more details.\n *\n * @param options the options for this connection.\n *\n * @return the new TLS connection.\n */\ntls.createConnection = function(options) {\n var caStore = null;\n if(options.caStore) {\n // if CA store is an array, convert it to a CA store object\n if(forge.util.isArray(options.caStore)) {\n caStore = forge.pki.createCaStore(options.caStore);\n } else {\n caStore = options.caStore;\n }\n } else {\n // create empty CA store\n caStore = forge.pki.createCaStore();\n }\n\n // setup default cipher suites\n var cipherSuites = options.cipherSuites || null;\n if(cipherSuites === null) {\n cipherSuites = [];\n for(var key in tls.CipherSuites) {\n cipherSuites.push(tls.CipherSuites[key]);\n }\n }\n\n // set default entity\n var entity = (options.server || false) ?\n tls.ConnectionEnd.server : tls.ConnectionEnd.client;\n\n // create session cache if requested\n var sessionCache = options.sessionCache ?\n tls.createSessionCache(options.sessionCache) : null;\n\n // create TLS connection\n var c = {\n version: {major: tls.Version.major, minor: tls.Version.minor},\n entity: entity,\n sessionId: options.sessionId,\n caStore: caStore,\n sessionCache: sessionCache,\n cipherSuites: cipherSuites,\n connected: options.connected,\n virtualHost: options.virtualHost || null,\n verifyClient: options.verifyClient || false,\n verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;},\n verifyOptions: options.verifyOptions || {},\n getCertificate: options.getCertificate || null,\n getPrivateKey: options.getPrivateKey || null,\n getSignature: options.getSignature || null,\n input: forge.util.createBuffer(),\n tlsData: forge.util.createBuffer(),\n data: forge.util.createBuffer(),\n tlsDataReady: options.tlsDataReady,\n dataReady: options.dataReady,\n heartbeatReceived: options.heartbeatReceived,\n closed: options.closed,\n error: function(c, ex) {\n // set origin if not set\n ex.origin = ex.origin ||\n ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server');\n\n // send TLS alert\n if(ex.send) {\n tls.queue(c, tls.createAlert(c, ex.alert));\n tls.flush(c);\n }\n\n // error is fatal by default\n var fatal = (ex.fatal !== false);\n if(fatal) {\n // set fail flag\n c.fail = true;\n }\n\n // call error handler first\n options.error(c, ex);\n\n if(fatal) {\n // fatal error, close connection, do not clear fail\n c.close(false);\n }\n },\n deflate: options.deflate || null,\n inflate: options.inflate || null\n };\n\n /**\n * Resets a closed TLS connection for reuse. Called in c.close().\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.reset = function(clearFail) {\n c.version = {major: tls.Version.major, minor: tls.Version.minor};\n c.record = null;\n c.session = null;\n c.peerCertificate = null;\n c.state = {\n pending: null,\n current: null\n };\n c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE;\n c.fragmented = null;\n c.records = [];\n c.open = false;\n c.handshakes = 0;\n c.handshaking = false;\n c.isConnected = false;\n c.fail = !(clearFail || typeof(clearFail) === 'undefined');\n c.input.clear();\n c.tlsData.clear();\n c.data.clear();\n c.state.current = tls.createConnectionState(c);\n };\n\n // do initial reset of connection\n c.reset();\n\n /**\n * Updates the current TLS engine state based on the given record.\n *\n * @param c the TLS connection.\n * @param record the TLS record to act on.\n */\n var _update = function(c, record) {\n // get record handler (align type in table by subtracting lowest)\n var aligned = record.type - tls.ContentType.change_cipher_spec;\n var handlers = ctTable[c.entity][c.expect];\n if(aligned in handlers) {\n handlers[aligned](c, record);\n } else {\n // unexpected record\n tls.handleUnexpected(c, record);\n }\n };\n\n /**\n * Reads the record header and initializes the next record on the given\n * connection.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecordHeader = function(c) {\n var rval = 0;\n\n // get input buffer and its length\n var b = c.input;\n var len = b.length();\n\n // need at least 5 bytes to initialize a record\n if(len < 5) {\n rval = 5 - len;\n } else {\n // enough bytes for header\n // initialize record\n c.record = {\n type: b.getByte(),\n version: {\n major: b.getByte(),\n minor: b.getByte()\n },\n length: b.getInt16(),\n fragment: forge.util.createBuffer(),\n ready: false\n };\n\n // check record version\n var compatibleVersion = (c.record.version.major === c.version.major);\n if(compatibleVersion && c.session && c.session.version) {\n // session version already set, require same minor version\n compatibleVersion = (c.record.version.minor === c.version.minor);\n }\n if(!compatibleVersion) {\n c.error(c, {\n message: 'Incompatible TLS version.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description: tls.Alert.Description.protocol_version\n }\n });\n }\n }\n\n return rval;\n };\n\n /**\n * Reads the next record's contents and appends its message to any\n * previously fragmented message.\n *\n * @param c the TLS connection with the next record.\n *\n * @return 0 if the input data could be processed, otherwise the\n * number of bytes required for data to be processed.\n */\n var _readRecord = function(c) {\n var rval = 0;\n\n // ensure there is enough input data to get the entire record\n var b = c.input;\n var len = b.length();\n if(len < c.record.length) {\n // not enough data yet, return how much is required\n rval = c.record.length - len;\n } else {\n // there is enough data to parse the pending record\n // fill record fragment and compact input buffer\n c.record.fragment.putBytes(b.getBytes(c.record.length));\n b.compact();\n\n // update record using current read state\n var s = c.state.current.read;\n if(s.update(c, c.record)) {\n // see if there is a previously fragmented message that the\n // new record's message fragment should be appended to\n if(c.fragmented !== null) {\n // if the record type matches a previously fragmented\n // record, append the record fragment to it\n if(c.fragmented.type === c.record.type) {\n // concatenate record fragments\n c.fragmented.fragment.putBuffer(c.record.fragment);\n c.record = c.fragmented;\n } else {\n // error, invalid fragmented record\n c.error(c, {\n message: 'Invalid fragmented record.',\n send: true,\n alert: {\n level: tls.Alert.Level.fatal,\n description:\n tls.Alert.Description.unexpected_message\n }\n });\n }\n }\n\n // record is now ready\n c.record.ready = true;\n }\n }\n\n return rval;\n };\n\n /**\n * Performs a handshake using the TLS Handshake Protocol, as a client.\n *\n * This method should only be called if the connection is in client mode.\n *\n * @param sessionId the session ID to use, null to start a new one.\n */\n c.handshake = function(sessionId) {\n // error to call this in non-client mode\n if(c.entity !== tls.ConnectionEnd.client) {\n // not fatal error\n c.error(c, {\n message: 'Cannot initiate handshake as a server.',\n fatal: false\n });\n } else if(c.handshaking) {\n // handshake is already in progress, fail but not fatal error\n c.error(c, {\n message: 'Handshake already in progress.',\n fatal: false\n });\n } else {\n // clear fail flag on reuse\n if(c.fail && !c.open && c.handshakes === 0) {\n c.fail = false;\n }\n\n // now handshaking\n c.handshaking = true;\n\n // default to blank (new session)\n sessionId = sessionId || '';\n\n // if a session ID was specified, try to find it in the cache\n var session = null;\n if(sessionId.length > 0) {\n if(c.sessionCache) {\n session = c.sessionCache.getSession(sessionId);\n }\n\n // matching session not found in cache, clear session ID\n if(session === null) {\n sessionId = '';\n }\n }\n\n // no session given, grab a session from the cache, if available\n if(sessionId.length === 0 && c.sessionCache) {\n session = c.sessionCache.getSession();\n if(session !== null) {\n sessionId = session.id;\n }\n }\n\n // set up session\n c.session = {\n id: sessionId,\n version: null,\n cipherSuite: null,\n compressionMethod: null,\n serverCertificate: null,\n certificateRequest: null,\n clientCertificate: null,\n sp: {},\n md5: forge.md.md5.create(),\n sha1: forge.md.sha1.create()\n };\n\n // use existing session information\n if(session) {\n // only update version on connection, session version not yet set\n c.version = session.version;\n c.session.sp = session.sp;\n }\n\n // generate new client random\n c.session.sp.client_random = tls.createRandom().getBytes();\n\n // connection now open\n c.open = true;\n\n // send hello\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.handshake,\n data: tls.createClientHello(c)\n }));\n tls.flush(c);\n }\n };\n\n /**\n * Called when TLS protocol data has been received from somewhere and should\n * be processed by the TLS engine.\n *\n * @param data the TLS protocol data, as a string, to process.\n *\n * @return 0 if the data could be processed, otherwise the number of bytes\n * required for data to be processed.\n */\n c.process = function(data) {\n var rval = 0;\n\n // buffer input data\n if(data) {\n c.input.putBytes(data);\n }\n\n // process next record if no failure, process will be called after\n // each record is handled (since handling can be asynchronous)\n if(!c.fail) {\n // reset record if ready and now empty\n if(c.record !== null &&\n c.record.ready && c.record.fragment.isEmpty()) {\n c.record = null;\n }\n\n // if there is no pending record, try to read record header\n if(c.record === null) {\n rval = _readRecordHeader(c);\n }\n\n // read the next record (if record not yet ready)\n if(!c.fail && c.record !== null && !c.record.ready) {\n rval = _readRecord(c);\n }\n\n // record ready to be handled, update engine state\n if(!c.fail && c.record !== null && c.record.ready) {\n _update(c, c.record);\n }\n }\n\n return rval;\n };\n\n /**\n * Requests that application data be packaged into a TLS record. The\n * tlsDataReady handler will be called when the TLS record(s) have been\n * prepared.\n *\n * @param data the application data, as a raw 'binary' encoded string, to\n * be sent; to send utf-16/utf-8 string data, use the return value\n * of util.encodeUtf8(str).\n *\n * @return true on success, false on failure.\n */\n c.prepare = function(data) {\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.application_data,\n data: forge.util.createBuffer(data)\n }));\n return tls.flush(c);\n };\n\n /**\n * Requests that a heartbeat request be packaged into a TLS record for\n * transmission. The tlsDataReady handler will be called when TLS record(s)\n * have been prepared.\n *\n * When a heartbeat response has been received, the heartbeatReceived\n * handler will be called with the matching payload. This handler can\n * be used to clear a retransmission timer, etc.\n *\n * @param payload the heartbeat data to send as the payload in the message.\n * @param [payloadLength] the payload length to use, defaults to the\n * actual payload length.\n *\n * @return true on success, false on failure.\n */\n c.prepareHeartbeatRequest = function(payload, payloadLength) {\n if(payload instanceof forge.util.ByteBuffer) {\n payload = payload.bytes();\n }\n if(typeof payloadLength === 'undefined') {\n payloadLength = payload.length;\n }\n c.expectedHeartbeatPayload = payload;\n tls.queue(c, tls.createRecord(c, {\n type: tls.ContentType.heartbeat,\n data: tls.createHeartbeat(\n tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength)\n }));\n return tls.flush(c);\n };\n\n /**\n * Closes the connection (sends a close_notify alert).\n *\n * @param clearFail true to clear the fail flag (default: true).\n */\n c.close = function(clearFail) {\n // save session if connection didn't fail\n if(!c.fail && c.sessionCache && c.session) {\n // only need to preserve session ID, version, and security params\n var session = {\n id: c.session.id,\n version: c.session.version,\n sp: c.session.sp\n };\n session.sp.keys = null;\n c.sessionCache.setSession(session.id, session);\n }\n\n if(c.open) {\n // connection no longer open, clear input\n c.open = false;\n c.input.clear();\n\n // if connected or handshaking, send an alert\n if(c.isConnected || c.handshaking) {\n c.isConnected = c.handshaking = false;\n\n // send close_notify alert\n tls.queue(c, tls.createAlert(c, {\n level: tls.Alert.Level.warning,\n description: tls.Alert.Description.close_notify\n }));\n tls.flush(c);\n }\n\n // call handler\n c.closed(c);\n }\n\n // reset TLS connection, do not clear fail flag\n c.reset(clearFail);\n };\n\n return c;\n};\n\n/* TLS API */\nmodule.exports = forge.tls = forge.tls || {};\n\n// expose non-functions\nfor(var key in tls) {\n if(typeof tls[key] !== 'function') {\n forge.tls[key] = tls[key];\n }\n}\n\n// expose prf_tls1 for testing\nforge.tls.prf_tls1 = prf_TLS1;\n\n// expose sha1 hmac method\nforge.tls.hmac_sha1 = hmac_sha1;\n\n// expose session cache creation\nforge.tls.createSessionCache = tls.createSessionCache;\n\n/**\n * Creates a new TLS connection. This does not make any assumptions about the\n * transport layer that TLS is working on top of, ie: it does not assume there\n * is a TCP/IP connection or establish one. A TLS connection is totally\n * abstracted away from the layer is runs on top of, it merely establishes a\n * secure channel between a client\" and a \"server\".\n *\n * A TLS connection contains 4 connection states: pending read and write, and\n * current read and write.\n *\n * At initialization, the current read and write states will be null. Only once\n * the security parameters have been set and the keys have been generated can\n * the pending states be converted into current states. Current states will be\n * updated for each record processed.\n *\n * A custom certificate verify callback may be provided to check information\n * like the common name on the server's certificate. It will be called for\n * every certificate in the chain. It has the following signature:\n *\n * variable func(c, certs, index, preVerify)\n * Where:\n * c The TLS connection\n * verified Set to true if certificate was verified, otherwise the alert\n * tls.Alert.Description for why the certificate failed.\n * depth The current index in the chain, where 0 is the server's cert.\n * certs The certificate chain, *NOTE* if the server was anonymous then\n * the chain will be empty.\n *\n * The function returns true on success and on failure either the appropriate\n * tls.Alert.Description or an object with 'alert' set to the appropriate\n * tls.Alert.Description and 'message' set to a custom error message. If true\n * is not returned then the connection will abort using, in order of\n * availability, first the returned alert description, second the preVerify\n * alert description, and lastly the default 'bad_certificate'.\n *\n * There are three callbacks that can be used to make use of client-side\n * certificates where each takes the TLS connection as the first parameter:\n *\n * getCertificate(conn, hint)\n * The second parameter is a hint as to which certificate should be\n * returned. If the connection entity is a client, then the hint will be\n * the CertificateRequest message from the server that is part of the\n * TLS protocol. If the connection entity is a server, then it will be\n * the servername list provided via an SNI extension the ClientHello, if\n * one was provided (empty array if not). The hint can be examined to\n * determine which certificate to use (advanced). Most implementations\n * will just return a certificate. The return value must be a\n * PEM-formatted certificate or an array of PEM-formatted certificates\n * that constitute a certificate chain, with the first in the array/chain\n * being the client's certificate.\n * getPrivateKey(conn, certificate)\n * The second parameter is an forge.pki X.509 certificate object that\n * is associated with the requested private key. The return value must\n * be a PEM-formatted private key.\n * getSignature(conn, bytes, callback)\n * This callback can be used instead of getPrivateKey if the private key\n * is not directly accessible in javascript or should not be. For\n * instance, a secure external web service could provide the signature\n * in exchange for appropriate credentials. The second parameter is a\n * string of bytes to be signed that are part of the TLS protocol. These\n * bytes are used to verify that the private key for the previously\n * provided client-side certificate is accessible to the client. The\n * callback is a function that takes 2 parameters, the TLS connection\n * and the RSA encrypted (signed) bytes as a string. This callback must\n * be called once the signature is ready.\n *\n * @param options the options for this connection:\n * server: true if the connection is server-side, false for client.\n * sessionId: a session ID to reuse, null for a new connection.\n * caStore: an array of certificates to trust.\n * sessionCache: a session cache to use.\n * cipherSuites: an optional array of cipher suites to use,\n * see tls.CipherSuites.\n * connected: function(conn) called when the first handshake completes.\n * virtualHost: the virtual server name to use in a TLS SNI extension.\n * verifyClient: true to require a client certificate in server mode,\n * 'optional' to request one, false not to (default: false).\n * verify: a handler used to custom verify certificates in the chain.\n * verifyOptions: an object with options for the certificate chain validation.\n * See documentation of pki.verifyCertificateChain for possible options.\n * verifyOptions.verify is ignored. If you wish to specify a verify handler\n * use the verify key.\n * getCertificate: an optional callback used to get a certificate or\n * a chain of certificates (as an array).\n * getPrivateKey: an optional callback used to get a private key.\n * getSignature: an optional callback used to get a signature.\n * tlsDataReady: function(conn) called when TLS protocol data has been\n * prepared and is ready to be used (typically sent over a socket\n * connection to its destination), read from conn.tlsData buffer.\n * dataReady: function(conn) called when application data has\n * been parsed from a TLS record and should be consumed by the\n * application, read from conn.data buffer.\n * closed: function(conn) called when the connection has been closed.\n * error: function(conn, error) called when there was an error.\n * deflate: function(inBytes) if provided, will deflate TLS records using\n * the deflate algorithm if the server supports it.\n * inflate: function(inBytes) if provided, will inflate TLS records using\n * the deflate algorithm if the server supports it.\n *\n * @return the new TLS connection.\n */\nforge.tls.createConnection = tls.createConnection;\n","/**\n * A Javascript implementation of AES Cipher Suites for TLS.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2009-2015 Digital Bazaar, Inc.\n *\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./tls');\n\nvar tls = module.exports = forge.tls;\n\n/**\n * Supported cipher suites.\n */\ntls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = {\n id: [0x00, 0x2f],\n name: 'TLS_RSA_WITH_AES_128_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 16;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\ntls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = {\n id: [0x00, 0x35],\n name: 'TLS_RSA_WITH_AES_256_CBC_SHA',\n initSecurityParameters: function(sp) {\n sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;\n sp.cipher_type = tls.CipherType.block;\n sp.enc_key_length = 32;\n sp.block_length = 16;\n sp.fixed_iv_length = 16;\n sp.record_iv_length = 16;\n sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;\n sp.mac_length = 20;\n sp.mac_key_length = 20;\n },\n initConnectionState: initConnectionState\n};\n\nfunction initConnectionState(state, c, sp) {\n var client = (c.entity === forge.tls.ConnectionEnd.client);\n\n // cipher setup\n state.read.cipherState = {\n init: false,\n cipher: forge.cipher.createDecipher('AES-CBC', client ?\n sp.keys.server_write_key : sp.keys.client_write_key),\n iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV\n };\n state.write.cipherState = {\n init: false,\n cipher: forge.cipher.createCipher('AES-CBC', client ?\n sp.keys.client_write_key : sp.keys.server_write_key),\n iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV\n };\n state.read.cipherFunction = decrypt_aes_cbc_sha1;\n state.write.cipherFunction = encrypt_aes_cbc_sha1;\n\n // MAC setup\n state.read.macLength = state.write.macLength = sp.mac_length;\n state.read.macFunction = state.write.macFunction = tls.hmac_sha1;\n}\n\n/**\n * Encrypts the TLSCompressed record into a TLSCipherText record using AES\n * in CBC mode.\n *\n * @param record the TLSCompressed record to encrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n // append MAC to fragment, update sequence number\n var mac = s.macFunction(s.macKey, s.sequenceNumber, record);\n record.fragment.putBytes(mac);\n s.updateSequenceNumber();\n\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use the pre-generated IV when initializing for TLS 1.0, otherwise use\n // the residue from the previous encryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n iv = forge.random.getBytesSync(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // TLS 1.1+ write IV into output\n if(record.version.minor >= tls.Versions.TLS_1_1.minor) {\n cipher.output.putBytes(iv);\n }\n\n // do encryption (default padding is appropriate)\n cipher.update(record.fragment);\n if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {\n // set record fragment to encrypted output\n record.fragment = cipher.output;\n record.length = record.fragment.length();\n rval = true;\n }\n\n return rval;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in encrypt mode.\n *\n * @param blockSize the block size.\n * @param input the input buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) {\n /* The encrypted data length (TLSCiphertext.length) is one more than the sum\n of SecurityParameters.block_length, TLSCompressed.length,\n SecurityParameters.mac_length, and padding_length.\n\n The padding may be any length up to 255 bytes long, as long as it results in\n the TLSCiphertext.length being an integral multiple of the block length.\n Lengths longer than necessary might be desirable to frustrate attacks on a\n protocol based on analysis of the lengths of exchanged messages. Each uint8\n in the padding data vector must be filled with the padding length value.\n\n The padding length should be such that the total size of the\n GenericBlockCipher structure is a multiple of the cipher's block length.\n Legal values range from zero to 255, inclusive. This length specifies the\n length of the padding field exclusive of the padding_length field itself.\n\n This is slightly different from PKCS#7 because the padding value is 1\n less than the actual number of padding bytes if you include the\n padding_length uint8 itself as a padding byte. */\n if(!decrypt) {\n // get the number of padding bytes required to reach the blockSize and\n // subtract 1 for the padding value (to make room for the padding_length\n // uint8)\n var padding = blockSize - (input.length() % blockSize);\n input.fillWithByte(padding - 1, padding);\n }\n return true;\n}\n\n/**\n * Handles padding for aes_cbc_sha1 in decrypt mode.\n *\n * @param blockSize the block size.\n * @param output the output buffer.\n * @param decrypt true in decrypt mode, false in encrypt mode.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {\n var rval = true;\n if(decrypt) {\n /* The last byte in the output specifies the number of padding bytes not\n including itself. Each of the padding bytes has the same value as that\n last byte (known as the padding_length). Here we check all padding\n bytes to ensure they have the value of padding_length even if one of\n them is bad in order to ward-off timing attacks. */\n var len = output.length();\n var paddingLength = output.last();\n for(var i = len - 1 - paddingLength; i < len - 1; ++i) {\n rval = rval && (output.at(i) == paddingLength);\n }\n if(rval) {\n // trim off padding bytes and last padding length byte\n output.truncate(paddingLength + 1);\n }\n }\n return rval;\n}\n\n/**\n * Decrypts a TLSCipherText record into a TLSCompressed record using\n * AES in CBC mode.\n *\n * @param record the TLSCipherText record to decrypt.\n * @param s the ConnectionState to use.\n *\n * @return true on success, false on failure.\n */\nfunction decrypt_aes_cbc_sha1(record, s) {\n var rval = false;\n\n var iv;\n if(record.version.minor === tls.Versions.TLS_1_0.minor) {\n // use pre-generated IV when initializing for TLS 1.0, otherwise use the\n // residue from the previous decryption\n iv = s.cipherState.init ? null : s.cipherState.iv;\n } else {\n // TLS 1.1+ use an explicit IV every time to protect against CBC attacks\n // that is appended to the record fragment\n iv = record.fragment.getBytes(16);\n }\n\n s.cipherState.init = true;\n\n // start cipher\n var cipher = s.cipherState.cipher;\n cipher.start({iv: iv});\n\n // do decryption\n cipher.update(record.fragment);\n rval = cipher.finish(decrypt_aes_cbc_sha1_padding);\n\n // even if decryption fails, keep going to minimize timing attacks\n\n // decrypted data:\n // first (len - 20) bytes = application data\n // last 20 bytes = MAC\n var macLen = s.macLength;\n\n // create a random MAC to check against should the mac length check fail\n // Note: do this regardless of the failure to keep timing consistent\n var mac = forge.random.getBytesSync(macLen);\n\n // get fragment and mac\n var len = cipher.output.length();\n if(len >= macLen) {\n record.fragment = cipher.output.getBytes(len - macLen);\n mac = cipher.output.getBytes(macLen);\n } else {\n // bad data, but get bytes anyway to try to keep timing consistent\n record.fragment = cipher.output.getBytes();\n }\n record.fragment = forge.util.createBuffer(record.fragment);\n record.length = record.fragment.length();\n\n // see if data integrity checks out, update sequence number\n var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record);\n s.updateSequenceNumber();\n rval = compareMacs(s.macKey, mac, mac2) && rval;\n return rval;\n}\n\n/**\n * Safely compare two MACs. This function will compare two MACs in a way\n * that protects against timing attacks.\n *\n * TODO: Expose elsewhere as a utility API.\n *\n * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/\n *\n * @param key the MAC key to use.\n * @param mac1 as a binary-encoded string of bytes.\n * @param mac2 as a binary-encoded string of bytes.\n *\n * @return true if the MACs are the same, false if not.\n */\nfunction compareMacs(key, mac1, mac2) {\n var hmac = forge.hmac.create();\n\n hmac.start('SHA1', key);\n hmac.update(mac1);\n mac1 = hmac.digest().getBytes();\n\n hmac.start(null, null);\n hmac.update(mac2);\n mac2 = hmac.digest().getBytes();\n\n return mac1 === mac2;\n}\n","/**\n * Debugging support for web applications.\n *\n * @author David I. Lehn \n *\n * Copyright 2008-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\n\n/* DEBUG API */\nmodule.exports = forge.debug = forge.debug || {};\n\n// Private storage for debugging.\n// Useful to expose data that is otherwise unviewable behind closures.\n// NOTE: remember that this can hold references to data and cause leaks!\n// format is \"forge._debug.. = data\"\n// Example:\n// (function() {\n// var cat = 'forge.test.Test'; // debugging category\n// var sState = {...}; // local state\n// forge.debug.set(cat, 'sState', sState);\n// })();\nforge.debug.storage = {};\n\n/**\n * Gets debug data. Omit name for all cat data Omit name and cat for\n * all data.\n *\n * @param cat name of debugging category.\n * @param name name of data to get (optional).\n * @return object with requested debug data or undefined.\n */\nforge.debug.get = function(cat, name) {\n var rval;\n if(typeof(cat) === 'undefined') {\n rval = forge.debug.storage;\n } else if(cat in forge.debug.storage) {\n if(typeof(name) === 'undefined') {\n rval = forge.debug.storage[cat];\n } else {\n rval = forge.debug.storage[cat][name];\n }\n }\n return rval;\n};\n\n/**\n * Sets debug data.\n *\n * @param cat name of debugging category.\n * @param name name of data to set.\n * @param data data to set.\n */\nforge.debug.set = function(cat, name, data) {\n if(!(cat in forge.debug.storage)) {\n forge.debug.storage[cat] = {};\n }\n forge.debug.storage[cat][name] = data;\n};\n\n/**\n * Clears debug data. Omit name for all cat data. Omit name and cat for\n * all data.\n *\n * @param cat name of debugging category.\n * @param name name of data to clear or omit to clear entire category.\n */\nforge.debug.clear = function(cat, name) {\n if(typeof(cat) === 'undefined') {\n forge.debug.storage = {};\n } else if(cat in forge.debug.storage) {\n if(typeof(name) === 'undefined') {\n delete forge.debug.storage[cat];\n } else {\n delete forge.debug.storage[cat][name];\n }\n }\n};\n","/**\n * Secure Hash Algorithm with a 1024-bit block size implementation.\n *\n * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For\n * SHA-256 (block size 512 bits), see sha256.js.\n *\n * See FIPS 180-4 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2014-2015 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./md');\nrequire('./util');\n\nvar sha512 = module.exports = forge.sha512 = forge.sha512 || {};\n\n// SHA-512\nforge.md.sha512 = forge.md.algorithms.sha512 = sha512;\n\n// SHA-384\nvar sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};\nsha384.create = function() {\n return sha512.create('SHA-384');\n};\nforge.md.sha384 = forge.md.algorithms.sha384 = sha384;\n\n// SHA-512/256\nforge.sha512.sha256 = forge.sha512.sha256 || {\n create: function() {\n return sha512.create('SHA-512/256');\n }\n};\nforge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =\n forge.sha512.sha256;\n\n// SHA-512/224\nforge.sha512.sha224 = forge.sha512.sha224 || {\n create: function() {\n return sha512.create('SHA-512/224');\n }\n};\nforge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =\n forge.sha512.sha224;\n\n/**\n * Creates a SHA-2 message digest object.\n *\n * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,\n * SHA-512/256).\n *\n * @return a message digest object.\n */\nsha512.create = function(algorithm) {\n // do initialization as necessary\n if(!_initialized) {\n _init();\n }\n\n if(typeof algorithm === 'undefined') {\n algorithm = 'SHA-512';\n }\n\n if(!(algorithm in _states)) {\n throw new Error('Invalid SHA-512 algorithm: ' + algorithm);\n }\n\n // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)\n var _state = _states[algorithm];\n var _h = null;\n\n // input buffer\n var _input = forge.util.createBuffer();\n\n // used for 64-bit word storage\n var _w = new Array(80);\n for(var wi = 0; wi < 80; ++wi) {\n _w[wi] = new Array(2);\n }\n\n // determine digest length by algorithm name (default)\n var digestLength = 64;\n switch(algorithm) {\n case 'SHA-384':\n digestLength = 48;\n break;\n case 'SHA-512/256':\n digestLength = 32;\n break;\n case 'SHA-512/224':\n digestLength = 28;\n break;\n }\n\n // message digest object\n var md = {\n // SHA-512 => sha512\n algorithm: algorithm.replace('-', '').toLowerCase(),\n blockLength: 128,\n digestLength: digestLength,\n // 56-bit length of message so far (does not including padding)\n messageLength: 0,\n // true message length\n fullMessageLength: null,\n // size of message length in bytes\n messageLengthSize: 16\n };\n\n /**\n * Starts the digest.\n *\n * @return this digest object.\n */\n md.start = function() {\n // up to 56-bit message length for convenience\n md.messageLength = 0;\n\n // full message length (set md.messageLength128 for backwards-compatibility)\n md.fullMessageLength = md.messageLength128 = [];\n var int32s = md.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n md.fullMessageLength.push(0);\n }\n _input = forge.util.createBuffer();\n _h = new Array(_state.length);\n for(var i = 0; i < _state.length; ++i) {\n _h[i] = _state[i].slice(0);\n }\n return md;\n };\n // start digest automatically for first time\n md.start();\n\n /**\n * Updates the digest with the given message input. The given input can\n * treated as raw input (no encoding will be applied) or an encoding of\n * 'utf8' maybe given to encode the input using UTF-8.\n *\n * @param msg the message input to update with.\n * @param encoding the encoding to use (default: 'raw', other: 'utf8').\n *\n * @return this digest object.\n */\n md.update = function(msg, encoding) {\n if(encoding === 'utf8') {\n msg = forge.util.encodeUtf8(msg);\n }\n\n // update message length\n var len = msg.length;\n md.messageLength += len;\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {\n md.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);\n md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n _input.putBytes(msg);\n\n // process bytes\n _update(_h, _w, _input);\n\n // compact input buffer every 2K or if empty\n if(_input.read > 2048 || _input.length() === 0) {\n _input.compact();\n }\n\n return md;\n };\n\n /**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\n md.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and\n add the appropriate SHA-512 padding. Then we do the final update\n on a copy of the state so that if the user wants to get\n intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message\n to ensure its length is congruent to 896 mod 1024. In other words,\n the data to be digested must be a multiple of 1024 bits (or 128 bytes).\n This data includes the message, some padding, and the length of the\n message. Since the length of the message will be encoded as 16 bytes (128\n bits), that means that the last segment of the data must have 112 bytes\n (896 bits) of message and padding. Therefore, the length of the message\n plus the padding must be congruent to 896 mod 1024 because\n 1024 - 128 = 896.\n\n In order to fill up the message length it must be filled with\n padding that begins with 1 bit followed by all 0 bits. Padding\n must *always* be present, so if the message length is already\n congruent to 896 mod 1024, then 1024 padding bits must be added. */\n\n var finalBlock = forge.util.createBuffer();\n finalBlock.putBytes(_input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n md.fullMessageLength[md.fullMessageLength.length - 1] +\n md.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (md.blockLength - 1);\n finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 and add carry from next int\n var next, carry;\n var bits = md.fullMessageLength[0] * 8;\n for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {\n next = md.fullMessageLength[i + 1] * 8;\n carry = (next / 0x100000000) >>> 0;\n bits += carry;\n finalBlock.putInt32(bits >>> 0);\n bits = next >>> 0;\n }\n finalBlock.putInt32(bits);\n\n var h = new Array(_h.length);\n for(var i = 0; i < _h.length; ++i) {\n h[i] = _h[i].slice(0);\n }\n _update(h, _w, finalBlock);\n var rval = forge.util.createBuffer();\n var hlen;\n if(algorithm === 'SHA-512') {\n hlen = h.length;\n } else if(algorithm === 'SHA-384') {\n hlen = h.length - 2;\n } else {\n hlen = h.length - 4;\n }\n for(var i = 0; i < hlen; ++i) {\n rval.putInt32(h[i][0]);\n if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {\n rval.putInt32(h[i][1]);\n }\n }\n return rval;\n };\n\n return md;\n};\n\n// sha-512 padding bytes not initialized yet\nvar _padding = null;\nvar _initialized = false;\n\n// table of constants\nvar _k = null;\n\n// initial hash states\nvar _states = null;\n\n/**\n * Initializes the constant tables.\n */\nfunction _init() {\n // create padding\n _padding = String.fromCharCode(128);\n _padding += forge.util.fillString(String.fromCharCode(0x00), 128);\n\n // create K table for SHA-512\n _k = [\n [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd],\n [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc],\n [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019],\n [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118],\n [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe],\n [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2],\n [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1],\n [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694],\n [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3],\n [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65],\n [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483],\n [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5],\n [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210],\n [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4],\n [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725],\n [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70],\n [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926],\n [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df],\n [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8],\n [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b],\n [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001],\n [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30],\n [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910],\n [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8],\n [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53],\n [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8],\n [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb],\n [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3],\n [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60],\n [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec],\n [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9],\n [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b],\n [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207],\n [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178],\n [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6],\n [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b],\n [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493],\n [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c],\n [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a],\n [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817]\n ];\n\n // initial hash states\n _states = {};\n _states['SHA-512'] = [\n [0x6a09e667, 0xf3bcc908],\n [0xbb67ae85, 0x84caa73b],\n [0x3c6ef372, 0xfe94f82b],\n [0xa54ff53a, 0x5f1d36f1],\n [0x510e527f, 0xade682d1],\n [0x9b05688c, 0x2b3e6c1f],\n [0x1f83d9ab, 0xfb41bd6b],\n [0x5be0cd19, 0x137e2179]\n ];\n _states['SHA-384'] = [\n [0xcbbb9d5d, 0xc1059ed8],\n [0x629a292a, 0x367cd507],\n [0x9159015a, 0x3070dd17],\n [0x152fecd8, 0xf70e5939],\n [0x67332667, 0xffc00b31],\n [0x8eb44a87, 0x68581511],\n [0xdb0c2e0d, 0x64f98fa7],\n [0x47b5481d, 0xbefa4fa4]\n ];\n _states['SHA-512/256'] = [\n [0x22312194, 0xFC2BF72C],\n [0x9F555FA3, 0xC84C64C2],\n [0x2393B86B, 0x6F53B151],\n [0x96387719, 0x5940EABD],\n [0x96283EE2, 0xA88EFFE3],\n [0xBE5E1E25, 0x53863992],\n [0x2B0199FC, 0x2C85B8AA],\n [0x0EB72DDC, 0x81C52CA2]\n ];\n _states['SHA-512/224'] = [\n [0x8C3D37C8, 0x19544DA2],\n [0x73E19966, 0x89DCD4D6],\n [0x1DFAB7AE, 0x32FF9C82],\n [0x679DD514, 0x582F9FCF],\n [0x0F6D2B69, 0x7BD44DA8],\n [0x77E36F73, 0x04C48942],\n [0x3F9D85A8, 0x6A1D36C8],\n [0x1112E6AD, 0x91D692A1]\n ];\n\n // now initialized\n _initialized = true;\n}\n\n/**\n * Updates a SHA-512 state with the given byte buffer.\n *\n * @param s the SHA-512 state to update.\n * @param w the array to use to store words.\n * @param bytes the byte buffer to update with.\n */\nfunction _update(s, w, bytes) {\n // consume 512 bit (128 byte) chunks\n var t1_hi, t1_lo;\n var t2_hi, t2_lo;\n var s0_hi, s0_lo;\n var s1_hi, s1_lo;\n var ch_hi, ch_lo;\n var maj_hi, maj_lo;\n var a_hi, a_lo;\n var b_hi, b_lo;\n var c_hi, c_lo;\n var d_hi, d_lo;\n var e_hi, e_lo;\n var f_hi, f_lo;\n var g_hi, g_lo;\n var h_hi, h_lo;\n var i, hi, lo, w2, w7, w15, w16;\n var len = bytes.length();\n while(len >= 128) {\n // the w array will be populated with sixteen 64-bit big-endian words\n // and then extended into 64 64-bit words according to SHA-512\n for(i = 0; i < 16; ++i) {\n w[i][0] = bytes.getInt32() >>> 0;\n w[i][1] = bytes.getInt32() >>> 0;\n }\n for(; i < 80; ++i) {\n // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)\n w2 = w[i - 2];\n hi = w2[0];\n lo = w2[1];\n\n // high bits\n t1_hi = (\n ((hi >>> 19) | (lo << 13)) ^ // ROTR 19\n ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)\n (hi >>> 6)) >>> 0; // SHR 6\n // low bits\n t1_lo = (\n ((hi << 13) | (lo >>> 19)) ^ // ROTR 19\n ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)\n ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6\n\n // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)\n w15 = w[i - 15];\n hi = w15[0];\n lo = w15[1];\n\n // high bits\n t2_hi = (\n ((hi >>> 1) | (lo << 31)) ^ // ROTR 1\n ((hi >>> 8) | (lo << 24)) ^ // ROTR 8\n (hi >>> 7)) >>> 0; // SHR 7\n // low bits\n t2_lo = (\n ((hi << 31) | (lo >>> 1)) ^ // ROTR 1\n ((hi << 24) | (lo >>> 8)) ^ // ROTR 8\n ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7\n\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)\n w7 = w[i - 7];\n w16 = w[i - 16];\n lo = (t1_lo + w7[1] + t2_lo + w16[1]);\n w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n w[i][1] = lo >>> 0;\n }\n\n // initialize hash value for this chunk\n a_hi = s[0][0];\n a_lo = s[0][1];\n b_hi = s[1][0];\n b_lo = s[1][1];\n c_hi = s[2][0];\n c_lo = s[2][1];\n d_hi = s[3][0];\n d_lo = s[3][1];\n e_hi = s[4][0];\n e_lo = s[4][1];\n f_hi = s[5][0];\n f_lo = s[5][1];\n g_hi = s[6][0];\n g_lo = s[6][1];\n h_hi = s[7][0];\n h_lo = s[7][1];\n\n // round function\n for(i = 0; i < 80; ++i) {\n // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)\n s1_hi = (\n ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14\n ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18\n ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)\n s1_lo = (\n ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14\n ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18\n ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)\n\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;\n ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;\n\n // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)\n s0_hi = (\n ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28\n ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)\n s0_lo = (\n ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28\n ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)\n ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)\n\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;\n maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;\n\n // main algorithm\n // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)\n lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);\n t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +\n ((lo / 0x100000000) >>> 0)) >>> 0;\n t1_lo = lo >>> 0;\n\n // t2 = s0 + maj modulo 2^64 (carry lo overflow)\n lo = s0_lo + maj_lo;\n t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n t2_lo = lo >>> 0;\n\n h_hi = g_hi;\n h_lo = g_lo;\n\n g_hi = f_hi;\n g_lo = f_lo;\n\n f_hi = e_hi;\n f_lo = e_lo;\n\n // e = (d + t1) modulo 2^64 (carry lo overflow)\n lo = d_lo + t1_lo;\n e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n e_lo = lo >>> 0;\n\n d_hi = c_hi;\n d_lo = c_lo;\n\n c_hi = b_hi;\n c_lo = b_lo;\n\n b_hi = a_hi;\n b_lo = a_lo;\n\n // a = (t1 + t2) modulo 2^64 (carry lo overflow)\n lo = t1_lo + t2_lo;\n a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n a_lo = lo >>> 0;\n }\n\n // update hash state (additional modulo 2^64)\n lo = s[0][1] + a_lo;\n s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[0][1] = lo >>> 0;\n\n lo = s[1][1] + b_lo;\n s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[1][1] = lo >>> 0;\n\n lo = s[2][1] + c_lo;\n s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[2][1] = lo >>> 0;\n\n lo = s[3][1] + d_lo;\n s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[3][1] = lo >>> 0;\n\n lo = s[4][1] + e_lo;\n s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[4][1] = lo >>> 0;\n\n lo = s[5][1] + f_lo;\n s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[5][1] = lo >>> 0;\n\n lo = s[6][1] + g_lo;\n s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[6][1] = lo >>> 0;\n\n lo = s[7][1] + h_lo;\n s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;\n s[7][1] = lo >>> 0;\n\n len -= 128;\n }\n}\n","/**\n * Copyright (c) 2019 Digital Bazaar, Inc.\n */\n\nvar forge = require('./forge');\nrequire('./asn1');\nvar asn1 = forge.asn1;\n\nexports.privateKeyValidator = {\n // PrivateKeyInfo\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n // Version (INTEGER)\n name: 'PrivateKeyInfo.version',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.INTEGER,\n constructed: false,\n capture: 'privateKeyVersion'\n }, {\n // privateKeyAlgorithm\n name: 'PrivateKeyInfo.privateKeyAlgorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'privateKeyOid'\n }]\n }, {\n // PrivateKey\n name: 'PrivateKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OCTETSTRING,\n constructed: false,\n capture: 'privateKey'\n }]\n};\n\nexports.publicKeyValidator = {\n name: 'SubjectPublicKeyInfo',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n captureAsn1: 'subjectPublicKeyInfo',\n value: [{\n name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n value: [{\n name: 'AlgorithmIdentifier.algorithm',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.OID,\n constructed: false,\n capture: 'publicKeyOid'\n }]\n },\n // capture group for ed25519PublicKey\n {\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n composed: true,\n captureBitStringValue: 'ed25519PublicKey'\n }\n // FIXME: this is capture group for rsaPublicKey, use it in this API or\n // discard?\n /* {\n // subjectPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.BITSTRING,\n constructed: false,\n value: [{\n // RSAPublicKey\n name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',\n tagClass: asn1.Class.UNIVERSAL,\n type: asn1.Type.SEQUENCE,\n constructed: true,\n optional: true,\n captureAsn1: 'rsaPublicKey'\n }]\n } */\n ]\n};\n","/**\n * JavaScript implementation of Ed25519.\n *\n * Copyright (c) 2017-2019 Digital Bazaar, Inc.\n *\n * This implementation is based on the most excellent TweetNaCl which is\n * in the public domain. Many thanks to its contributors:\n *\n * https://github.com/dchest/tweetnacl-js\n */\nvar forge = require('./forge');\nrequire('./jsbn');\nrequire('./random');\nrequire('./sha512');\nrequire('./util');\nvar asn1Validator = require('./asn1-validator');\nvar publicKeyValidator = asn1Validator.publicKeyValidator;\nvar privateKeyValidator = asn1Validator.privateKeyValidator;\n\nif(typeof BigInteger === 'undefined') {\n var BigInteger = forge.jsbn.BigInteger;\n}\n\nvar ByteBuffer = forge.util.ByteBuffer;\nvar NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer;\n\n/*\n * Ed25519 algorithms, see RFC 8032:\n * https://tools.ietf.org/html/rfc8032\n */\nforge.pki = forge.pki || {};\nmodule.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {};\nvar ed25519 = forge.ed25519;\n\ned25519.constants = {};\ned25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;\ned25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;\ned25519.constants.SEED_BYTE_LENGTH = 32;\ned25519.constants.SIGN_BYTE_LENGTH = 64;\ned25519.constants.HASH_BYTE_LENGTH = 64;\n\ned25519.generateKeyPair = function(options) {\n options = options || {};\n var seed = options.seed;\n if(seed === undefined) {\n // generate seed\n seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);\n } else if(typeof seed === 'string') {\n if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {\n throw new TypeError(\n '\"seed\" must be ' + ed25519.constants.SEED_BYTE_LENGTH +\n ' bytes in length.');\n }\n } else if(!(seed instanceof Uint8Array)) {\n throw new TypeError(\n '\"seed\" must be a node.js Buffer, Uint8Array, or a binary string.');\n }\n\n seed = messageToNativeBuffer({message: seed, encoding: 'binary'});\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n for(var i = 0; i < 32; ++i) {\n sk[i] = seed[i];\n }\n crypto_sign_keypair(pk, sk);\n return {publicKey: pk, privateKey: sk};\n};\n\n/**\n * Converts a private key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a private key.\n *\n * @returns {Object} keyInfo - The key information.\n * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes.\n */\ned25519.privateKeyFromAsn1 = function(obj) {\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.privateKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var privateKey = capture.privateKey;\n // manually extract the private key bytes from nested octet string, see FIXME:\n // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542\n var privateKeyBytes = messageToNativeBuffer({\n message: forge.asn1.fromDer(privateKey).value,\n encoding: 'binary'\n });\n // TODO: RFC8410 specifies a format for encoding the public key bytes along\n // with the private key bytes. `publicKeyBytes` can be returned in the\n // future. https://tools.ietf.org/html/rfc8410#section-10.3\n return {privateKeyBytes: privateKeyBytes};\n};\n\n/**\n * Converts a public key from a RFC8410 ASN.1 encoding.\n *\n * @param obj - The asn1 representation of a public key.\n *\n * @return {Buffer|Uint8Array} - 32 public key bytes.\n */\ned25519.publicKeyFromAsn1 = function(obj) {\n // get SubjectPublicKeyInfo\n var capture = {};\n var errors = [];\n var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors);\n if(!valid) {\n var error = new Error('Invalid Key.');\n error.errors = errors;\n throw error;\n }\n var oid = forge.asn1.derToOid(capture.publicKeyOid);\n var ed25519Oid = forge.oids.EdDSA25519;\n if(oid !== ed25519Oid) {\n throw new Error('Invalid OID \"' + oid + '\"; OID must be \"' +\n ed25519Oid + '\".');\n }\n var publicKeyBytes = capture.ed25519PublicKey;\n if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new Error('Key length is invalid.');\n }\n return messageToNativeBuffer({\n message: publicKeyBytes,\n encoding: 'binary'\n });\n};\n\ned25519.publicKeyFromPrivateKey = function(options) {\n options = options || {};\n var privateKey = messageToNativeBuffer({\n message: options.privateKey, encoding: 'binary'\n });\n if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n for(var i = 0; i < pk.length; ++i) {\n pk[i] = privateKey[32 + i];\n }\n return pk;\n};\n\ned25519.sign = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n var privateKey = messageToNativeBuffer({\n message: options.privateKey,\n encoding: 'binary'\n });\n if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {\n var keyPair = ed25519.generateKeyPair({seed: privateKey});\n privateKey = keyPair.privateKey;\n } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.privateKey\" must have a byte length of ' +\n ed25519.constants.SEED_BYTE_LENGTH + ' or ' +\n ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);\n }\n\n var signedMsg = new NativeBuffer(\n ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n crypto_sign(signedMsg, msg, msg.length, privateKey);\n\n var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);\n for(var i = 0; i < sig.length; ++i) {\n sig[i] = signedMsg[i];\n }\n return sig;\n};\n\ned25519.verify = function(options) {\n options = options || {};\n var msg = messageToNativeBuffer(options);\n if(options.signature === undefined) {\n throw new TypeError(\n '\"options.signature\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a binary string.');\n }\n var sig = messageToNativeBuffer({\n message: options.signature,\n encoding: 'binary'\n });\n if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.signature\" must have a byte length of ' +\n ed25519.constants.SIGN_BYTE_LENGTH);\n }\n var publicKey = messageToNativeBuffer({\n message: options.publicKey,\n encoding: 'binary'\n });\n if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {\n throw new TypeError(\n '\"options.publicKey\" must have a byte length of ' +\n ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);\n }\n\n var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);\n var i;\n for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) {\n sm[i] = sig[i];\n }\n for(i = 0; i < msg.length; ++i) {\n sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i];\n }\n return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);\n};\n\nfunction messageToNativeBuffer(options) {\n var message = options.message;\n if(message instanceof Uint8Array || message instanceof NativeBuffer) {\n return message;\n }\n\n var encoding = options.encoding;\n if(message === undefined) {\n if(options.md) {\n // TODO: more rigorous validation that `md` is a MessageDigest\n message = options.md.digest().getBytes();\n encoding = 'binary';\n } else {\n throw new TypeError('\"options.message\" or \"options.md\" not specified.');\n }\n }\n\n if(typeof message === 'string' && !encoding) {\n throw new TypeError('\"options.encoding\" must be \"binary\" or \"utf8\".');\n }\n\n if(typeof message === 'string') {\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(message, encoding);\n }\n message = new ByteBuffer(message, encoding);\n } else if(!(message instanceof ByteBuffer)) {\n throw new TypeError(\n '\"options.message\" must be a node.js Buffer, a Uint8Array, a forge ' +\n 'ByteBuffer, or a string with \"options.encoding\" specifying its ' +\n 'encoding.');\n }\n\n // convert to native buffer\n var buffer = new NativeBuffer(message.length());\n for(var i = 0; i < buffer.length; ++i) {\n buffer[i] = message.at(i);\n }\n return buffer;\n}\n\nvar gf0 = gf();\nvar gf1 = gf([1]);\nvar D = gf([\n 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,\n 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]);\nvar D2 = gf([\n 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,\n 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]);\nvar X = gf([\n 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,\n 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]);\nvar Y = gf([\n 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,\n 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]);\nvar L = new Float64Array([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,\n 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);\nvar I = gf([\n 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,\n 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);\n\n// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`,\n// whichever is available, to improve performance\nfunction sha512(msg, msgLen) {\n // Note: `out` and `msg` are NativeBuffer\n var md = forge.md.sha512.create();\n var buffer = new ByteBuffer(msg);\n md.update(buffer.getBytes(msgLen), 'binary');\n var hash = md.digest().getBytes();\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(hash, 'binary');\n }\n var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);\n for(var i = 0; i < 64; ++i) {\n out[i] = hash.charCodeAt(i);\n }\n return out;\n}\n\nfunction crypto_sign_keypair(pk, sk) {\n var p = [gf(), gf(), gf(), gf()];\n var i;\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n scalarbase(p, d);\n pack(pk, p);\n\n for(i = 0; i < 32; ++i) {\n sk[i + 32] = pk[i];\n }\n return 0;\n}\n\n// Note: difference from C - smlen returned, not passed as argument.\nfunction crypto_sign(sm, m, n, sk) {\n var i, j, x = new Float64Array(64);\n var p = [gf(), gf(), gf(), gf()];\n\n var d = sha512(sk, 32);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n var smlen = n + 64;\n for(i = 0; i < n; ++i) {\n sm[64 + i] = m[i];\n }\n for(i = 0; i < 32; ++i) {\n sm[32 + i] = d[32 + i];\n }\n\n var r = sha512(sm.subarray(32), n + 32);\n reduce(r);\n scalarbase(p, r);\n pack(sm, p);\n\n for(i = 32; i < 64; ++i) {\n sm[i] = sk[i];\n }\n var h = sha512(sm, n + 64);\n reduce(h);\n\n for(i = 32; i < 64; ++i) {\n x[i] = 0;\n }\n for(i = 0; i < 32; ++i) {\n x[i] = r[i];\n }\n for(i = 0; i < 32; ++i) {\n for(j = 0; j < 32; j++) {\n x[i + j] += h[i] * d[j];\n }\n }\n\n modL(sm.subarray(32), x);\n return smlen;\n}\n\nfunction crypto_sign_open(m, sm, n, pk) {\n var i, mlen;\n var t = new NativeBuffer(32);\n var p = [gf(), gf(), gf(), gf()],\n q = [gf(), gf(), gf(), gf()];\n\n mlen = -1;\n if(n < 64) {\n return -1;\n }\n\n if(unpackneg(q, pk)) {\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i];\n }\n for(i = 0; i < 32; ++i) {\n m[i + 32] = pk[i];\n }\n var h = sha512(m, n);\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, sm.subarray(32));\n add(p, q);\n pack(t, p);\n\n n -= 64;\n if(crypto_verify_32(sm, 0, t, 0)) {\n for(i = 0; i < n; ++i) {\n m[i] = 0;\n }\n return -1;\n }\n\n for(i = 0; i < n; ++i) {\n m[i] = sm[i + 64];\n }\n mlen = n;\n return mlen;\n}\n\nfunction modL(r, x) {\n var carry, i, j, k;\n for(i = 63; i >= 32; --i) {\n carry = 0;\n for(j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = (x[j] + 128) >> 8;\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for(j = 0; j < 32; ++j) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for(j = 0; j < 32; ++j) {\n x[j] -= carry * L[j];\n }\n for(i = 0; i < 32; ++i) {\n x[i + 1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r) {\n var x = new Float64Array(64);\n for(var i = 0; i < 64; ++i) {\n x[i] = r[i];\n r[i] = 0;\n }\n modL(r, x);\n}\n\nfunction add(p, q) {\n var a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n Z(a, p[1], p[0]);\n Z(t, q[1], q[0]);\n M(a, a, t);\n A(b, p[0], p[1]);\n A(t, q[0], q[1]);\n M(b, b, t);\n M(c, p[3], q[3]);\n M(c, c, D2);\n M(d, p[2], q[2]);\n A(d, d, d);\n Z(e, b, a);\n Z(f, d, c);\n A(g, d, c);\n A(h, b, a);\n\n M(p[0], e, f);\n M(p[1], h, g);\n M(p[2], g, f);\n M(p[3], e, h);\n}\n\nfunction cswap(p, q, b) {\n for(var i = 0; i < 4; ++i) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r, p) {\n var tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n M(tx, p[0], zi);\n M(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction pack25519(o, n) {\n var i, j, b;\n var m = gf(), t = gf();\n for(i = 0; i < 16; ++i) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for(j = 0; j < 2; ++j) {\n m[0] = t[0] - 0xffed;\n for(i = 1; i < 15; ++i) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i-1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpackneg(r, p) {\n var t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n S(num, r[1]);\n M(den, num, D);\n Z(num, num, r[2]);\n A(den, r[2], den);\n\n S(den2, den);\n S(den4, den2);\n M(den6, den4, den2);\n M(t, den6, num);\n M(t, t, den);\n\n pow2523(t, t);\n M(t, t, num);\n M(t, t, den);\n M(t, t, den);\n M(r[0], t, den);\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n M(r[0], r[0], I);\n }\n\n S(chk, r[0]);\n M(chk, chk, den);\n if(neq25519(chk, num)) {\n return -1;\n }\n\n if(par25519(r[0]) === (p[31] >> 7)) {\n Z(r[0], gf0, r[0]);\n }\n\n M(r[3], r[0], r[1]);\n return 0;\n}\n\nfunction unpack25519(o, n) {\n var i;\n for(i = 0; i < 16; ++i) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction pow2523(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 250; a >= 0; --a) {\n S(c, c);\n if(a !== 1) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction neq25519(a, b) {\n var c = new NativeBuffer(32);\n var d = new NativeBuffer(32);\n pack25519(c, a);\n pack25519(d, b);\n return crypto_verify_32(c, 0, d, 0);\n}\n\nfunction crypto_verify_32(x, xi, y, yi) {\n return vn(x, xi, y, yi, 32);\n}\n\nfunction vn(x, xi, y, yi, n) {\n var i, d = 0;\n for(i = 0; i < n; ++i) {\n d |= x[xi + i] ^ y[yi + i];\n }\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\nfunction par25519(a) {\n var d = new NativeBuffer(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction scalarmult(p, q, s) {\n var b, i;\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for(i = 255; i >= 0; --i) {\n b = (s[(i / 8)|0] >> (i & 7)) & 1;\n cswap(p, q, b);\n add(q, p);\n add(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p, s) {\n var q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n M(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nfunction set25519(r, a) {\n var i;\n for(i = 0; i < 16; i++) {\n r[i] = a[i] | 0;\n }\n}\n\nfunction inv25519(o, i) {\n var c = gf();\n var a;\n for(a = 0; a < 16; ++a) {\n c[a] = i[a];\n }\n for(a = 253; a >= 0; --a) {\n S(c, c);\n if(a !== 2 && a !== 4) {\n M(c, c, i);\n }\n }\n for(a = 0; a < 16; ++a) {\n o[a] = c[a];\n }\n}\n\nfunction car25519(o) {\n var i, v, c = 1;\n for(i = 0; i < 16; ++i) {\n v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p, q, b) {\n var t, c = ~(b - 1);\n for(var i = 0; i < 16; ++i) {\n t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction gf(init) {\n var i, r = new Float64Array(16);\n if(init) {\n for(i = 0; i < init.length; ++i) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\nfunction A(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction Z(o, a, b) {\n for(var i = 0; i < 16; ++i) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction S(o, a) {\n M(o, a, a);\n}\n\nfunction M(o, a, b) {\n var v, c,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c-1 + 37 * (c-1);\n\n o[ 0] = t0;\n o[ 1] = t1;\n o[ 2] = t2;\n o[ 3] = t3;\n o[ 4] = t4;\n o[ 5] = t5;\n o[ 6] = t6;\n o[ 7] = t7;\n o[ 8] = t8;\n o[ 9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n","/**\n * Javascript implementation of RSA-KEM.\n *\n * @author Lautaro Cozzani Rodriguez\n * @author Dave Longley\n *\n * Copyright (c) 2014 Lautaro Cozzani \n * Copyright (c) 2014 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\nrequire('./random');\nrequire('./jsbn');\n\nmodule.exports = forge.kem = forge.kem || {};\n\nvar BigInteger = forge.jsbn.BigInteger;\n\n/**\n * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2.\n */\nforge.kem.rsa = {};\n\n/**\n * Creates an RSA KEM API object for generating a secret asymmetric key.\n *\n * The symmetric key may be generated via a call to 'encrypt', which will\n * produce a ciphertext to be transmitted to the recipient and a key to be\n * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which\n * will produce the same secret key for the recipient to use to decrypt a\n * message that was encrypted with the secret key.\n *\n * @param kdf the KDF API to use (eg: new forge.kem.kdf1()).\n * @param options the options to use.\n * [prng] a custom crypto-secure pseudo-random number generator to use,\n * that must define \"getBytesSync\".\n */\nforge.kem.rsa.create = function(kdf, options) {\n options = options || {};\n var prng = options.prng || forge.random;\n\n var kem = {};\n\n /**\n * Generates a secret key and its encapsulation.\n *\n * @param publicKey the RSA public key to encrypt with.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return an object with:\n * encapsulation: the ciphertext for generating the secret key, as a\n * binary-encoded string of bytes.\n * key: the secret key to use for encrypting a message.\n */\n kem.encrypt = function(publicKey, keyLength) {\n // generate a random r where 1 < r < n\n var byteLength = Math.ceil(publicKey.n.bitLength() / 8);\n var r;\n do {\n r = new BigInteger(\n forge.util.bytesToHex(prng.getBytesSync(byteLength)),\n 16).mod(publicKey.n);\n } while(r.compareTo(BigInteger.ONE) <= 0);\n\n // prepend r with zeros\n r = forge.util.hexToBytes(r.toString(16));\n var zeros = byteLength - r.length;\n if(zeros > 0) {\n r = forge.util.fillString(String.fromCharCode(0), zeros) + r;\n }\n\n // encrypt the random\n var encapsulation = publicKey.encrypt(r, 'NONE');\n\n // generate the secret key\n var key = kdf.generate(r, keyLength);\n\n return {encapsulation: encapsulation, key: key};\n };\n\n /**\n * Decrypts an encapsulated secret key.\n *\n * @param privateKey the RSA private key to decrypt with.\n * @param encapsulation the ciphertext for generating the secret key, as\n * a binary-encoded string of bytes.\n * @param keyLength the length, in bytes, of the secret key to generate.\n *\n * @return the secret key as a binary-encoded string of bytes.\n */\n kem.decrypt = function(privateKey, encapsulation, keyLength) {\n // decrypt the encapsulation and generate the secret key\n var r = privateKey.decrypt(encapsulation, 'NONE');\n return kdf.generate(r, keyLength);\n };\n\n return kem;\n};\n\n// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API?\n\n/**\n * Creates a key derivation API object that implements KDF1 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF1 API object.\n */\nforge.kem.kdf1 = function(md, digestLength) {\n _createKDF(this, md, 0, digestLength || md.digestLength);\n};\n\n/**\n * Creates a key derivation API object that implements KDF2 per ISO 18033-2.\n *\n * @param md the hash API to use.\n * @param [digestLength] an optional digest length that must be positive and\n * less than or equal to md.digestLength.\n *\n * @return a KDF2 API object.\n */\nforge.kem.kdf2 = function(md, digestLength) {\n _createKDF(this, md, 1, digestLength || md.digestLength);\n};\n\n/**\n * Creates a KDF1 or KDF2 API object.\n *\n * @param md the hash API to use.\n * @param counterStart the starting index for the counter.\n * @param digestLength the digest length to use.\n *\n * @return the KDF API object.\n */\nfunction _createKDF(kdf, md, counterStart, digestLength) {\n /**\n * Generate a key of the specified length.\n *\n * @param x the binary-encoded byte string to generate a key from.\n * @param length the number of bytes to generate (the size of the key).\n *\n * @return the key as a binary-encoded string.\n */\n kdf.generate = function(x, length) {\n var key = new forge.util.ByteBuffer();\n\n // run counter from counterStart to ceil(length / Hash.len)\n var k = Math.ceil(length / digestLength) + counterStart;\n\n var c = new forge.util.ByteBuffer();\n for(var i = counterStart; i < k; ++i) {\n // I2OSP(i, 4): convert counter to an octet string of 4 octets\n c.putInt32(i);\n\n // digest 'x' and the counter and add the result to the key\n md.start();\n md.update(x + c.getBytes());\n var hash = md.digest();\n key.putBytes(hash.getBytes(digestLength));\n }\n\n // truncate to the correct key length\n key.truncate(key.length() - length);\n return key.getBytes();\n };\n}\n","/**\n * Cross-browser support for logging in a web application.\n *\n * @author David I. Lehn \n *\n * Copyright (c) 2008-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./util');\n\n/* LOG API */\nmodule.exports = forge.log = forge.log || {};\n\n/**\n * Application logging system.\n *\n * Each logger level available as it's own function of the form:\n * forge.log.level(category, args...)\n * The category is an arbitrary string, and the args are the same as\n * Firebug's console.log API. By default the call will be output as:\n * 'LEVEL [category] , args[1], ...'\n * This enables proper % formatting via the first argument.\n * Each category is enabled by default but can be enabled or disabled with\n * the setCategoryEnabled() function.\n */\n// list of known levels\nforge.log.levels = [\n 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max'];\n// info on the levels indexed by name:\n// index: level index\n// name: uppercased display name\nvar sLevelInfo = {};\n// list of loggers\nvar sLoggers = [];\n/**\n * Standard console logger. If no console support is enabled this will\n * remain null. Check before using.\n */\nvar sConsoleLogger = null;\n\n// logger flags\n/**\n * Lock the level at the current value. Used in cases where user config may\n * set the level such that only critical messages are seen but more verbose\n * messages are needed for debugging or other purposes.\n */\nforge.log.LEVEL_LOCKED = (1 << 1);\n/**\n * Always call log function. By default, the logging system will check the\n * message level against logger.level before calling the log function. This\n * flag allows the function to do its own check.\n */\nforge.log.NO_LEVEL_CHECK = (1 << 2);\n/**\n * Perform message interpolation with the passed arguments. \"%\" style\n * fields in log messages will be replaced by arguments as needed. Some\n * loggers, such as Firebug, may do this automatically. The original log\n * message will be available as 'message' and the interpolated version will\n * be available as 'fullMessage'.\n */\nforge.log.INTERPOLATE = (1 << 3);\n\n// setup each log level\nfor(var i = 0; i < forge.log.levels.length; ++i) {\n var level = forge.log.levels[i];\n sLevelInfo[level] = {\n index: i,\n name: level.toUpperCase()\n };\n}\n\n/**\n * Message logger. Will dispatch a message to registered loggers as needed.\n *\n * @param message message object\n */\nforge.log.logMessage = function(message) {\n var messageLevelIndex = sLevelInfo[message.level].index;\n for(var i = 0; i < sLoggers.length; ++i) {\n var logger = sLoggers[i];\n if(logger.flags & forge.log.NO_LEVEL_CHECK) {\n logger.f(message);\n } else {\n // get logger level\n var loggerLevelIndex = sLevelInfo[logger.level].index;\n // check level\n if(messageLevelIndex <= loggerLevelIndex) {\n // message critical enough, call logger\n logger.f(logger, message);\n }\n }\n }\n};\n\n/**\n * Sets the 'standard' key on a message object to:\n * \"LEVEL [category] \" + message\n *\n * @param message a message log object\n */\nforge.log.prepareStandard = function(message) {\n if(!('standard' in message)) {\n message.standard =\n sLevelInfo[message.level].name +\n //' ' + +message.timestamp +\n ' [' + message.category + '] ' +\n message.message;\n }\n};\n\n/**\n * Sets the 'full' key on a message object to the original message\n * interpolated via % formatting with the message arguments.\n *\n * @param message a message log object.\n */\nforge.log.prepareFull = function(message) {\n if(!('full' in message)) {\n // copy args and insert message at the front\n var args = [message.message];\n args = args.concat([] || message['arguments']);\n // format the message\n message.full = forge.util.format.apply(this, args);\n }\n};\n\n/**\n * Applies both preparseStandard() and prepareFull() to a message object and\n * store result in 'standardFull'.\n *\n * @param message a message log object.\n */\nforge.log.prepareStandardFull = function(message) {\n if(!('standardFull' in message)) {\n // FIXME implement 'standardFull' logging\n forge.log.prepareStandard(message);\n message.standardFull = message.standard;\n }\n};\n\n// create log level functions\nif(true) {\n // levels for which we want functions\n var levels = ['error', 'warning', 'info', 'debug', 'verbose'];\n for(var i = 0; i < levels.length; ++i) {\n // wrap in a function to ensure proper level var is passed\n (function(level) {\n // create function for this level\n forge.log[level] = function(category, message/*, args...*/) {\n // convert arguments to real array, remove category and message\n var args = Array.prototype.slice.call(arguments).slice(2);\n // create message object\n // Note: interpolation and standard formatting is done lazily\n var msg = {\n timestamp: new Date(),\n level: level,\n category: category,\n message: message,\n 'arguments': args\n /*standard*/\n /*full*/\n /*fullMessage*/\n };\n // process this message\n forge.log.logMessage(msg);\n };\n })(levels[i]);\n }\n}\n\n/**\n * Creates a new logger with specified custom logging function.\n *\n * The logging function has a signature of:\n * function(logger, message)\n * logger: current logger\n * message: object:\n * level: level id\n * category: category\n * message: string message\n * arguments: Array of extra arguments\n * fullMessage: interpolated message and arguments if INTERPOLATE flag set\n *\n * @param logFunction a logging function which takes a log message object\n * as a parameter.\n *\n * @return a logger object.\n */\nforge.log.makeLogger = function(logFunction) {\n var logger = {\n flags: 0,\n f: logFunction\n };\n forge.log.setLevel(logger, 'none');\n return logger;\n};\n\n/**\n * Sets the current log level on a logger.\n *\n * @param logger the target logger.\n * @param level the new maximum log level as a string.\n *\n * @return true if set, false if not.\n */\nforge.log.setLevel = function(logger, level) {\n var rval = false;\n if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) {\n for(var i = 0; i < forge.log.levels.length; ++i) {\n var aValidLevel = forge.log.levels[i];\n if(level == aValidLevel) {\n // set level\n logger.level = level;\n rval = true;\n break;\n }\n }\n }\n\n return rval;\n};\n\n/**\n * Locks the log level at its current value.\n *\n * @param logger the target logger.\n * @param lock boolean lock value, default to true.\n */\nforge.log.lock = function(logger, lock) {\n if(typeof lock === 'undefined' || lock) {\n logger.flags |= forge.log.LEVEL_LOCKED;\n } else {\n logger.flags &= ~forge.log.LEVEL_LOCKED;\n }\n};\n\n/**\n * Adds a logger.\n *\n * @param logger the logger object.\n */\nforge.log.addLogger = function(logger) {\n sLoggers.push(logger);\n};\n\n// setup the console logger if possible, else create fake console.log\nif(typeof(console) !== 'undefined' && 'log' in console) {\n var logger;\n if(console.error && console.warn && console.info && console.debug) {\n // looks like Firebug-style logging is available\n // level handlers map\n var levelHandlers = {\n error: console.error,\n warning: console.warn,\n info: console.info,\n debug: console.debug,\n verbose: console.debug\n };\n var f = function(logger, message) {\n forge.log.prepareStandard(message);\n var handler = levelHandlers[message.level];\n // prepend standard message and concat args\n var args = [message.standard];\n args = args.concat(message['arguments'].slice());\n // apply to low-level console function\n handler.apply(console, args);\n };\n logger = forge.log.makeLogger(f);\n } else {\n // only appear to have basic console.log\n var f = function(logger, message) {\n forge.log.prepareStandardFull(message);\n console.log(message.standardFull);\n };\n logger = forge.log.makeLogger(f);\n }\n forge.log.setLevel(logger, 'debug');\n forge.log.addLogger(logger);\n sConsoleLogger = logger;\n} else {\n // define fake console.log to avoid potential script errors on\n // browsers that do not have console logging\n console = {\n log: function() {}\n };\n}\n\n/*\n * Check for logging control query vars.\n *\n * console.level=\n * Set's the console log level by name. Useful to override defaults and\n * allow more verbose logging before a user config is loaded.\n *\n * console.lock=\n * Lock the console log level at whatever level it is set at. This is run\n * after console.level is processed. Useful to force a level of verbosity\n * that could otherwise be limited by a user config.\n */\nif(sConsoleLogger !== null) {\n var query = forge.util.getQueryVariables();\n if('console.level' in query) {\n // set with last value\n forge.log.setLevel(\n sConsoleLogger, query['console.level'].slice(-1)[0]);\n }\n if('console.lock' in query) {\n // set with last value\n var lock = query['console.lock'].slice(-1)[0];\n if(lock == 'true') {\n forge.log.lock(sConsoleLogger);\n }\n }\n}\n\n// provide public access to console logger\nforge.log.consoleLogger = sConsoleLogger;\n","/**\n * Javascript implementation of PKCS#7 v1.5.\n *\n * @author Stefan Siegl\n * @author Dave Longley\n *\n * Copyright (c) 2012 Stefan Siegl \n * Copyright (c) 2012-2015 Digital Bazaar, Inc.\n *\n * Currently this implementation only supports ContentType of EnvelopedData,\n * EncryptedData, or SignedData at the root level. The top level elements may\n * contain only a ContentInfo of ContentType Data, i.e. plain data. Further\n * nesting is not (yet) supported.\n *\n * The Forge validators for PKCS #7's ASN.1 structures are available from\n * a separate file pkcs7asn1.js, since those are referenced from other\n * PKCS standards like PKCS #12.\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./asn1');\nrequire('./des');\nrequire('./oids');\nrequire('./pem');\nrequire('./pkcs7asn1');\nrequire('./random');\nrequire('./util');\nrequire('./x509');\n\n// shortcut for ASN.1 API\nvar asn1 = forge.asn1;\n\n// shortcut for PKCS#7 API\nvar p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};\n\n/**\n * Converts a PKCS#7 message from PEM format.\n *\n * @param pem the PEM-formatted PKCS#7 message.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromPem = function(pem) {\n var msg = forge.pem.decode(pem)[0];\n\n if(msg.type !== 'PKCS7') {\n var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +\n 'header type is not \"PKCS#7\".');\n error.headerType = msg.type;\n throw error;\n }\n if(msg.procType && msg.procType.type === 'ENCRYPTED') {\n throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');\n }\n\n // convert DER to ASN.1 object\n var obj = asn1.fromDer(msg.body);\n\n return p7.messageFromAsn1(obj);\n};\n\n/**\n * Converts a PKCS#7 message to PEM format.\n *\n * @param msg The PKCS#7 message object\n * @param maxline The maximum characters per line, defaults to 64.\n *\n * @return The PEM-formatted PKCS#7 message.\n */\np7.messageToPem = function(msg, maxline) {\n // convert to ASN.1, then DER, then PEM-encode\n var pemObj = {\n type: 'PKCS7',\n body: asn1.toDer(msg.toAsn1()).getBytes()\n };\n return forge.pem.encode(pemObj, {maxline: maxline});\n};\n\n/**\n * Converts a PKCS#7 message from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a ContentInfo.\n *\n * @return the PKCS#7 message.\n */\np7.messageFromAsn1 = function(obj) {\n // validate root level ContentInfo and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not an PKCS#7 ContentInfo.');\n error.errors = errors;\n throw error;\n }\n\n var contentType = asn1.derToOid(capture.contentType);\n var msg;\n\n switch(contentType) {\n case forge.pki.oids.envelopedData:\n msg = p7.createEnvelopedData();\n break;\n\n case forge.pki.oids.encryptedData:\n msg = p7.createEncryptedData();\n break;\n\n case forge.pki.oids.signedData:\n msg = p7.createSignedData();\n break;\n\n default:\n throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +\n contentType + ' is not (yet) supported.');\n }\n\n msg.fromAsn1(capture.content.value[0]);\n return msg;\n};\n\np7.createSignedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.signedData,\n version: 1,\n certificates: [],\n crls: [],\n // TODO: add json-formatted signer stuff here?\n signers: [],\n // populated during sign()\n digestAlgorithmIdentifiers: [],\n contentInfo: null,\n signerInfos: [],\n\n fromAsn1: function(obj) {\n // validate SignedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.signedDataValidator);\n msg.certificates = [];\n msg.crls = [];\n msg.digestAlgorithmIdentifiers = [];\n msg.contentInfo = null;\n msg.signerInfos = [];\n\n if(msg.rawCapture.certificates) {\n var certs = msg.rawCapture.certificates.value;\n for(var i = 0; i < certs.length; ++i) {\n msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));\n }\n }\n\n // TODO: parse crls\n },\n\n toAsn1: function() {\n // degenerate case with no content\n if(!msg.contentInfo) {\n msg.sign();\n }\n\n var certs = [];\n for(var i = 0; i < msg.certificates.length; ++i) {\n certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));\n }\n\n var crls = [];\n // TODO: implement CRLs\n\n // [0] SignedData\n var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // DigestAlgorithmIdentifiers\n asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.digestAlgorithmIdentifiers),\n // ContentInfo\n msg.contentInfo\n ])\n ]);\n if(certs.length > 0) {\n // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));\n }\n if(crls.length > 0) {\n // [1] IMPLICIT CertificateRevocationLists OPTIONAL\n signedData.value[0].value.push(\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));\n }\n // SignerInfos\n signedData.value[0].value.push(\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n msg.signerInfos));\n\n // ContentInfo\n return asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] SignedData\n signedData\n ]);\n },\n\n /**\n * Add (another) entity to list of signers.\n *\n * Note: If authenticatedAttributes are provided, then, per RFC 2315,\n * they must include at least two attributes: content type and\n * message digest. The message digest attribute value will be\n * auto-calculated during signing and will be ignored if provided.\n *\n * Here's an example of providing these two attributes:\n *\n * forge.pkcs7.createSignedData();\n * p7.addSigner({\n * issuer: cert.issuer.attributes,\n * serialNumber: cert.serialNumber,\n * key: privateKey,\n * digestAlgorithm: forge.pki.oids.sha1,\n * authenticatedAttributes: [{\n * type: forge.pki.oids.contentType,\n * value: forge.pki.oids.data\n * }, {\n * type: forge.pki.oids.messageDigest\n * }]\n * });\n *\n * TODO: Support [subjectKeyIdentifier] as signer's ID.\n *\n * @param signer the signer information:\n * key the signer's private key.\n * [certificate] a certificate containing the public key\n * associated with the signer's private key; use this option as\n * an alternative to specifying signer.issuer and\n * signer.serialNumber.\n * [issuer] the issuer attributes (eg: cert.issuer.attributes).\n * [serialNumber] the signer's certificate's serial number in\n * hexadecimal (eg: cert.serialNumber).\n * [digestAlgorithm] the message digest OID, as a string, to use\n * (eg: forge.pki.oids.sha1).\n * [authenticatedAttributes] an optional array of attributes\n * to also sign along with the content.\n */\n addSigner: function(signer) {\n var issuer = signer.issuer;\n var serialNumber = signer.serialNumber;\n if(signer.certificate) {\n var cert = signer.certificate;\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n issuer = cert.issuer.attributes;\n serialNumber = cert.serialNumber;\n }\n var key = signer.key;\n if(!key) {\n throw new Error(\n 'Could not add PKCS#7 signer; no private key specified.');\n }\n if(typeof key === 'string') {\n key = forge.pki.privateKeyFromPem(key);\n }\n\n // ensure OID known for digest algorithm\n var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;\n switch(digestAlgorithm) {\n case forge.pki.oids.sha1:\n case forge.pki.oids.sha256:\n case forge.pki.oids.sha384:\n case forge.pki.oids.sha512:\n case forge.pki.oids.md5:\n break;\n default:\n throw new Error(\n 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +\n digestAlgorithm);\n }\n\n // if authenticatedAttributes is present, then the attributes\n // must contain at least PKCS #9 content-type and message-digest\n var authenticatedAttributes = signer.authenticatedAttributes || [];\n if(authenticatedAttributes.length > 0) {\n var contentType = false;\n var messageDigest = false;\n for(var i = 0; i < authenticatedAttributes.length; ++i) {\n var attr = authenticatedAttributes[i];\n if(!contentType && attr.type === forge.pki.oids.contentType) {\n contentType = true;\n if(messageDigest) {\n break;\n }\n continue;\n }\n if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {\n messageDigest = true;\n if(contentType) {\n break;\n }\n continue;\n }\n }\n\n if(!contentType || !messageDigest) {\n throw new Error('Invalid signer.authenticatedAttributes. If ' +\n 'signer.authenticatedAttributes is specified, then it must ' +\n 'contain at least two attributes, PKCS #9 content-type and ' +\n 'PKCS #9 message-digest.');\n }\n }\n\n msg.signers.push({\n key: key,\n version: 1,\n issuer: issuer,\n serialNumber: serialNumber,\n digestAlgorithm: digestAlgorithm,\n signatureAlgorithm: forge.pki.oids.rsaEncryption,\n signature: null,\n authenticatedAttributes: authenticatedAttributes,\n unauthenticatedAttributes: []\n });\n },\n\n /**\n * Signs the content.\n * @param options Options to apply when signing:\n * [detached] boolean. If signing should be done in detached mode. Defaults to false.\n */\n sign: function(options) {\n options = options || {};\n // auto-generate content info\n if(typeof msg.content !== 'object' || msg.contentInfo === null) {\n // use Data ContentInfo\n msg.contentInfo = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes())\n ]);\n\n // add actual content, if present\n if('content' in msg) {\n var content;\n if(msg.content instanceof forge.util.ByteBuffer) {\n content = msg.content.bytes();\n } else if(typeof msg.content === 'string') {\n content = forge.util.encodeUtf8(msg.content);\n }\n\n if (options.detached) {\n msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);\n } else {\n msg.contentInfo.value.push(\n // [0] EXPLICIT content\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n content)\n ]));\n }\n }\n }\n\n // no signers, return early (degenerate case for certificate container)\n if(msg.signers.length === 0) {\n return;\n }\n\n // generate digest algorithm identifiers\n var mds = addDigestAlgorithmIds();\n\n // generate signerInfos\n addSignerInfos(mds);\n },\n\n verify: function() {\n throw new Error('PKCS#7 signature verification not yet implemented.');\n },\n\n /**\n * Add a certificate.\n *\n * @param cert the certificate to add.\n */\n addCertificate: function(cert) {\n // convert from PEM\n if(typeof cert === 'string') {\n cert = forge.pki.certificateFromPem(cert);\n }\n msg.certificates.push(cert);\n },\n\n /**\n * Add a certificate revokation list.\n *\n * @param crl the certificate revokation list to add.\n */\n addCertificateRevokationList: function(crl) {\n throw new Error('PKCS#7 CRL support not yet implemented.');\n }\n };\n return msg;\n\n function addDigestAlgorithmIds() {\n var mds = {};\n\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n var oid = signer.digestAlgorithm;\n if(!(oid in mds)) {\n // content digest\n mds[oid] = forge.md[forge.pki.oids[oid]].create();\n }\n if(signer.authenticatedAttributes.length === 0) {\n // no custom attributes to digest; use content message digest\n signer.md = mds[oid];\n } else {\n // custom attributes to be digested; use own message digest\n // TODO: optimize to just copy message digest state if that\n // feature is ever supported with message digests\n signer.md = forge.md[forge.pki.oids[oid]].create();\n }\n }\n\n // add unique digest algorithm identifiers\n msg.digestAlgorithmIdentifiers = [];\n for(var oid in mds) {\n msg.digestAlgorithmIdentifiers.push(\n // AlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(oid).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n }\n\n return mds;\n }\n\n function addSignerInfos(mds) {\n var content;\n\n if (msg.detachedContent) {\n // Signature has been made in detached mode.\n content = msg.detachedContent;\n } else {\n // Note: ContentInfo is a SEQUENCE with 2 values, second value is\n // the content field and is optional for a ContentInfo but required here\n // since signers are present\n // get ContentInfo content\n content = msg.contentInfo.value[1];\n // skip [0] EXPLICIT content wrapper\n content = content.value[0];\n }\n\n if(!content) {\n throw new Error(\n 'Could not sign PKCS#7 message; there is no content to sign.');\n }\n\n // get ContentInfo content type\n var contentType = asn1.derToOid(msg.contentInfo.value[0].value);\n\n // serialize content\n var bytes = asn1.toDer(content);\n\n // skip identifier and length per RFC 2315 9.3\n // skip identifier (1 byte)\n bytes.getByte();\n // read and discard length bytes\n asn1.getBerValueLength(bytes);\n bytes = bytes.getBytes();\n\n // digest content DER value bytes\n for(var oid in mds) {\n mds[oid].start().update(bytes);\n }\n\n // sign content\n var signingTime = new Date();\n for(var i = 0; i < msg.signers.length; ++i) {\n var signer = msg.signers[i];\n\n if(signer.authenticatedAttributes.length === 0) {\n // if ContentInfo content type is not \"Data\", then\n // authenticatedAttributes must be present per RFC 2315\n if(contentType !== forge.pki.oids.data) {\n throw new Error(\n 'Invalid signer; authenticatedAttributes must be present ' +\n 'when the ContentInfo content type is not PKCS#7 Data.');\n }\n } else {\n // process authenticated attributes\n // [0] IMPLICIT\n signer.authenticatedAttributesAsn1 = asn1.create(\n asn1.Class.CONTEXT_SPECIFIC, 0, true, []);\n\n // per RFC 2315, attributes are to be digested using a SET container\n // not the above [0] IMPLICIT container\n var attrsAsn1 = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);\n\n for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {\n var attr = signer.authenticatedAttributes[ai];\n if(attr.type === forge.pki.oids.messageDigest) {\n // use content message digest as value\n attr.value = mds[signer.digestAlgorithm].digest();\n } else if(attr.type === forge.pki.oids.signingTime) {\n // auto-populate signing time if not already set\n if(!attr.value) {\n attr.value = signingTime;\n }\n }\n\n // convert to ASN.1 and push onto Attributes SET (for signing) and\n // onto authenticatedAttributesAsn1 to complete SignedData ASN.1\n // TODO: optimize away duplication\n attrsAsn1.value.push(_attributeToAsn1(attr));\n signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));\n }\n\n // DER-serialize and digest SET OF attributes only\n bytes = asn1.toDer(attrsAsn1).getBytes();\n signer.md.start().update(bytes);\n }\n\n // sign digest\n signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');\n }\n\n // add signer info\n msg.signerInfos = _signersToAsn1(msg.signers);\n }\n};\n\n/**\n * Creates an empty PKCS#7 message of type EncryptedData.\n *\n * @return the message.\n */\np7.createEncryptedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.encryptedData,\n version: 0,\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EncryptedData content block (in ASN.1 format)\n *\n * @param obj The ASN.1 representation of the EncryptedData content block\n */\n fromAsn1: function(obj) {\n // Validate EncryptedData content block and capture data.\n _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);\n },\n\n /**\n * Decrypt encrypted content\n *\n * @param key The (symmetric) key as a byte buffer\n */\n decrypt: function(key) {\n if(key !== undefined) {\n msg.encryptedContent.key = key;\n }\n _decryptContent(msg);\n }\n };\n return msg;\n};\n\n/**\n * Creates an empty PKCS#7 message of type EnvelopedData.\n *\n * @return the message.\n */\np7.createEnvelopedData = function() {\n var msg = null;\n msg = {\n type: forge.pki.oids.envelopedData,\n version: 0,\n recipients: [],\n encryptedContent: {\n algorithm: forge.pki.oids['aes256-CBC']\n },\n\n /**\n * Reads an EnvelopedData content block (in ASN.1 format)\n *\n * @param obj the ASN.1 representation of the EnvelopedData content block.\n */\n fromAsn1: function(obj) {\n // validate EnvelopedData content block and capture data\n var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);\n msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);\n },\n\n toAsn1: function() {\n // ContentInfo\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // ContentType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(msg.type).getBytes()),\n // [0] EnvelopedData\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(msg.version).getBytes()),\n // RecipientInfos\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,\n _recipientsToAsn1(msg.recipients)),\n // EncryptedContentInfo\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,\n _encryptedContentToAsn1(msg.encryptedContent))\n ])\n ])\n ]);\n },\n\n /**\n * Find recipient by X.509 certificate's issuer.\n *\n * @param cert the certificate with the issuer to look for.\n *\n * @return the recipient object.\n */\n findRecipient: function(cert) {\n var sAttr = cert.issuer.attributes;\n\n for(var i = 0; i < msg.recipients.length; ++i) {\n var r = msg.recipients[i];\n var rAttr = r.issuer;\n\n if(r.serialNumber !== cert.serialNumber) {\n continue;\n }\n\n if(rAttr.length !== sAttr.length) {\n continue;\n }\n\n var match = true;\n for(var j = 0; j < sAttr.length; ++j) {\n if(rAttr[j].type !== sAttr[j].type ||\n rAttr[j].value !== sAttr[j].value) {\n match = false;\n break;\n }\n }\n\n if(match) {\n return r;\n }\n }\n\n return null;\n },\n\n /**\n * Decrypt enveloped content\n *\n * @param recipient The recipient object related to the private key\n * @param privKey The (RSA) private key object\n */\n decrypt: function(recipient, privKey) {\n if(msg.encryptedContent.key === undefined && recipient !== undefined &&\n privKey !== undefined) {\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n case forge.pki.oids.desCBC:\n var key = privKey.decrypt(recipient.encryptedContent.content);\n msg.encryptedContent.key = forge.util.createBuffer(key);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, ' +\n 'OID ' + recipient.encryptedContent.algorithm);\n }\n }\n\n _decryptContent(msg);\n },\n\n /**\n * Add (another) entity to list of recipients.\n *\n * @param cert The certificate of the entity to add.\n */\n addRecipient: function(cert) {\n msg.recipients.push({\n version: 0,\n issuer: cert.issuer.attributes,\n serialNumber: cert.serialNumber,\n encryptedContent: {\n // We simply assume rsaEncryption here, since forge.pki only\n // supports RSA so far. If the PKI module supports other\n // ciphers one day, we need to modify this one as well.\n algorithm: forge.pki.oids.rsaEncryption,\n key: cert.publicKey\n }\n });\n },\n\n /**\n * Encrypt enveloped content.\n *\n * This function supports two optional arguments, cipher and key, which\n * can be used to influence symmetric encryption. Unless cipher is\n * provided, the cipher specified in encryptedContent.algorithm is used\n * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key\n * is (re-)used. If that one's not set, a random key will be generated\n * automatically.\n *\n * @param [key] The key to be used for symmetric encryption.\n * @param [cipher] The OID of the symmetric cipher to use.\n */\n encrypt: function(key, cipher) {\n // Part 1: Symmetric encryption\n if(msg.encryptedContent.content === undefined) {\n cipher = cipher || msg.encryptedContent.algorithm;\n key = key || msg.encryptedContent.key;\n\n var keyLen, ivLen, ciphFn;\n switch(cipher) {\n case forge.pki.oids['aes128-CBC']:\n keyLen = 16;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes192-CBC']:\n keyLen = 24;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['aes256-CBC']:\n keyLen = 32;\n ivLen = 16;\n ciphFn = forge.aes.createEncryptionCipher;\n break;\n\n case forge.pki.oids['des-EDE3-CBC']:\n keyLen = 24;\n ivLen = 8;\n ciphFn = forge.des.createEncryptionCipher;\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' + cipher);\n }\n\n if(key === undefined) {\n key = forge.util.createBuffer(forge.random.getBytes(keyLen));\n } else if(key.length() != keyLen) {\n throw new Error('Symmetric key has wrong length; ' +\n 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');\n }\n\n // Keep a copy of the key & IV in the object, so the caller can\n // use it for whatever reason.\n msg.encryptedContent.algorithm = cipher;\n msg.encryptedContent.key = key;\n msg.encryptedContent.parameter = forge.util.createBuffer(\n forge.random.getBytes(ivLen));\n\n var ciph = ciphFn(key);\n ciph.start(msg.encryptedContent.parameter.copy());\n ciph.update(msg.content);\n\n // The finish function does PKCS#7 padding by default, therefore\n // no action required by us.\n if(!ciph.finish()) {\n throw new Error('Symmetric encryption failed.');\n }\n\n msg.encryptedContent.content = ciph.output;\n }\n\n // Part 2: asymmetric encryption for each recipient\n for(var i = 0; i < msg.recipients.length; ++i) {\n var recipient = msg.recipients[i];\n\n // Nothing to do, encryption already done.\n if(recipient.encryptedContent.content !== undefined) {\n continue;\n }\n\n switch(recipient.encryptedContent.algorithm) {\n case forge.pki.oids.rsaEncryption:\n recipient.encryptedContent.content =\n recipient.encryptedContent.key.encrypt(\n msg.encryptedContent.key.data);\n break;\n\n default:\n throw new Error('Unsupported asymmetric cipher, OID ' +\n recipient.encryptedContent.algorithm);\n }\n }\n }\n };\n return msg;\n};\n\n/**\n * Converts a single recipient from an ASN.1 object.\n *\n * @param obj the ASN.1 RecipientInfo.\n *\n * @return the recipient object.\n */\nfunction _recipientFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +\n 'ASN.1 object is not an PKCS#7 RecipientInfo.');\n error.errors = errors;\n throw error;\n }\n\n return {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n encryptedContent: {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: capture.encParameter.value,\n content: capture.encKey\n }\n };\n}\n\n/**\n * Converts a single recipient object to an ASN.1 object.\n *\n * @param obj the recipient object.\n *\n * @return the ASN.1 RecipientInfo.\n */\nfunction _recipientToAsn1(obj) {\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // IssuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // Serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // KeyEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),\n // Parameter, force NULL, only RSA supported for now.\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]),\n // EncryptedKey\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n obj.encryptedContent.content)\n ]);\n}\n\n/**\n * Map a set of RecipientInfo ASN.1 objects to recipient objects.\n *\n * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).\n *\n * @return an array of recipient objects.\n */\nfunction _recipientsFromAsn1(infos) {\n var ret = [];\n for(var i = 0; i < infos.length; ++i) {\n ret.push(_recipientFromAsn1(infos[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of recipient objects to ASN.1 RecipientInfo objects.\n *\n * @param recipients an array of recipientInfo objects.\n *\n * @return an array of ASN.1 RecipientInfos.\n */\nfunction _recipientsToAsn1(recipients) {\n var ret = [];\n for(var i = 0; i < recipients.length; ++i) {\n ret.push(_recipientToAsn1(recipients[i]));\n }\n return ret;\n}\n\n/**\n * Converts a single signer from an ASN.1 object.\n *\n * @param obj the ASN.1 representation of a SignerInfo.\n *\n * @return the signer object.\n */\nfunction _signerFromAsn1(obj) {\n // validate EnvelopedData content block and capture data\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 SignerInfo. ' +\n 'ASN.1 object is not an PKCS#7 SignerInfo.');\n error.errors = errors;\n throw error;\n }\n\n var rval = {\n version: capture.version.charCodeAt(0),\n issuer: forge.pki.RDNAttributesAsArray(capture.issuer),\n serialNumber: forge.util.createBuffer(capture.serial).toHex(),\n digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),\n signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),\n signature: capture.signature,\n authenticatedAttributes: [],\n unauthenticatedAttributes: []\n };\n\n // TODO: convert attributes\n var authenticatedAttributes = capture.authenticatedAttributes || [];\n var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];\n\n return rval;\n}\n\n/**\n * Converts a single signerInfo object to an ASN.1 object.\n *\n * @param obj the signerInfo object.\n *\n * @return the ASN.1 representation of a SignerInfo.\n */\nfunction _signerToAsn1(obj) {\n // SignerInfo\n var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // version\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n asn1.integerToDer(obj.version).getBytes()),\n // issuerAndSerialNumber\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // name\n forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),\n // serial\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,\n forge.util.hexToBytes(obj.serialNumber))\n ]),\n // digestAlgorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.digestAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ])\n ]);\n\n // authenticatedAttributes (OPTIONAL)\n if(obj.authenticatedAttributesAsn1) {\n // add ASN.1 previously generated during signing\n rval.value.push(obj.authenticatedAttributesAsn1);\n }\n\n // digestEncryptionAlgorithm\n rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(obj.signatureAlgorithm).getBytes()),\n // parameters (null)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')\n ]));\n\n // encryptedDigest\n rval.value.push(asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));\n\n // unauthenticatedAttributes (OPTIONAL)\n if(obj.unauthenticatedAttributes.length > 0) {\n // [1] IMPLICIT\n var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);\n for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {\n var attr = obj.unauthenticatedAttributes[i];\n attrsAsn1.values.push(_attributeToAsn1(attr));\n }\n rval.value.push(attrsAsn1);\n }\n\n return rval;\n}\n\n/**\n * Map a set of SignerInfo ASN.1 objects to an array of signer objects.\n *\n * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).\n *\n * @return an array of signers objects.\n */\nfunction _signersFromAsn1(signerInfoAsn1s) {\n var ret = [];\n for(var i = 0; i < signerInfoAsn1s.length; ++i) {\n ret.push(_signerFromAsn1(signerInfoAsn1s[i]));\n }\n return ret;\n}\n\n/**\n * Map an array of signer objects to ASN.1 objects.\n *\n * @param signers an array of signer objects.\n *\n * @return an array of ASN.1 SignerInfos.\n */\nfunction _signersToAsn1(signers) {\n var ret = [];\n for(var i = 0; i < signers.length; ++i) {\n ret.push(_signerToAsn1(signers[i]));\n }\n return ret;\n}\n\n/**\n * Convert an attribute object to an ASN.1 Attribute.\n *\n * @param attr the attribute object.\n *\n * @return the ASN.1 Attribute.\n */\nfunction _attributeToAsn1(attr) {\n var value;\n\n // TODO: generalize to support more attributes\n if(attr.type === forge.pki.oids.contentType) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.value).getBytes());\n } else if(attr.type === forge.pki.oids.messageDigest) {\n value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n attr.value.bytes());\n } else if(attr.type === forge.pki.oids.signingTime) {\n /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049\n (inclusive) MUST be encoded as UTCTime. Any dates with year values\n before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]\n UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST\n include seconds (i.e., times are YYMMDDHHMMSSZ), even where the\n number of seconds is zero. Midnight (GMT) must be represented as\n \"YYMMDD000000Z\". */\n // TODO: make these module-level constants\n var jan_1_1950 = new Date('1950-01-01T00:00:00Z');\n var jan_1_2050 = new Date('2050-01-01T00:00:00Z');\n var date = attr.value;\n if(typeof date === 'string') {\n // try to parse date\n var timestamp = Date.parse(date);\n if(!isNaN(timestamp)) {\n date = new Date(timestamp);\n } else if(date.length === 13) {\n // YYMMDDHHMMSSZ (13 chars for UTCTime)\n date = asn1.utcTimeToDate(date);\n } else {\n // assume generalized time\n date = asn1.generalizedTimeToDate(date);\n }\n }\n\n if(date >= jan_1_1950 && date < jan_1_2050) {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,\n asn1.dateToUtcTime(date));\n } else {\n value = asn1.create(\n asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,\n asn1.dateToGeneralizedTime(date));\n }\n }\n\n // TODO: expose as common API call\n // create a RelativeDistinguishedName set\n // each value in the set is an AttributeTypeAndValue first\n // containing the type (an OID) and second the value\n return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // AttributeType\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(attr.type).getBytes()),\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [\n // AttributeValue\n value\n ])\n ]);\n}\n\n/**\n * Map messages encrypted content to ASN.1 objects.\n *\n * @param ec The encryptedContent object of the message.\n *\n * @return ASN.1 representation of the encryptedContent object (SEQUENCE).\n */\nfunction _encryptedContentToAsn1(ec) {\n return [\n // ContentType, always Data for the moment\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(forge.pki.oids.data).getBytes()),\n // ContentEncryptionAlgorithmIdentifier\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [\n // Algorithm\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,\n asn1.oidToDer(ec.algorithm).getBytes()),\n // Parameters (IV)\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.parameter.getBytes())\n ]),\n // [0] EncryptedContent\n asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [\n asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,\n ec.content.getBytes())\n ])\n ];\n}\n\n/**\n * Reads the \"common part\" of an PKCS#7 content block (in ASN.1 format)\n *\n * This function reads the \"common part\" of the PKCS#7 content blocks\n * EncryptedData and EnvelopedData, i.e. version number and symmetrically\n * encrypted content block.\n *\n * The result of the ASN.1 validate and capture process is returned\n * to allow the caller to extract further data, e.g. the list of recipients\n * in case of a EnvelopedData object.\n *\n * @param msg the PKCS#7 object to read the data to.\n * @param obj the ASN.1 representation of the content block.\n * @param validator the ASN.1 structure validator object to use.\n *\n * @return the value map captured by validator object.\n */\nfunction _fromAsn1(msg, obj, validator) {\n var capture = {};\n var errors = [];\n if(!asn1.validate(obj, validator, capture, errors)) {\n var error = new Error('Cannot read PKCS#7 message. ' +\n 'ASN.1 object is not a supported PKCS#7 message.');\n error.errors = error;\n throw error;\n }\n\n // Check contentType, so far we only support (raw) Data.\n var contentType = asn1.derToOid(capture.contentType);\n if(contentType !== forge.pki.oids.data) {\n throw new Error('Unsupported PKCS#7 message. ' +\n 'Only wrapped ContentType Data supported.');\n }\n\n if(capture.encryptedContent) {\n var content = '';\n if(forge.util.isArray(capture.encryptedContent)) {\n for(var i = 0; i < capture.encryptedContent.length; ++i) {\n if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting encrypted ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.encryptedContent[i].value;\n }\n } else {\n content = capture.encryptedContent;\n }\n msg.encryptedContent = {\n algorithm: asn1.derToOid(capture.encAlgorithm),\n parameter: forge.util.createBuffer(capture.encParameter.value),\n content: forge.util.createBuffer(content)\n };\n }\n\n if(capture.content) {\n var content = '';\n if(forge.util.isArray(capture.content)) {\n for(var i = 0; i < capture.content.length; ++i) {\n if(capture.content[i].type !== asn1.Type.OCTETSTRING) {\n throw new Error('Malformed PKCS#7 message, expecting ' +\n 'content constructed of only OCTET STRING objects.');\n }\n content += capture.content[i].value;\n }\n } else {\n content = capture.content;\n }\n msg.content = forge.util.createBuffer(content);\n }\n\n msg.version = capture.version.charCodeAt(0);\n msg.rawCapture = capture;\n\n return capture;\n}\n\n/**\n * Decrypt the symmetrically encrypted content block of the PKCS#7 message.\n *\n * Decryption is skipped in case the PKCS#7 message object already has a\n * (decrypted) content attribute. The algorithm, key and cipher parameters\n * (probably the iv) are taken from the encryptedContent attribute of the\n * message object.\n *\n * @param The PKCS#7 message object.\n */\nfunction _decryptContent(msg) {\n if(msg.encryptedContent.key === undefined) {\n throw new Error('Symmetric key not available.');\n }\n\n if(msg.content === undefined) {\n var ciph;\n\n switch(msg.encryptedContent.algorithm) {\n case forge.pki.oids['aes128-CBC']:\n case forge.pki.oids['aes192-CBC']:\n case forge.pki.oids['aes256-CBC']:\n ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n case forge.pki.oids['desCBC']:\n case forge.pki.oids['des-EDE3-CBC']:\n ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);\n break;\n\n default:\n throw new Error('Unsupported symmetric cipher, OID ' +\n msg.encryptedContent.algorithm);\n }\n ciph.start(msg.encryptedContent.parameter);\n ciph.update(msg.encryptedContent.content);\n\n if(!ciph.finish()) {\n throw new Error('Symmetric decryption failed.');\n }\n\n msg.content = ciph.output;\n }\n}\n","/**\n * Functions to output keys in SSH-friendly formats.\n *\n * This is part of the Forge project which may be used under the terms of\n * either the BSD License or the GNU General Public License (GPL) Version 2.\n *\n * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE\n *\n * @author https://github.com/shellac\n */\nvar forge = require('./forge');\nrequire('./aes');\nrequire('./hmac');\nrequire('./md5');\nrequire('./sha1');\nrequire('./util');\n\nvar ssh = module.exports = forge.ssh = forge.ssh || {};\n\n/**\n * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file.\n *\n * @param privateKey the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n * @param comment a comment to include in the key file.\n *\n * @return the PPK file as a string.\n */\nssh.privateKeyToPutty = function(privateKey, passphrase, comment) {\n comment = comment || '';\n passphrase = passphrase || '';\n var algorithm = 'ssh-rsa';\n var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc';\n\n var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\\r\\n';\n ppk += 'Encryption: ' + encryptionAlgorithm + '\\r\\n';\n ppk += 'Comment: ' + comment + '\\r\\n';\n\n // public key into buffer for ppk\n var pubbuffer = forge.util.createBuffer();\n _addStringToBuffer(pubbuffer, algorithm);\n _addBigIntegerToBuffer(pubbuffer, privateKey.e);\n _addBigIntegerToBuffer(pubbuffer, privateKey.n);\n\n // write public key\n var pub = forge.util.encode64(pubbuffer.bytes(), 64);\n var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \\r\\n\n ppk += 'Public-Lines: ' + length + '\\r\\n';\n ppk += pub;\n\n // private key into a buffer\n var privbuffer = forge.util.createBuffer();\n _addBigIntegerToBuffer(privbuffer, privateKey.d);\n _addBigIntegerToBuffer(privbuffer, privateKey.p);\n _addBigIntegerToBuffer(privbuffer, privateKey.q);\n _addBigIntegerToBuffer(privbuffer, privateKey.qInv);\n\n // optionally encrypt the private key\n var priv;\n if(!passphrase) {\n // use the unencrypted buffer\n priv = forge.util.encode64(privbuffer.bytes(), 64);\n } else {\n // encrypt RSA key using passphrase\n var encLen = privbuffer.length() + 16 - 1;\n encLen -= encLen % 16;\n\n // pad private key with sha1-d data -- needs to be a multiple of 16\n var padding = _sha1(privbuffer.bytes());\n\n padding.truncate(padding.length() - encLen + privbuffer.length());\n privbuffer.putBuffer(padding);\n\n var aeskey = forge.util.createBuffer();\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x00', passphrase));\n aeskey.putBuffer(_sha1('\\x00\\x00\\x00\\x01', passphrase));\n\n // encrypt some bytes using CBC mode\n // key is 40 bytes, so truncate *by* 8 bytes\n var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC');\n cipher.start(forge.util.createBuffer().fillWithByte(0, 16));\n cipher.update(privbuffer.copy());\n cipher.finish();\n var encrypted = cipher.output;\n\n // Note: this appears to differ from Putty -- is forge wrong, or putty?\n // due to padding we finish as an exact multiple of 16\n encrypted.truncate(16); // all padding\n\n priv = forge.util.encode64(encrypted.bytes(), 64);\n }\n\n // output private key\n length = Math.floor(priv.length / 66) + 1; // 64 + \\r\\n\n ppk += '\\r\\nPrivate-Lines: ' + length + '\\r\\n';\n ppk += priv;\n\n // MAC\n var mackey = _sha1('putty-private-key-file-mac-key', passphrase);\n\n var macbuffer = forge.util.createBuffer();\n _addStringToBuffer(macbuffer, algorithm);\n _addStringToBuffer(macbuffer, encryptionAlgorithm);\n _addStringToBuffer(macbuffer, comment);\n macbuffer.putInt32(pubbuffer.length());\n macbuffer.putBuffer(pubbuffer);\n macbuffer.putInt32(privbuffer.length());\n macbuffer.putBuffer(privbuffer);\n\n var hmac = forge.hmac.create();\n hmac.start('sha1', mackey);\n hmac.update(macbuffer.bytes());\n\n ppk += '\\r\\nPrivate-MAC: ' + hmac.digest().toHex() + '\\r\\n';\n\n return ppk;\n};\n\n/**\n * Encodes a public RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param comment a comment.\n *\n * @return the public key in OpenSSH format.\n */\nssh.publicKeyToOpenSSH = function(key, comment) {\n var type = 'ssh-rsa';\n comment = comment || '';\n\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment;\n};\n\n/**\n * Encodes a private RSA key as an OpenSSH file.\n *\n * @param key the key.\n * @param passphrase a passphrase to protect the key (falsy for no encryption).\n *\n * @return the public key in OpenSSH format.\n */\nssh.privateKeyToOpenSSH = function(privateKey, passphrase) {\n if(!passphrase) {\n return forge.pki.privateKeyToPem(privateKey);\n }\n // OpenSSH private key is just a legacy format, it seems\n return forge.pki.encryptRsaPrivateKey(privateKey, passphrase,\n {legacy: true, algorithm: 'aes128'});\n};\n\n/**\n * Gets the SSH fingerprint for the given public key.\n *\n * @param options the options to use.\n * [md] the message digest object to use (defaults to forge.md.md5).\n * [encoding] an alternative output encoding, such as 'hex'\n * (defaults to none, outputs a byte buffer).\n * [delimiter] the delimiter to use between bytes for 'hex' encoded\n * output, eg: ':' (defaults to none).\n *\n * @return the fingerprint as a byte buffer or other encoding based on options.\n */\nssh.getPublicKeyFingerprint = function(key, options) {\n options = options || {};\n var md = options.md || forge.md.md5.create();\n\n var type = 'ssh-rsa';\n var buffer = forge.util.createBuffer();\n _addStringToBuffer(buffer, type);\n _addBigIntegerToBuffer(buffer, key.e);\n _addBigIntegerToBuffer(buffer, key.n);\n\n // hash public key bytes\n md.start();\n md.update(buffer.getBytes());\n var digest = md.digest();\n if(options.encoding === 'hex') {\n var hex = digest.toHex();\n if(options.delimiter) {\n return hex.match(/.{2}/g).join(options.delimiter);\n }\n return hex;\n } else if(options.encoding === 'binary') {\n return digest.getBytes();\n } else if(options.encoding) {\n throw new Error('Unknown encoding \"' + options.encoding + '\".');\n }\n return digest;\n};\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a big integer.\n */\nfunction _addBigIntegerToBuffer(buffer, val) {\n var hexVal = val.toString(16);\n // ensure 2s complement +ve\n if(hexVal[0] >= '8') {\n hexVal = '00' + hexVal;\n }\n var bytes = forge.util.hexToBytes(hexVal);\n buffer.putInt32(bytes.length);\n buffer.putBytes(bytes);\n}\n\n/**\n * Adds len(val) then val to a buffer.\n *\n * @param buffer the buffer to add to.\n * @param val a string.\n */\nfunction _addStringToBuffer(buffer, val) {\n buffer.putInt32(val.length);\n buffer.putString(val);\n}\n\n/**\n * Hashes the arguments into one value using SHA-1.\n *\n * @return the sha1 hash of the provided arguments.\n */\nfunction _sha1() {\n var sha = forge.md.sha1.create();\n var num = arguments.length;\n for (var i = 0; i < num; ++i) {\n sha.update(arguments[i]);\n }\n return sha.digest();\n}\n","/**\n * Support for concurrent task management and synchronization in web\n * applications.\n *\n * @author Dave Longley\n * @author David I. Lehn \n *\n * Copyright (c) 2009-2013 Digital Bazaar, Inc.\n */\nvar forge = require('./forge');\nrequire('./debug');\nrequire('./log');\nrequire('./util');\n\n// logging category\nvar cat = 'forge.task';\n\n// verbose level\n// 0: off, 1: a little, 2: a whole lot\n// Verbose debug logging is surrounded by a level check to avoid the\n// performance issues with even calling the logging code regardless if it\n// is actually logged. For performance reasons this should not be set to 2\n// for production use.\n// ex: if(sVL >= 2) forge.log.verbose(....)\nvar sVL = 0;\n\n// track tasks for debugging\nvar sTasks = {};\nvar sNextTaskId = 0;\n// debug access\nforge.debug.set(cat, 'tasks', sTasks);\n\n// a map of task type to task queue\nvar sTaskQueues = {};\n// debug access\nforge.debug.set(cat, 'queues', sTaskQueues);\n\n// name for unnamed tasks\nvar sNoTaskName = '?';\n\n// maximum number of doNext() recursions before a context swap occurs\n// FIXME: might need to tweak this based on the browser\nvar sMaxRecursions = 30;\n\n// time slice for doing tasks before a context swap occurs\n// FIXME: might need to tweak this based on the browser\nvar sTimeSlice = 20;\n\n/**\n * Task states.\n *\n * READY: ready to start processing\n * RUNNING: task or a subtask is running\n * BLOCKED: task is waiting to acquire N permits to continue\n * SLEEPING: task is sleeping for a period of time\n * DONE: task is done\n * ERROR: task has an error\n */\nvar READY = 'ready';\nvar RUNNING = 'running';\nvar BLOCKED = 'blocked';\nvar SLEEPING = 'sleeping';\nvar DONE = 'done';\nvar ERROR = 'error';\n\n/**\n * Task actions. Used to control state transitions.\n *\n * STOP: stop processing\n * START: start processing tasks\n * BLOCK: block task from continuing until 1 or more permits are released\n * UNBLOCK: release one or more permits\n * SLEEP: sleep for a period of time\n * WAKEUP: wakeup early from SLEEPING state\n * CANCEL: cancel further tasks\n * FAIL: a failure occured\n */\nvar STOP = 'stop';\nvar START = 'start';\nvar BLOCK = 'block';\nvar UNBLOCK = 'unblock';\nvar SLEEP = 'sleep';\nvar WAKEUP = 'wakeup';\nvar CANCEL = 'cancel';\nvar FAIL = 'fail';\n\n/**\n * State transition table.\n *\n * nextState = sStateTable[currentState][action]\n */\nvar sStateTable = {};\n\nsStateTable[READY] = {};\nsStateTable[READY][STOP] = READY;\nsStateTable[READY][START] = RUNNING;\nsStateTable[READY][CANCEL] = DONE;\nsStateTable[READY][FAIL] = ERROR;\n\nsStateTable[RUNNING] = {};\nsStateTable[RUNNING][STOP] = READY;\nsStateTable[RUNNING][START] = RUNNING;\nsStateTable[RUNNING][BLOCK] = BLOCKED;\nsStateTable[RUNNING][UNBLOCK] = RUNNING;\nsStateTable[RUNNING][SLEEP] = SLEEPING;\nsStateTable[RUNNING][WAKEUP] = RUNNING;\nsStateTable[RUNNING][CANCEL] = DONE;\nsStateTable[RUNNING][FAIL] = ERROR;\n\nsStateTable[BLOCKED] = {};\nsStateTable[BLOCKED][STOP] = BLOCKED;\nsStateTable[BLOCKED][START] = BLOCKED;\nsStateTable[BLOCKED][BLOCK] = BLOCKED;\nsStateTable[BLOCKED][UNBLOCK] = BLOCKED;\nsStateTable[BLOCKED][SLEEP] = BLOCKED;\nsStateTable[BLOCKED][WAKEUP] = BLOCKED;\nsStateTable[BLOCKED][CANCEL] = DONE;\nsStateTable[BLOCKED][FAIL] = ERROR;\n\nsStateTable[SLEEPING] = {};\nsStateTable[SLEEPING][STOP] = SLEEPING;\nsStateTable[SLEEPING][START] = SLEEPING;\nsStateTable[SLEEPING][BLOCK] = SLEEPING;\nsStateTable[SLEEPING][UNBLOCK] = SLEEPING;\nsStateTable[SLEEPING][SLEEP] = SLEEPING;\nsStateTable[SLEEPING][WAKEUP] = SLEEPING;\nsStateTable[SLEEPING][CANCEL] = DONE;\nsStateTable[SLEEPING][FAIL] = ERROR;\n\nsStateTable[DONE] = {};\nsStateTable[DONE][STOP] = DONE;\nsStateTable[DONE][START] = DONE;\nsStateTable[DONE][BLOCK] = DONE;\nsStateTable[DONE][UNBLOCK] = DONE;\nsStateTable[DONE][SLEEP] = DONE;\nsStateTable[DONE][WAKEUP] = DONE;\nsStateTable[DONE][CANCEL] = DONE;\nsStateTable[DONE][FAIL] = ERROR;\n\nsStateTable[ERROR] = {};\nsStateTable[ERROR][STOP] = ERROR;\nsStateTable[ERROR][START] = ERROR;\nsStateTable[ERROR][BLOCK] = ERROR;\nsStateTable[ERROR][UNBLOCK] = ERROR;\nsStateTable[ERROR][SLEEP] = ERROR;\nsStateTable[ERROR][WAKEUP] = ERROR;\nsStateTable[ERROR][CANCEL] = ERROR;\nsStateTable[ERROR][FAIL] = ERROR;\n\n/**\n * Creates a new task.\n *\n * @param options options for this task\n * run: the run function for the task (required)\n * name: the run function for the task (optional)\n * parent: parent of this task (optional)\n *\n * @return the empty task.\n */\nvar Task = function(options) {\n // task id\n this.id = -1;\n\n // task name\n this.name = options.name || sNoTaskName;\n\n // task has no parent\n this.parent = options.parent || null;\n\n // save run function\n this.run = options.run;\n\n // create a queue of subtasks to run\n this.subtasks = [];\n\n // error flag\n this.error = false;\n\n // state of the task\n this.state = READY;\n\n // number of times the task has been blocked (also the number\n // of permits needed to be released to continue running)\n this.blocks = 0;\n\n // timeout id when sleeping\n this.timeoutId = null;\n\n // no swap time yet\n this.swapTime = null;\n\n // no user data\n this.userData = null;\n\n // initialize task\n // FIXME: deal with overflow\n this.id = sNextTaskId++;\n sTasks[this.id] = this;\n if(sVL >= 1) {\n forge.log.verbose(cat, '[%s][%s] init', this.id, this.name, this);\n }\n};\n\n/**\n * Logs debug information on this task and the system state.\n */\nTask.prototype.debug = function(msg) {\n msg = msg || '';\n forge.log.debug(cat, msg,\n '[%s][%s] task:', this.id, this.name, this,\n 'subtasks:', this.subtasks.length,\n 'queue:', sTaskQueues);\n};\n\n/**\n * Adds a subtask to run after task.doNext() or task.fail() is called.\n *\n * @param name human readable name for this task (optional).\n * @param subrun a function to run that takes the current task as\n * its first parameter.\n *\n * @return the current task (useful for chaining next() calls).\n */\nTask.prototype.next = function(name, subrun) {\n // juggle parameters if it looks like no name is given\n if(typeof(name) === 'function') {\n subrun = name;\n\n // inherit parent's name\n name = this.name;\n }\n // create subtask, set parent to this task, propagate callbacks\n var subtask = new Task({\n run: subrun,\n name: name,\n parent: this\n });\n // start subtasks running\n subtask.state = RUNNING;\n subtask.type = this.type;\n subtask.successCallback = this.successCallback || null;\n subtask.failureCallback = this.failureCallback || null;\n\n // queue a new subtask\n this.subtasks.push(subtask);\n\n return this;\n};\n\n/**\n * Adds subtasks to run in parallel after task.doNext() or task.fail()\n * is called.\n *\n * @param name human readable name for this task (optional).\n * @param subrun functions to run that take the current task as\n * their first parameter.\n *\n * @return the current task (useful for chaining next() calls).\n */\nTask.prototype.parallel = function(name, subrun) {\n // juggle parameters if it looks like no name is given\n if(forge.util.isArray(name)) {\n subrun = name;\n\n // inherit parent's name\n name = this.name;\n }\n // Wrap parallel tasks in a regular task so they are started at the\n // proper time.\n return this.next(name, function(task) {\n // block waiting for subtasks\n var ptask = task;\n ptask.block(subrun.length);\n\n // we pass the iterator from the loop below as a parameter\n // to a function because it is otherwise included in the\n // closure and changes as the loop changes -- causing i\n // to always be set to its highest value\n var startParallelTask = function(pname, pi) {\n forge.task.start({\n type: pname,\n run: function(task) {\n subrun[pi](task);\n },\n success: function(task) {\n ptask.unblock();\n },\n failure: function(task) {\n ptask.unblock();\n }\n });\n };\n\n for(var i = 0; i < subrun.length; i++) {\n // Type must be unique so task starts in parallel:\n // name + private string + task id + sub-task index\n // start tasks in parallel and unblock when the finish\n var pname = name + '__parallel-' + task.id + '-' + i;\n var pi = i;\n startParallelTask(pname, pi);\n }\n });\n};\n\n/**\n * Stops a running task.\n */\nTask.prototype.stop = function() {\n this.state = sStateTable[this.state][STOP];\n};\n\n/**\n * Starts running a task.\n */\nTask.prototype.start = function() {\n this.error = false;\n this.state = sStateTable[this.state][START];\n\n // try to restart\n if(this.state === RUNNING) {\n this.start = new Date();\n this.run(this);\n runNext(this, 0);\n }\n};\n\n/**\n * Blocks a task until it one or more permits have been released. The\n * task will not resume until the requested number of permits have\n * been released with call(s) to unblock().\n *\n * @param n number of permits to wait for(default: 1).\n */\nTask.prototype.block = function(n) {\n n = typeof(n) === 'undefined' ? 1 : n;\n this.blocks += n;\n if(this.blocks > 0) {\n this.state = sStateTable[this.state][BLOCK];\n }\n};\n\n/**\n * Releases a permit to unblock a task. If a task was blocked by\n * requesting N permits via block(), then it will only continue\n * running once enough permits have been released via unblock() calls.\n *\n * If multiple processes need to synchronize with a single task then\n * use a condition variable (see forge.task.createCondition). It is\n * an error to unblock a task more times than it has been blocked.\n *\n * @param n number of permits to release (default: 1).\n *\n * @return the current block count (task is unblocked when count is 0)\n */\nTask.prototype.unblock = function(n) {\n n = typeof(n) === 'undefined' ? 1 : n;\n this.blocks -= n;\n if(this.blocks === 0 && this.state !== DONE) {\n this.state = RUNNING;\n runNext(this, 0);\n }\n return this.blocks;\n};\n\n/**\n * Sleep for a period of time before resuming tasks.\n *\n * @param n number of milliseconds to sleep (default: 0).\n */\nTask.prototype.sleep = function(n) {\n n = typeof(n) === 'undefined' ? 0 : n;\n this.state = sStateTable[this.state][SLEEP];\n var self = this;\n this.timeoutId = setTimeout(function() {\n self.timeoutId = null;\n self.state = RUNNING;\n runNext(self, 0);\n }, n);\n};\n\n/**\n * Waits on a condition variable until notified. The next task will\n * not be scheduled until notification. A condition variable can be\n * created with forge.task.createCondition().\n *\n * Once cond.notify() is called, the task will continue.\n *\n * @param cond the condition variable to wait on.\n */\nTask.prototype.wait = function(cond) {\n cond.wait(this);\n};\n\n/**\n * If sleeping, wakeup and continue running tasks.\n */\nTask.prototype.wakeup = function() {\n if(this.state === SLEEPING) {\n cancelTimeout(this.timeoutId);\n this.timeoutId = null;\n this.state = RUNNING;\n runNext(this, 0);\n }\n};\n\n/**\n * Cancel all remaining subtasks of this task.\n */\nTask.prototype.cancel = function() {\n this.state = sStateTable[this.state][CANCEL];\n // remove permits needed\n this.permitsNeeded = 0;\n // cancel timeouts\n if(this.timeoutId !== null) {\n cancelTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n // remove subtasks\n this.subtasks = [];\n};\n\n/**\n * Finishes this task with failure and sets error flag. The entire\n * task will be aborted unless the next task that should execute\n * is passed as a parameter. This allows levels of subtasks to be\n * skipped. For instance, to abort only this tasks's subtasks, then\n * call fail(task.parent). To abort this task's subtasks and its\n * parent's subtasks, call fail(task.parent.parent). To abort\n * all tasks and simply call the task callback, call fail() or\n * fail(null).\n *\n * The task callback (success or failure) will always, eventually, be\n * called.\n *\n * @param next the task to continue at, or null to abort entirely.\n */\nTask.prototype.fail = function(next) {\n // set error flag\n this.error = true;\n\n // finish task\n finish(this, true);\n\n if(next) {\n // propagate task info\n next.error = this.error;\n next.swapTime = this.swapTime;\n next.userData = this.userData;\n\n // do next task as specified\n runNext(next, 0);\n } else {\n if(this.parent !== null) {\n // finish root task (ensures it is removed from task queue)\n var parent = this.parent;\n while(parent.parent !== null) {\n // propagate task info\n parent.error = this.error;\n parent.swapTime = this.swapTime;\n parent.userData = this.userData;\n parent = parent.parent;\n }\n finish(parent, true);\n }\n\n // call failure callback if one exists\n if(this.failureCallback) {\n this.failureCallback(this);\n }\n }\n};\n\n/**\n * Asynchronously start a task.\n *\n * @param task the task to start.\n */\nvar start = function(task) {\n task.error = false;\n task.state = sStateTable[task.state][START];\n setTimeout(function() {\n if(task.state === RUNNING) {\n task.swapTime = +new Date();\n task.run(task);\n runNext(task, 0);\n }\n }, 0);\n};\n\n/**\n * Run the next subtask or finish this task.\n *\n * @param task the task to process.\n * @param recurse the recursion count.\n */\nvar runNext = function(task, recurse) {\n // get time since last context swap (ms), if enough time has passed set\n // swap to true to indicate that doNext was performed asynchronously\n // also, if recurse is too high do asynchronously\n var swap =\n (recurse > sMaxRecursions) ||\n (+new Date() - task.swapTime) > sTimeSlice;\n\n var doNext = function(recurse) {\n recurse++;\n if(task.state === RUNNING) {\n if(swap) {\n // update swap time\n task.swapTime = +new Date();\n }\n\n if(task.subtasks.length > 0) {\n // run next subtask\n var subtask = task.subtasks.shift();\n subtask.error = task.error;\n subtask.swapTime = task.swapTime;\n subtask.userData = task.userData;\n subtask.run(subtask);\n if(!subtask.error) {\n runNext(subtask, recurse);\n }\n } else {\n finish(task);\n\n if(!task.error) {\n // chain back up and run parent\n if(task.parent !== null) {\n // propagate task info\n task.parent.error = task.error;\n task.parent.swapTime = task.swapTime;\n task.parent.userData = task.userData;\n\n // no subtasks left, call run next subtask on parent\n runNext(task.parent, recurse);\n }\n }\n }\n }\n };\n\n if(swap) {\n // we're swapping, so run asynchronously\n setTimeout(doNext, 0);\n } else {\n // not swapping, so run synchronously\n doNext(recurse);\n }\n};\n\n/**\n * Finishes a task and looks for the next task in the queue to start.\n *\n * @param task the task to finish.\n * @param suppressCallbacks true to suppress callbacks.\n */\nvar finish = function(task, suppressCallbacks) {\n // subtask is now done\n task.state = DONE;\n\n delete sTasks[task.id];\n if(sVL >= 1) {\n forge.log.verbose(cat, '[%s][%s] finish',\n task.id, task.name, task);\n }\n\n // only do queue processing for root tasks\n if(task.parent === null) {\n // report error if queue is missing\n if(!(task.type in sTaskQueues)) {\n forge.log.error(cat,\n '[%s][%s] task queue missing [%s]',\n task.id, task.name, task.type);\n } else if(sTaskQueues[task.type].length === 0) {\n // report error if queue is empty\n forge.log.error(cat,\n '[%s][%s] task queue empty [%s]',\n task.id, task.name, task.type);\n } else if(sTaskQueues[task.type][0] !== task) {\n // report error if this task isn't the first in the queue\n forge.log.error(cat,\n '[%s][%s] task not first in queue [%s]',\n task.id, task.name, task.type);\n } else {\n // remove ourselves from the queue\n sTaskQueues[task.type].shift();\n // clean up queue if it is empty\n if(sTaskQueues[task.type].length === 0) {\n if(sVL >= 1) {\n forge.log.verbose(cat, '[%s][%s] delete queue [%s]',\n task.id, task.name, task.type);\n }\n /* Note: Only a task can delete a queue of its own type. This\n is used as a way to synchronize tasks. If a queue for a certain\n task type exists, then a task of that type is running.\n */\n delete sTaskQueues[task.type];\n } else {\n // dequeue the next task and start it\n if(sVL >= 1) {\n forge.log.verbose(cat,\n '[%s][%s] queue start next [%s] remain:%s',\n task.id, task.name, task.type,\n sTaskQueues[task.type].length);\n }\n sTaskQueues[task.type][0].start();\n }\n }\n\n if(!suppressCallbacks) {\n // call final callback if one exists\n if(task.error && task.failureCallback) {\n task.failureCallback(task);\n } else if(!task.error && task.successCallback) {\n task.successCallback(task);\n }\n }\n }\n};\n\n/* Tasks API */\nmodule.exports = forge.task = forge.task || {};\n\n/**\n * Starts a new task that will run the passed function asynchronously.\n *\n * In order to finish the task, either task.doNext() or task.fail()\n * *must* be called.\n *\n * The task must have a type (a string identifier) that can be used to\n * synchronize it with other tasks of the same type. That type can also\n * be used to cancel tasks that haven't started yet.\n *\n * To start a task, the following object must be provided as a parameter\n * (each function takes a task object as its first parameter):\n *\n * {\n * type: the type of task.\n * run: the function to run to execute the task.\n * success: a callback to call when the task succeeds (optional).\n * failure: a callback to call when the task fails (optional).\n * }\n *\n * @param options the object as described above.\n */\nforge.task.start = function(options) {\n // create a new task\n var task = new Task({\n run: options.run,\n name: options.name || sNoTaskName\n });\n task.type = options.type;\n task.successCallback = options.success || null;\n task.failureCallback = options.failure || null;\n\n // append the task onto the appropriate queue\n if(!(task.type in sTaskQueues)) {\n if(sVL >= 1) {\n forge.log.verbose(cat, '[%s][%s] create queue [%s]',\n task.id, task.name, task.type);\n }\n // create the queue with the new task\n sTaskQueues[task.type] = [task];\n start(task);\n } else {\n // push the task onto the queue, it will be run after a task\n // with the same type completes\n sTaskQueues[options.type].push(task);\n }\n};\n\n/**\n * Cancels all tasks of the given type that haven't started yet.\n *\n * @param type the type of task to cancel.\n */\nforge.task.cancel = function(type) {\n // find the task queue\n if(type in sTaskQueues) {\n // empty all but the current task from the queue\n sTaskQueues[type] = [sTaskQueues[type][0]];\n }\n};\n\n/**\n * Creates a condition variable to synchronize tasks. To make a task wait\n * on the condition variable, call task.wait(condition). To notify all\n * tasks that are waiting, call condition.notify().\n *\n * @return the condition variable.\n */\nforge.task.createCondition = function() {\n var cond = {\n // all tasks that are blocked\n tasks: {}\n };\n\n /**\n * Causes the given task to block until notify is called. If the task\n * is already waiting on this condition then this is a no-op.\n *\n * @param task the task to cause to wait.\n */\n cond.wait = function(task) {\n // only block once\n if(!(task.id in cond.tasks)) {\n task.block();\n cond.tasks[task.id] = task;\n }\n };\n\n /**\n * Notifies all waiting tasks to wake up.\n */\n cond.notify = function() {\n // since unblock() will run the next task from here, make sure to\n // clear the condition's blocked task list before unblocking\n var tmp = cond.tasks;\n cond.tasks = {};\n for(var id in tmp) {\n tmp[id].unblock();\n }\n };\n\n return cond;\n};\n","/**\n * Node.js module for Forge.\n *\n * @author Dave Longley\n *\n * Copyright 2011-2016 Digital Bazaar, Inc.\n */\nmodule.exports = require('./forge');\nrequire('./aes');\nrequire('./aesCipherSuites');\nrequire('./asn1');\nrequire('./cipher');\nrequire('./debug');\nrequire('./des');\nrequire('./ed25519');\nrequire('./hmac');\nrequire('./kem');\nrequire('./log');\nrequire('./md.all');\nrequire('./mgf1');\nrequire('./pbkdf2');\nrequire('./pem');\nrequire('./pkcs1');\nrequire('./pkcs12');\nrequire('./pkcs7');\nrequire('./pki');\nrequire('./prime');\nrequire('./prng');\nrequire('./pss');\nrequire('./random');\nrequire('./rc2');\nrequire('./ssh');\nrequire('./task');\nrequire('./tls');\nrequire('./util');\n","var forge = require('node-forge');\n\n// a hexString is considered negative if it's most significant bit is 1\n// because serial numbers use ones' complement notation\n// this RFC in section 4.1.2.2 requires serial numbers to be positive\n// http://www.ietf.org/rfc/rfc5280.txt\nfunction toPositiveHex(hexString){\n var mostSiginficativeHexAsInt = parseInt(hexString[0], 16);\n if (mostSiginficativeHexAsInt < 8){\n return hexString;\n }\n\n mostSiginficativeHexAsInt -= 8;\n return mostSiginficativeHexAsInt.toString() + hexString.substring(1);\n}\n\nfunction getAlgorithm(key) {\n switch (key) {\n case 'sha256':\n return forge.md.sha256.create();\n default:\n return forge.md.sha1.create();\n }\n}\n\n/**\n *\n * @param {forge.pki.CertificateField[]} attrs Attributes used for subject and issuer.\n * @param {object} options\n * @param {number} [options.days=365] the number of days before expiration\n * @param {number} [options.keySize=1024] the size for the private key in bits\n * @param {object} [options.extensions] additional extensions for the certificate\n * @param {string} [options.algorithm=\"sha1\"] The signature algorithm sha256 or sha1\n * @param {boolean} [options.pkcs7=false] include PKCS#7 as part of the output\n * @param {boolean} [options.clientCertificate=false] generate client cert signed by the original key\n * @param {string} [options.clientCertificateCN=\"John Doe jdoe123\"] client certificate's common name\n * @param {function} [done] Optional callback, if not provided the generation is synchronous\n * @returns\n */\nexports.generate = function generate(attrs, options, done) {\n if (typeof attrs === 'function') {\n done = attrs;\n attrs = undefined;\n } else if (typeof options === 'function') {\n done = options;\n options = {};\n }\n\n options = options || {};\n\n var generatePem = function (keyPair) {\n var cert = forge.pki.createCertificate();\n\n cert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); // the serial number can be decimal or hex (if preceded by 0x)\n\n cert.validity.notBefore = new Date();\n cert.validity.notAfter = new Date();\n cert.validity.notAfter.setDate(cert.validity.notBefore.getDate() + (options.days || 365));\n\n attrs = attrs || [{\n name: 'commonName',\n value: 'example.org'\n }, {\n name: 'countryName',\n value: 'US'\n }, {\n shortName: 'ST',\n value: 'Virginia'\n }, {\n name: 'localityName',\n value: 'Blacksburg'\n }, {\n name: 'organizationName',\n value: 'Test'\n }, {\n shortName: 'OU',\n value: 'Test'\n }];\n\n cert.setSubject(attrs);\n cert.setIssuer(attrs);\n\n cert.publicKey = keyPair.publicKey;\n\n cert.setExtensions(options.extensions || [{\n name: 'basicConstraints',\n cA: true\n }, {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true\n }, {\n name: 'subjectAltName',\n altNames: [{\n type: 6, // URI\n value: 'http://example.org/webid#me'\n }]\n }]);\n\n cert.sign(keyPair.privateKey, getAlgorithm(options && options.algorithm));\n\n const fingerprint = forge.md.sha1\n .create()\n .update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes())\n .digest()\n .toHex()\n .match(/.{2}/g)\n .join(':');\n\n var pem = {\n private: forge.pki.privateKeyToPem(keyPair.privateKey),\n public: forge.pki.publicKeyToPem(keyPair.publicKey),\n cert: forge.pki.certificateToPem(cert),\n fingerprint: fingerprint,\n };\n\n if (options && options.pkcs7) {\n var p7 = forge.pkcs7.createSignedData();\n p7.addCertificate(cert);\n pem.pkcs7 = forge.pkcs7.messageToPem(p7);\n }\n\n if (options && options.clientCertificate) {\n var clientkeys = forge.pki.rsa.generateKeyPair(1024);\n var clientcert = forge.pki.createCertificate();\n clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9)));\n clientcert.validity.notBefore = new Date();\n clientcert.validity.notAfter = new Date();\n clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1);\n\n var clientAttrs = JSON.parse(JSON.stringify(attrs));\n\n for(var i = 0; i < clientAttrs.length; i++) {\n if(clientAttrs[i].name === 'commonName') {\n if( options.clientCertificateCN )\n clientAttrs[i] = { name: 'commonName', value: options.clientCertificateCN };\n else\n clientAttrs[i] = { name: 'commonName', value: 'John Doe jdoe123' };\n }\n }\n\n clientcert.setSubject(clientAttrs);\n\n // Set the issuer to the parent key\n clientcert.setIssuer(attrs);\n\n clientcert.publicKey = clientkeys.publicKey;\n\n // Sign client cert with root cert\n clientcert.sign(keyPair.privateKey);\n\n pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey);\n pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey);\n pem.clientcert = forge.pki.certificateToPem(clientcert);\n\n if (options.pkcs7) {\n var clientp7 = forge.pkcs7.createSignedData();\n clientp7.addCertificate(clientcert);\n pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7);\n }\n }\n\n var caStore = forge.pki.createCaStore();\n caStore.addCertificate(cert);\n\n try {\n forge.pki.verifyCertificateChain(caStore, [cert],\n function (vfd, depth, chain) {\n if (vfd !== true) {\n throw new Error('Certificate could not be verified.');\n }\n return true;\n });\n }\n catch(ex) {\n throw new Error(ex);\n }\n\n return pem;\n };\n\n var keySize = options.keySize || 1024;\n\n if (done) { // async scenario\n return forge.pki.rsa.generateKeyPair({ bits: keySize }, function (err, keyPair) {\n if (err) { return done(err); }\n\n try {\n return done(null, generatePem(keyPair));\n } catch (ex) {\n return done(ex);\n }\n });\n }\n\n var keyPair = options.keyPair ? {\n privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey),\n publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey)\n } : forge.pki.rsa.generateKeyPair(keySize);\n\n return generatePem(keyPair);\n};\n"],"names":["forge","baseN","require$$0","require$$1","util","global","_createCipher","_updateBlock","registerAlgorithm","oids","asn1","_initialized","_init","_update","_padding","_k","_crypto","BigInteger","pki","privateKeyValidator","publicKeyValidator","contentInfoValidator","tls","sha512"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAOAA,OAAc,GAAG;AACjB;AACA,EAAE,OAAO,EAAE;AACX,IAAI,iBAAiB,EAAE,KAAK;AAC5B,GAAG;AACH,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACkBD,IAAI,GAAG,GAAG,EAAE,CAAC;IACbC,OAAc,GAAG,GAAG,CAAC;AACrB;AACA;AACA,IAAI,iBAAiB,GAAG,EAAE,CAAC;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,CAAC,MAAM,GAAG,SAAS,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE;AAChD,EAAE,GAAG,OAAO,QAAQ,KAAK,QAAQ,EAAE;AACnC,IAAI,MAAM,IAAI,SAAS,CAAC,8BAA8B,CAAC,CAAC;AACxD,GAAG;AACH,EAAE,GAAG,OAAO,KAAK,SAAS,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC3D,IAAI,MAAM,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AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,UAAU,GAAG;AACtB,EAAE,IAAI,GAAG,IAAI,CAAC;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC5E;AACA;AACA,EAAE,IAAI,KAAK,GAAG,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;AAC7B,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,EAAE,CAAC,EAAE;AAC/B,IAAI,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACtB,IAAI,KAAK,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC;AAC5C,GAAG;AACH;AACA;AACA,EAAE,IAAI,GAAG,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;AACxB,EAAE,KAAK,GAAG,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;AACzB,EAAE,GAAG,GAAG,IAAI,KAA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GAAG,CAAC,CAAC,CAAC,CAAC;AAChB,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;AAChB,IAAI,GAAG,GAAG,IAAI,CAAC;AACf,GAAG;AACH,EAAE,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;AAC7B,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACtB,EAAE,CAAC,GAAG,KAAK,CAAC,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACtB,EAAE,CAAC,GAAG,KAAK,CAAC,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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AAC,CAAC;AACF;AACA;AACA;AACA;AACAA,KAAG,CAAC,gBAAgB,GAAG;AACvB,EAAE,eAAe,EAAE,0BAA0B;AAC7C,EAAE,uBAAuB,EAAE,kCAAkC;AAC7D,EAAE,mBAAmB,EAAE,8BAA8B;AACrD,EAAE,mBAAmB,EAAE,8BAA8B;AACrD,EAAE,mBAAmB,EAAE,8BAA8B;AACrD,EAAE,UAAU,EAAE,uCAAuC;AACrD,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAA,KAAG,CAAC,sBAAsB,GAAG,SAAS,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,GAAG,OAAO,OAAO,KAAK,UAAU,EAAE;AACpC,IAAI,OAAO,GAAG,CAAC,MAAM,EAAE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EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACvE,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAA,KAAG,CAAC,YAAY,GAAG,SAAS,CAAC,EAAE,EAAE,EAAE;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,GAAG,GAAG,QAAQ,CAAC;AACrB;AACA;AACA,EAAE,IAAI,MAAM,GAAG,EAAE,CAAC,aAAa,GAAG,EAAE,CAAC,aAAa,CAAC;AACnD;AACA;AACA,EAAE,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE;AAC1B;AACA,IAAI,EAAE,CAAC,aAAa,GAAG,GAAG;AAC1B,MAAM,EAAE,CAAC,iBAAiB,EAAE,eAAe,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC;AACjE,IAAI,EAAE,CAAC,iBAAiB,GAAG,IAAI,CAAC;AAChC,GAAG;AACH;AACA;AAC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AAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AAClB,KAAK;AACL;AACA;AACA,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;AACvB,GAAG,CAAC;AACJ;AACA,EAAE,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AACF;AACA;AACiBtB,OAAK,CAAC,GAAG,GAAGA,OAAK,CAAC,GAAG,IAAI,GAAG;AAC7C;AACA;AACA,IAAI,IAAI,GAAG,IAAIsB,KAAG,EAAE;AACpB,EAAE,GAAG,OAAOA,KAAG,CAAC,GAAG,CAAC,KAAK,UAAU,EAAE;AACrC,IAAItB,OAAK,CAAC,GAAG,CAAC,GAAG,CAAC,GAAGsB,KAAG,CAAC,GAAG,CAAC,CAAC;AAC9B,GAAG;AACH,CAAC;AACD;AACA;AACAtB,OAAK,CAAC,GAAG,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC9B;AACA;AACAA,OAAK,CAAC,GAAG,CAAC,SAAS,GAAG,SAAS,CAAC;AAChC;AACA;AACAA,OAAK,CAAC,GAAG,CAAC,kBAAkB,GAAGsB,KAAG,CAAC,kBAAkB,CAAC;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAtB,OAAK,CAAC,GAAG,CAA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AE,CAAC,CAAC;AAC1B,KAAK;AACL;AACA,IAAI,OAAO,GAAG,CAAC;AACf,GAAG,CAAC;AACJ;AACA,EAAE,IAAI,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC;AACxC;AACA,EAAE,IAAI,IAAI,EAAE;AACZ,IAAI,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,UAAU,GAAG,EAAE,OAAO,EAAE;AACpF,MAAM,IAAI,GAAG,EAAE,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE;AACpC;AACA,MAAM,IAAI;AACV,QAAQ,OAAO,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;AAChD,OAAO,CAAC,OAAO,EAAE,EAAE;AACnB,QAAQ,OAAO,IAAI,CAAC,EAAE,CAAC,CAAC;AACxB,OAAO;AACP,KAAK,CAAC,CAAC;AACP,GAAG;AACH;AACA,EAAE,IAAI,OAAO,GAAG,OAAO,CAAC,OAAO,GAAG;AAClC,IAAI,UAAU,EAAE,KAAK,CAAC,GAAG,CAAC,iBAAiB,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC;AACvE,IAAI,SAAS,EAAE,KAAK,CAAC,GAAG,CAAC,gBAAgB,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC;AACpE,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;AAC7C;AACA,EAAE,OAAO,WAAW,CAAC,OAAO,CAAC,CAAC;AAC9B,CAAC;;;;;;;;"} \ No newline at end of file diff --git a/packages/astro/vendor/vite/dist/node/chunks/dep-35df7f96.js b/packages/astro/vendor/vite/dist/node/chunks/dep-35df7f96.js deleted file mode 100755 index 9365f132bd0f..000000000000 --- a/packages/astro/vendor/vite/dist/node/chunks/dep-35df7f96.js +++ /dev/null @@ -1,92088 +0,0 @@ -'use strict'; - -var fs$r = require('fs'); -var path$t = require('path'); -var require$$0$b = require('events'); -var require$$0$6 = require('util'); -var require$$0$a = require('stream'); -var require$$0$5 = require('os'); -var perf_hooks = require('perf_hooks'); -var require$$0$8 = require('url'); -var require$$1 = require('crypto'); -var require$$0$7 = require('module'); -var esbuild = require('esbuild'); -var require$$1$1 = require('worker_threads'); -var require$$5 = require('assert'); -var require$$1$4 = require('child_process'); -var readline = require('readline'); -var require$$0$9 = require('zlib'); -var resolve$4 = require('resolve'); -var qs = require('querystring'); -var require$$0$4 = require('tty'); -var require$$3 = require('net'); -var require$$1$2 = require('http'); -var require$$0$c = require('buffer'); -var require$$1$3 = require('https'); -var require$$4 = require('tls'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; } - -function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - for (var k in e) { - n[k] = e[k]; - } - } - n["default"] = e; - return n; -} - -var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$r); -var fs__namespace = /*#__PURE__*/_interopNamespace(fs$r); -var path__default = /*#__PURE__*/_interopDefaultLegacy(path$t); -var require$$0__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$0$b); -var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6); -var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$a); -var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$5); -var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$8); -var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1); -var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7); -var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1$1); -var require$$5__default = /*#__PURE__*/_interopDefaultLegacy(require$$5); -var require$$1__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$1$4); -var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline); -var require$$0__default$7 = /*#__PURE__*/_interopDefaultLegacy(require$$0$9); -var resolve__default = /*#__PURE__*/_interopDefaultLegacy(resolve$4); -var qs__namespace = /*#__PURE__*/_interopNamespace(qs); -var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); -var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3); -var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2); -var require$$0__default$8 = /*#__PURE__*/_interopDefaultLegacy(require$$0$c); -var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3); -var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4); - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var a = Object.defineProperty({}, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; -} - -function commonjsRequire (path) { - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); -} - -var ansiStyles$2 = {exports: {}}; - -var colorName$1 = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; - -/* MIT license */ - -/* eslint-disable no-mixed-operators */ -const cssKeywords$1 = colorName$1; - -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) - -const reverseKeywords$1 = {}; -for (const key of Object.keys(cssKeywords$1)) { - reverseKeywords$1[cssKeywords$1[key]] = key; -} - -const convert$3 = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} -}; - -var conversions$5 = convert$3; - -// Hide .channels and .labels properties -for (const model of Object.keys(convert$3)) { - if (!('channels' in convert$3[model])) { - throw new Error('missing channels property: ' + model); - } - - if (!('labels' in convert$3[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert$3[model].labels.length !== convert$3[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - const {channels, labels} = convert$3[model]; - delete convert$3[model].channels; - delete convert$3[model].labels; - Object.defineProperty(convert$3[model], 'channels', {value: channels}); - Object.defineProperty(convert$3[model], 'labels', {value: labels}); -} - -convert$3.rgb.hsl = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - const l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - - return [h, s * 100, l * 100]; -}; - -convert$3.rgb.hsv = function (rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; - - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; - - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } - - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - - return [ - h * 360, - s * 100, - v * 100 - ]; -}; - -convert$3.rgb.hwb = function (rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert$3.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); - - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - - return [h, w * 100, b * 100]; -}; - -convert$3.rgb.cmyk = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; - - return [c * 100, m * 100, y * 100, k * 100]; -}; - -function comparativeDistance$1(x, y) { - /* - See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - */ - return ( - ((x[0] - y[0]) ** 2) + - ((x[1] - y[1]) ** 2) + - ((x[2] - y[2]) ** 2) - ); -} - -convert$3.rgb.keyword = function (rgb) { - const reversed = reverseKeywords$1[rgb]; - if (reversed) { - return reversed; - } - - let currentClosestDistance = Infinity; - let currentClosestKeyword; - - for (const keyword of Object.keys(cssKeywords$1)) { - const value = cssKeywords$1[keyword]; - - // Compute comparative distance - const distance = comparativeDistance$1(rgb, value); - - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - - return currentClosestKeyword; -}; - -convert$3.keyword.rgb = function (keyword) { - return cssKeywords$1[keyword]; -}; - -convert$3.rgb.xyz = function (rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; - - // Assume sRGB - r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); - g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); - b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); - - const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); - - return [x * 100, y * 100, z * 100]; -}; - -convert$3.rgb.lab = function (rgb) { - const xyz = convert$3.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; -}; - -convert$3.hsl.rgb = function (hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t2; - let t3; - let val; - - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - - const t1 = 2 * l - t2; - - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - - if (t3 > 1) { - t3--; - } - - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } - - rgb[i] = val * 255; - } - - return rgb; -}; - -convert$3.hsl.hsv = function (hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); - - return [h, sv * 100, v * 100]; -}; - -convert$3.hsv.rgb = function (hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; - - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - (s * f)); - const t = 255 * v * (1 - (s * (1 - f))); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } -}; - -convert$3.hsv.hsl = function (hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; - - l = (2 - s) * v; - const lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - - return [h, sl * 100, l * 100]; -}; - -// http://dev.w3.org/csswg/css-color/#hwb-to-rgb -convert$3.hwb.rgb = function (hwb) { - const h = hwb[0] / 360; - let wh = hwb[1] / 100; - let bl = hwb[2] / 100; - const ratio = wh + bl; - let f; - - // Wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; - - if ((i & 0x01) !== 0) { - f = 1 - f; - } - - const n = wh + f * (v - wh); // Linear interpolation - - let r; - let g; - let b; - /* eslint-disable max-statements-per-line,no-multi-spaces */ - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } - /* eslint-enable max-statements-per-line,no-multi-spaces */ - - return [r * 255, g * 255, b * 255]; -}; - -convert$3.cmyk.rgb = function (cmyk) { - const c = cmyk[0] / 100; - const m = cmyk[1] / 100; - const y = cmyk[2] / 100; - const k = cmyk[3] / 100; - - const r = 1 - Math.min(1, c * (1 - k) + k); - const g = 1 - Math.min(1, m * (1 - k) + k); - const b = 1 - Math.min(1, y * (1 - k) + k); - - return [r * 255, g * 255, b * 255]; -}; - -convert$3.xyz.rgb = function (xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z = xyz[2] / 100; - let r; - let g; - let b; - - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); - - // Assume sRGB - r = r > 0.0031308 - ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) - : r * 12.92; - - g = g > 0.0031308 - ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) - : g * 12.92; - - b = b > 0.0031308 - ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) - : b * 12.92; - - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); - - return [r * 255, g * 255, b * 255]; -}; - -convert$3.xyz.lab = function (xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; -}; - -convert$3.lab.xyz = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z; - - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; - - const y2 = y ** 3; - const x2 = x ** 3; - const z2 = z ** 3; - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; - - x *= 95.047; - y *= 100; - z *= 108.883; - - return [x, y, z]; -}; - -convert$3.lab.lch = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; - - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - - if (h < 0) { - h += 360; - } - - const c = Math.sqrt(a * a + b * b); - - return [l, c, h]; -}; - -convert$3.lch.lab = function (lch) { - const l = lch[0]; - const c = lch[1]; - const h = lch[2]; - - const hr = h / 360 * 2 * Math.PI; - const a = c * Math.cos(hr); - const b = c * Math.sin(hr); - - return [l, a, b]; -}; - -convert$3.rgb.ansi16 = function (args, saturation = null) { - const [r, g, b] = args; - let value = saturation === null ? convert$3.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization - - value = Math.round(value / 50); - - if (value === 0) { - return 30; - } - - let ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); - - if (value === 2) { - ansi += 60; - } - - return ansi; -}; - -convert$3.hsv.ansi16 = function (args) { - // Optimization here; we already know the value and don't need to get - // it converted for us. - return convert$3.rgb.ansi16(convert$3.hsv.rgb(args), args[2]); -}; - -convert$3.rgb.ansi256 = function (args) { - const r = args[0]; - const g = args[1]; - const b = args[2]; - - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } - - if (r > 248) { - return 231; - } - - return Math.round(((r - 8) / 247) * 24) + 232; - } - - const ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); - - return ansi; -}; - -convert$3.ansi16.rgb = function (args) { - let color = args % 10; - - // Handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - - color = color / 10.5 * 255; - - return [color, color, color]; - } - - const mult = (~~(args > 50) + 1) * 0.5; - const r = ((color & 1) * mult) * 255; - const g = (((color >> 1) & 1) * mult) * 255; - const b = (((color >> 2) & 1) * mult) * 255; - - return [r, g, b]; -}; - -convert$3.ansi256.rgb = function (args) { - // Handle greyscale - if (args >= 232) { - const c = (args - 232) * 10 + 8; - return [c, c, c]; - } - - args -= 16; - - let rem; - const r = Math.floor(args / 36) / 5 * 255; - const g = Math.floor((rem = args % 36) / 6) / 5 * 255; - const b = (rem % 6) / 5 * 255; - - return [r, g, b]; -}; - -convert$3.rgb.hex = function (args) { - const integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert$3.hex.rgb = function (args) { - const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } - - let colorString = match[0]; - - if (match[0].length === 3) { - colorString = colorString.split('').map(char => { - return char + char; - }).join(''); - } - - const integer = parseInt(colorString, 16); - const r = (integer >> 16) & 0xFF; - const g = (integer >> 8) & 0xFF; - const b = integer & 0xFF; - - return [r, g, b]; -}; - -convert$3.rgb.hcg = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const max = Math.max(Math.max(r, g), b); - const min = Math.min(Math.min(r, g), b); - const chroma = (max - min); - let grayscale; - let hue; - - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } - - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma; - } - - hue /= 6; - hue %= 1; - - return [hue * 360, chroma * 100, grayscale * 100]; -}; - -convert$3.hsl.hcg = function (hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; - - const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); - - let f = 0; - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } - - return [hsl[0], c * 100, f * 100]; -}; - -convert$3.hsv.hcg = function (hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; - - const c = s * v; - let f = 0; - - if (c < 1.0) { - f = (v - c) / (1 - c); - } - - return [hsv[0], c * 100, f * 100]; -}; - -convert$3.hcg.rgb = function (hcg) { - const h = hcg[0] / 360; - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } - - const pure = [0, 0, 0]; - const hi = (h % 1) * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; - - /* eslint-disable max-statements-per-line */ - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } - /* eslint-enable max-statements-per-line */ - - mg = (1.0 - c) * g; - - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; - -convert$3.hcg.hsv = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const v = c + g * (1.0 - c); - let f = 0; - - if (v > 0.0) { - f = c / v; - } - - return [hcg[0], f * 100, v * 100]; -}; - -convert$3.hcg.hsl = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const l = g * (1.0 - c) + 0.5 * c; - let s = 0; - - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } - - return [hcg[0], s * 100, l * 100]; -}; - -convert$3.hcg.hwb = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; -}; - -convert$3.hwb.hcg = function (hwb) { - const w = hwb[1] / 100; - const b = hwb[2] / 100; - const v = 1 - b; - const c = v - w; - let g = 0; - - if (c < 1) { - g = (v - c) / (1 - c); - } - - return [hwb[0], c * 100, g * 100]; -}; - -convert$3.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; -}; - -convert$3.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; -}; - -convert$3.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; - -convert$3.gray.hsl = function (args) { - return [0, 0, args[0]]; -}; - -convert$3.gray.hsv = convert$3.gray.hsl; - -convert$3.gray.hwb = function (gray) { - return [0, 100, gray[0]]; -}; - -convert$3.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; -}; - -convert$3.gray.lab = function (gray) { - return [gray[0], 0, 0]; -}; - -convert$3.gray.hex = function (gray) { - const val = Math.round(gray[0] / 100 * 255) & 0xFF; - const integer = (val << 16) + (val << 8) + val; - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert$3.rgb.gray = function (rgb) { - const val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; -}; - -const conversions$4 = conversions$5; - -/* - This function routes a model to all other models. - - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). - - conversions that are not possible simply are not included. -*/ - -function buildGraph$1() { - const graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - const models = Object.keys(conversions$4); - - for (let len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - - return graph; -} - -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS$1(fromModel) { - const graph = buildGraph$1(); - const queue = [fromModel]; // Unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - const current = queue.pop(); - const adjacents = Object.keys(conversions$4[current]); - - for (let len = adjacents.length, i = 0; i < len; i++) { - const adjacent = adjacents[i]; - const node = graph[adjacent]; - - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } - - return graph; -} - -function link$1(from, to) { - return function (args) { - return to(from(args)); - }; -} - -function wrapConversion$1(toModel, graph) { - const path = [graph[toModel].parent, toModel]; - let fn = conversions$4[graph[toModel].parent][toModel]; - - let cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link$1(conversions$4[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; -} - -var route$3 = function (fromModel) { - const graph = deriveBFS$1(fromModel); - const conversion = {}; - - const models = Object.keys(graph); - for (let len = models.length, i = 0; i < len; i++) { - const toModel = models[i]; - const node = graph[toModel]; - - if (node.parent === null) { - // No possible conversion, or this node is the source model. - continue; - } - - conversion[toModel] = wrapConversion$1(toModel, graph); - } - - return conversion; -}; - -const conversions$3 = conversions$5; -const route$2 = route$3; - -const convert$2 = {}; - -const models$1 = Object.keys(conversions$3); - -function wrapRaw$1(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - return fn(args); - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -function wrapRounded$1(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - const result = fn(args); - - // We're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (let len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - - return result; - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -models$1.forEach(fromModel => { - convert$2[fromModel] = {}; - - Object.defineProperty(convert$2[fromModel], 'channels', {value: conversions$3[fromModel].channels}); - Object.defineProperty(convert$2[fromModel], 'labels', {value: conversions$3[fromModel].labels}); - - const routes = route$2(fromModel); - const routeModels = Object.keys(routes); - - routeModels.forEach(toModel => { - const fn = routes[toModel]; - - convert$2[fromModel][toModel] = wrapRounded$1(fn); - convert$2[fromModel][toModel].raw = wrapRaw$1(fn); - }); -}); - -var colorConvert$1 = convert$2; - -(function (module) { - -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; - -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); -}; - -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = colorConvert$1; - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); -}(ansiStyles$2)); - -var hasFlag$3 = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; - -const os$5 = require$$0__default$1; -const tty = require$$0__default; -const hasFlag$2 = hasFlag$3; - -const {env: env$2} = process; - -let forceColor$1; -if (hasFlag$2('no-color') || - hasFlag$2('no-colors') || - hasFlag$2('color=false') || - hasFlag$2('color=never')) { - forceColor$1 = 0; -} else if (hasFlag$2('color') || - hasFlag$2('colors') || - hasFlag$2('color=true') || - hasFlag$2('color=always')) { - forceColor$1 = 1; -} - -if ('FORCE_COLOR' in env$2) { - if (env$2.FORCE_COLOR === 'true') { - forceColor$1 = 1; - } else if (env$2.FORCE_COLOR === 'false') { - forceColor$1 = 0; - } else { - forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3); - } -} - -function translateLevel$1(level) { - if (level === 0) { - return false; - } - - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} - -function supportsColor$1(haveStream, streamIsTTY) { - if (forceColor$1 === 0) { - return 0; - } - - if (hasFlag$2('color=16m') || - hasFlag$2('color=full') || - hasFlag$2('color=truecolor')) { - return 3; - } - - if (hasFlag$2('color=256')) { - return 2; - } - - if (haveStream && !streamIsTTY && forceColor$1 === undefined) { - return 0; - } - - const min = forceColor$1 || 0; - - if (env$2.TERM === 'dumb') { - return min; - } - - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os$5.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env$2) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env$2) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; - } - - if (env$2.COLORTERM === 'truecolor') { - return 3; - } - - if ('TERM_PROGRAM' in env$2) { - const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env$2.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env$2.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { - return 1; - } - - if ('COLORTERM' in env$2) { - return 1; - } - - return min; -} - -function getSupportLevel$1(stream) { - const level = supportsColor$1(stream, stream && stream.isTTY); - return translateLevel$1(level); -} - -var supportsColor_1$1 = { - supportsColor: getSupportLevel$1, - stdout: translateLevel$1(supportsColor$1(true, tty.isatty(1))), - stderr: translateLevel$1(supportsColor$1(true, tty.isatty(2))) -}; - -const stringReplaceAll$1 = (string, substring, replacer) => { - let index = string.indexOf(substring); - if (index === -1) { - return string; - } - - const substringLength = substring.length; - let endIndex = 0; - let returnValue = ''; - do { - returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; - endIndex = index + substringLength; - index = string.indexOf(substring, endIndex); - } while (index !== -1); - - returnValue += string.substr(endIndex); - return returnValue; -}; - -const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => { - let endIndex = 0; - let returnValue = ''; - do { - const gotCR = string[index - 1] === '\r'; - returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; - endIndex = index + 1; - index = string.indexOf('\n', endIndex); - } while (index !== -1); - - returnValue += string.substr(endIndex); - return returnValue; -}; - -var util$9 = { - stringReplaceAll: stringReplaceAll$1, - stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 -}; - -const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; - -const ESCAPES$1 = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); - -function unescape$2(c) { - const u = c[0] === 'u'; - const bracket = c[1] === '{'; - - if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } - - if (u && bracket) { - return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); - } - - return ESCAPES$1.get(c) || c; -} - -function parseArguments$1(name, arguments_) { - const results = []; - const chunks = arguments_.trim().split(/\s*,\s*/g); - let matches; - - for (const chunk of chunks) { - const number = Number(chunk); - if (!Number.isNaN(number)) { - results.push(number); - } else if ((matches = chunk.match(STRING_REGEX$1))) { - results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$2(escape) : character)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } - - return results; -} - -function parseStyle$1(style) { - STYLE_REGEX$1.lastIndex = 0; - - const results = []; - let matches; - - while ((matches = STYLE_REGEX$1.exec(style)) !== null) { - const name = matches[1]; - - if (matches[2]) { - const args = parseArguments$1(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } - - return results; -} - -function buildStyle$1(chalk, styles) { - const enabled = {}; - - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } - - let current = chalk; - for (const [styleName, styles] of Object.entries(enabled)) { - if (!Array.isArray(styles)) { - continue; - } - - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } - - current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; - } - - return current; -} - -var templates$1 = (chalk, temporary) => { - const styles = []; - const chunks = []; - let chunk = []; - - // eslint-disable-next-line max-params - temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => { - if (escapeCharacter) { - chunk.push(unescape$2(escapeCharacter)); - } else if (style) { - const string = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string)); - styles.push({inverse, styles: parseStyle$1(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } - - chunks.push(buildStyle$1(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(character); - } - }); - - chunks.push(chunk.join('')); - - if (styles.length > 0) { - const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMessage); - } - - return chunks.join(''); -}; - -const ansiStyles$1 = ansiStyles$2.exports; -const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1$1; -const { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -} = util$9; - -const {isArray: isArray$4} = Array; - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = [ - 'ansi', - 'ansi', - 'ansi256', - 'ansi16m' -]; - -const styles = Object.create(null); - -const applyOptions = (object, options = {}) => { - if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { - throw new Error('The `level` option should be an integer from 0 to 3'); - } - - // Detect level if not set manually - const colorLevel = stdoutColor ? stdoutColor.level : 0; - object.level = options.level === undefined ? colorLevel : options.level; -}; - -class ChalkClass { - constructor(options) { - // eslint-disable-next-line no-constructor-return - return chalkFactory(options); - } -} - -const chalkFactory = options => { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = () => { - throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); - }; - - chalk.template.Instance = ChalkClass; - - return chalk.template; -}; - -function Chalk(options) { - return chalkFactory(options); -} - -for (const [styleName, style] of Object.entries(ansiStyles$1)) { - styles[styleName] = { - get() { - const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); - Object.defineProperty(this, styleName, {value: builder}); - return builder; - } - }; -} - -styles.visible = { - get() { - const builder = createBuilder(this, this._styler, true); - Object.defineProperty(this, 'visible', {value: builder}); - return builder; - } -}; - -const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; - -for (const model of usedModels) { - styles[model] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} - -for (const model of usedModels) { - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} - -const proto$1 = Object.defineProperties(() => {}, { - ...styles, - level: { - enumerable: true, - get() { - return this._generator.level; - }, - set(level) { - this._generator.level = level; - } - } -}); - -const createStyler = (open, close, parent) => { - let openAll; - let closeAll; - if (parent === undefined) { - openAll = open; - closeAll = close; - } else { - openAll = parent.openAll + open; - closeAll = close + parent.closeAll; - } - - return { - open, - close, - openAll, - closeAll, - parent - }; -}; - -const createBuilder = (self, _styler, _isEmpty) => { - const builder = (...arguments_) => { - if (isArray$4(arguments_[0]) && isArray$4(arguments_[0].raw)) { - // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` - return applyStyle(builder, chalkTag(builder, ...arguments_)); - } - - // Single argument is hot path, implicit coercion is faster than anything - // eslint-disable-next-line no-implicit-coercion - return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); - }; - - // We alter the prototype because we must return a function, but there is - // no way to create a function with a different prototype - Object.setPrototypeOf(builder, proto$1); - - builder._generator = self; - builder._styler = _styler; - builder._isEmpty = _isEmpty; - - return builder; -}; - -const applyStyle = (self, string) => { - if (self.level <= 0 || !string) { - return self._isEmpty ? '' : string; - } - - let styler = self._styler; - - if (styler === undefined) { - return string; - } - - const {openAll, closeAll} = styler; - if (string.indexOf('\u001B') !== -1) { - while (styler !== undefined) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - string = stringReplaceAll(string, styler.close, styler.open); - - styler = styler.parent; - } - } - - // We can move both next actions out of loop, because remaining actions in loop won't have - // any/visible effect on parts we add here. Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 - const lfIndex = string.indexOf('\n'); - if (lfIndex !== -1) { - string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); - } - - return openAll + string + closeAll; -}; - -let template; -const chalkTag = (chalk, ...strings) => { - const [firstString] = strings; - - if (!isArray$4(firstString) || !isArray$4(firstString.raw)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return strings.join(' '); - } - - const arguments_ = strings.slice(1); - const parts = [firstString.raw[0]]; - - for (let i = 1; i < firstString.length; i++) { - parts.push( - String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), - String(firstString.raw[i]) - ); - } - - if (template === undefined) { - template = templates$1; - } - - return template(chalk, parts.join('')); -}; - -Object.defineProperties(Chalk.prototype, styles); - -const chalk$2 = Chalk(); // eslint-disable-line new-cap -chalk$2.supportsColor = stdoutColor; -chalk$2.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap -chalk$2.stderr.supportsColor = stderrColor; - -var source = chalk$2; - -var src$2 = {exports: {}}; - -var browser$1 = {exports: {}}; - -/** - * Helpers. - */ - -var s$1 = 1000; -var m$1 = s$1 * 60; -var h$1 = m$1 * 60; -var d$1 = h$1 * 24; -var w = d$1 * 7; -var y$1 = d$1 * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -var ms$1 = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse$m(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong$1(val) : fmtShort$1(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse$m(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y$1; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d$1; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h$1; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m$1; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s$1; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort$1(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d$1) { - return Math.round(ms / d$1) + 'd'; - } - if (msAbs >= h$1) { - return Math.round(ms / h$1) + 'h'; - } - if (msAbs >= m$1) { - return Math.round(ms / m$1) + 'm'; - } - if (msAbs >= s$1) { - return Math.round(ms / s$1) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong$1(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d$1) { - return plural$1(ms, msAbs, d$1, 'day'); - } - if (msAbs >= h$1) { - return plural$1(ms, msAbs, h$1, 'hour'); - } - if (msAbs >= m$1) { - return plural$1(ms, msAbs, m$1, 'minute'); - } - if (msAbs >= s$1) { - return plural$1(ms, msAbs, s$1, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural$1(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = ms$1; - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -var common$e = setup; - -/* eslint-env browser */ - -(function (module, exports) { -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = common$e(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; -}(browser$1, browser$1.exports)); - -var node$1 = {exports: {}}; - -/** - * Module dependencies. - */ - -(function (module, exports) { -const tty = require$$0__default; -const util = require$$0__default$2; - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = require('supports-color'); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = common$e(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; -}(node$1, node$1.exports)); - -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - src$2.exports = browser$1.exports; -} else { - src$2.exports = node$1.exports; -} - -var debug$f = src$2.exports; - -const DEFAULT_MAIN_FIELDS = [ - 'module', - 'jsnext:main', - 'jsnext' -]; -const DEFAULT_EXTENSIONS = [ - '.mjs', - '.js', - '.ts', - '.jsx', - '.tsx', - '.json' -]; -const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/; -const OPTIMIZABLE_ENTRY_RE = /\.(?:m?js|ts)$/; -const SPECIAL_QUERY_RE = /[\?&](?:worker|sharedworker|raw|url)\b/; -/** - * Prefix for resolved fs paths, since windows paths may not be valid as URLs. - */ -const FS_PREFIX = `/@fs/`; -/** - * Prefix for resolved Ids that are not valid browser import specifiers - */ -const VALID_ID_PREFIX = `/@id/`; -/** - * Some Rollup plugins use ids that starts with the null byte \0 to avoid - * collisions, but it is not permitted in import URLs so we have to replace - * them. - */ -const NULL_BYTE_PLACEHOLDER = `__x00__`; -const CLIENT_PUBLIC_PATH = `/@vite/client`; -const ENV_PUBLIC_PATH = `/@vite/env`; -// eslint-disable-next-line node/no-missing-require -const CLIENT_ENTRY = require.resolve('../../client/client.mjs'); -// eslint-disable-next-line node/no-missing-require -const ENV_ENTRY = require.resolve('../../client/env.mjs'); -const CLIENT_DIR = path__default.dirname(CLIENT_ENTRY); -// ** READ THIS ** before editing `KNOWN_ASSET_TYPES`. -// If you add an asset to `KNOWN_ASSET_TYPES`, make sure to also add it -// to the TypeScript declaration file `packages/vite/client.d.ts`. -const KNOWN_ASSET_TYPES = [ - // images - 'png', - 'jpe?g', - 'gif', - 'svg', - 'ico', - 'webp', - 'avif', - // media - 'mp4', - 'webm', - 'ogg', - 'mp3', - 'wav', - 'flac', - 'aac', - // fonts - 'woff2?', - 'eot', - 'ttf', - 'otf', - // other - 'wasm', - 'webmanifest', - 'pdf' -]; -const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`); -const DEP_VERSION_RE = /[\?&](v=[\w\.-]+)\b/; - -const {builtinModules} = require$$0__default$3; - -const ignoreList = [ - 'sys' -]; - -// eslint-disable-next-line node/no-deprecated-api -var builtinModules_1 = (builtinModules || Object.keys(process.binding('natives'))) - .filter(x => !/^_|^(internal|v8|node-inspect)\/|\//.test(x) && !ignoreList.includes(x)) - .sort(); - -var charToInteger$1 = {}; -var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -for (var i$2 = 0; i$2 < chars$2.length; i$2++) { - charToInteger$1[chars$2.charCodeAt(i$2)] = i$2; -} -function decode(mappings) { - var decoded = []; - var line = []; - var segment = [ - 0, - 0, - 0, - 0, - 0, - ]; - var j = 0; - for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) { - var c = mappings.charCodeAt(i); - if (c === 44) { // "," - segmentify(line, segment, j); - j = 0; - } - else if (c === 59) { // ";" - segmentify(line, segment, j); - j = 0; - decoded.push(line); - line = []; - segment[0] = 0; - } - else { - var integer = charToInteger$1[c]; - if (integer === undefined) { - throw new Error('Invalid character (' + String.fromCharCode(c) + ')'); - } - var hasContinuationBit = integer & 32; - integer &= 31; - value += integer << shift; - if (hasContinuationBit) { - shift += 5; - } - else { - var shouldNegate = value & 1; - value >>>= 1; - if (shouldNegate) { - value = value === 0 ? -0x80000000 : -value; - } - segment[j] += value; - j++; - value = shift = 0; // reset - } - } - } - segmentify(line, segment, j); - decoded.push(line); - return decoded; -} -function segmentify(line, segment, j) { - // This looks ugly, but we're creating specialized arrays with a specific - // length. This is much faster than creating a new array (which v8 expands to - // a capacity of 17 after pushing the first item), or slicing out a subarray - // (which is slow). Length 4 is assumed to be the most frequent, followed by - // length 5 (since not everything will have an associated name), followed by - // length 1 (it's probably rare for a source substring to not have an - // associated segment data). - if (j === 4) - line.push([segment[0], segment[1], segment[2], segment[3]]); - else if (j === 5) - line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]); - else if (j === 1) - line.push([segment[0]]); -} -function encode$1(decoded) { - var sourceFileIndex = 0; // second field - var sourceCodeLine = 0; // third field - var sourceCodeColumn = 0; // fourth field - var nameIndex = 0; // fifth field - var mappings = ''; - for (var i = 0; i < decoded.length; i++) { - var line = decoded[i]; - if (i > 0) - mappings += ';'; - if (line.length === 0) - continue; - var generatedCodeColumn = 0; // first field - var lineMappings = []; - for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { - var segment = line_1[_i]; - var segmentMappings = encodeInteger$1(segment[0] - generatedCodeColumn); - generatedCodeColumn = segment[0]; - if (segment.length > 1) { - segmentMappings += - encodeInteger$1(segment[1] - sourceFileIndex) + - encodeInteger$1(segment[2] - sourceCodeLine) + - encodeInteger$1(segment[3] - sourceCodeColumn); - sourceFileIndex = segment[1]; - sourceCodeLine = segment[2]; - sourceCodeColumn = segment[3]; - } - if (segment.length === 5) { - segmentMappings += encodeInteger$1(segment[4] - nameIndex); - nameIndex = segment[4]; - } - lineMappings.push(segmentMappings); - } - mappings += lineMappings.join(','); - } - return mappings; -} -function encodeInteger$1(num) { - var result = ''; - num = num < 0 ? (-num << 1) | 1 : num << 1; - do { - var clamped = num & 31; - num >>>= 5; - if (num > 0) { - clamped |= 32; - } - result += chars$2[clamped]; - } while (num > 0); - return result; -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Creates a brand new (prototype-less) object with the enumerable-own - * properties of `target`. Any enumerable-own properties from `source` which - * are not present on `target` will be copied as well. - */ -function defaults(target, source) { - return Object.assign(Object.create(null), source, target); -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Decodes an input sourcemap into a `DecodedSourceMap` sourcemap object. - * - * Valid input maps include a `DecodedSourceMap`, a `RawSourceMap`, or JSON - * representations of either type. - */ -function decodeSourceMap(map) { - if (typeof map === 'string') { - map = JSON.parse(map); - } - let { mappings } = map; - if (typeof mappings === 'string') { - mappings = sortMappings(decode(mappings), true); - } - else { - // Clone the Line so that we can sort it. We don't want to mutate an array - // that we don't own directly. - mappings = sortMappings(mappings, false); - } - return defaults({ mappings }, map); -} -function firstUnsortedSegmentLine(mappings) { - for (let i = 0; i < mappings.length; i++) { - const segments = mappings[i]; - for (let j = 1; j < segments.length; j++) { - if (segments[j][0] < segments[j - 1][0]) { - return i; - } - } - } - return mappings.length; -} -function sortMappings(mappings, owned) { - const unosrtedIndex = firstUnsortedSegmentLine(mappings); - if (unosrtedIndex === mappings.length) - return mappings; - if (!owned) - mappings = mappings.slice(); - for (let i = unosrtedIndex; i < mappings.length; i++) { - mappings[i] = sortSegments(mappings[i], owned); - } - return mappings; -} -function sortSegments(segments, owned) { - if (!owned) - segments = segments.slice(); - return segments.sort(segmentComparator); -} -function segmentComparator(a, b) { - return a[0] - b[0]; -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A "leaf" node in the sourcemap tree, representing an original, unmodified - * source file. Recursive segment tracing ends at the `OriginalSource`. - */ -class OriginalSource { - constructor(filename, content) { - this.filename = filename; - this.content = content; - } - /** - * Tracing a `SourceMapSegment` ends when we get to an `OriginalSource`, - * meaning this line/column location originated from this source file. - */ - traceSegment(line, column, name) { - return { column, line, name, source: this }; - } -} - -/* istanbul ignore next */ -const Url$1 = (typeof URL !== 'undefined' ? URL : require('url').URL); -// Matches "..", which must be preceeded by "/" or the start of the string, and -// must be followed by a "/". We do not eat the following "/", so that the next -// iteration can match on it. -const parentRegex = /(^|\/)\.\.(?=\/|$)/g; -function isAbsoluteUrl(url) { - try { - return !!new Url$1(url); - } - catch (e) { - return false; - } -} -/** - * Creates a directory name that is guaranteed to not be in `str`. - */ -function uniqInStr(str) { - let uniq = String(Math.random()).slice(2); - while (str.indexOf(uniq) > -1) { - /* istanbul ignore next */ - uniq += uniq; - } - return uniq; -} -/** - * Removes the filename from the path (everything trailing the last "/"). This - * is only safe to call on a path, never call with an absolute or protocol - * relative URL. - */ -function stripPathFilename(path) { - path = normalizePath$5(path); - const index = path.lastIndexOf('/'); - return path.slice(0, index + 1); -} -/** - * Normalizes a protocol-relative URL, but keeps it protocol relative by - * stripping out the protocl before returning it. - */ -function normalizeProtocolRelative(input, absoluteBase) { - const { href, protocol } = new Url$1(input, absoluteBase); - return href.slice(protocol.length); -} -/** - * Normalizes a simple path (one that has no ".."s, or is absolute so ".."s can - * be normalized absolutely). - */ -function normalizeSimplePath(input) { - const { href } = new Url$1(input, 'https://foo.com/'); - return href.slice('https://foo.com/'.length); -} -/** - * Normalizes a path, ensuring that excess ".."s are preserved for relative - * paths in the output. - * - * If the input is absolute, this will return an absolutey normalized path, but - * it will not have a leading "/". - * - * If the input has a leading "..", the output will have a leading "..". - * - * If the input has a leading ".", the output will not have a leading "." - * unless there are too many ".."s, in which case there will be a leading "..". - */ -function normalizePath$5(input) { - // If there are no ".."s, we can treat this as if it were an absolute path. - // The return won't be an absolute path, so it's easy. - if (!parentRegex.test(input)) - return normalizeSimplePath(input); - // We already found one "..". Let's see how many there are. - let total = 1; - while (parentRegex.test(input)) - total++; - // If there are ".."s, we need to prefix the the path with the same number of - // unique directories. This is to ensure that we "remember" how many parent - // directories we are accessing. Eg, "../../.." must keep 3, and "foo/../.." - // must keep 1. - const uniqDirectory = `z${uniqInStr(input)}/`; - // uniqDirectory is just a "z", followed by numbers, followed by a "/". So - // generating a runtime regex from it is safe. We'll use this search regex to - // strip out our uniq directory names and insert any needed ".."s. - const search = new RegExp(`^(?:${uniqDirectory})*`); - // Now we can resolve the total path. If there are excess ".."s, they will - // eliminate one or more of the unique directories we prefix with. - const relative = normalizeSimplePath(uniqDirectory.repeat(total) + input); - // We can now count the number of unique directories that were eliminated. If - // there were 3, and 1 was eliminated, we know we only need to add 1 "..". If - // 2 were eliminated, we need to insert 2 ".."s. If all 3 were eliminated, - // then we need 3, etc. This replace is guranteed to match (it may match 0 or - // more times), and we can count the total match to see how many were eliminated. - return relative.replace(search, (all) => { - const leftover = all.length / uniqDirectory.length; - return '../'.repeat(total - leftover); - }); -} -/** - * Attempts to resolve `input` URL relative to `base`. - */ -function resolve$3(input, base) { - if (!base) - base = ''; - // Absolute URLs are very easy to resolve right. - if (isAbsoluteUrl(input)) - return new Url$1(input).href; - if (base) { - // Absolute URLs are easy... - if (isAbsoluteUrl(base)) - return new Url$1(input, base).href; - // If base is protocol relative, we'll resolve with it but keep the result - // protocol relative. - if (base.startsWith('//')) - return normalizeProtocolRelative(input, `https:${base}`); - } - // Normalize input, but keep it protocol relative. We know base doesn't supply - // a protocol, because that would have been handled above. - if (input.startsWith('//')) - return normalizeProtocolRelative(input, 'https://foo.com/'); - // We now know that base (if there is one) and input are paths. We've handled - // both absolute and protocol-relative variations above. - // Absolute paths don't need any special handling, because they cannot have - // extra "." or ".."s. That'll all be stripped away. Input takes priority here, - // because if input is an absolute path, base path won't affect it in any way. - if (input.startsWith('/')) - return '/' + normalizeSimplePath(input); - // Since input and base are paths, we need to join them to do any further - // processing. Paths are joined at the directory level, so we need to remove - // the base's filename before joining. We also know that input does not have a - // leading slash, and that the stripped base will have a trailing slash if - // there are any directories (or it'll be empty). - const joined = stripPathFilename(base) + input; - // If base is an absolute path, then input will be relative to it. - if (base.startsWith('/')) - return '/' + normalizeSimplePath(joined); - // We now know both base (if there is one) and input are relative paths. - const relative = normalizePath$5(joined); - // If base started with a leading ".", or there is no base and input started - // with a ".", then we need to ensure that the relative path starts with a - // ".". We don't know if relative starts with a "..", though, so check before - // prepending. - if ((base || input).startsWith('.') && !relative.startsWith('.')) { - return './' + relative; - } - return relative; -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function resolve$1$1(input, base) { - // The base is always treated as a directory, if it's not empty. - // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 - // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 - if (base && !base.endsWith('/')) - base += '/'; - return resolve$3(input, base); -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A binary search implementation that returns the index if a match is found, - * or the negated index of where the `needle` should be inserted. - * - * The `comparator` callback receives both the `item` under comparison and the - * needle we are searching for. It must return `0` if the `item` is a match, - * any negative number if `item` is too small (and we must search after it), or - * any positive number if the `item` is too large (and we must search before - * it). - * - * If no match is found, a negated index of where to insert the `needle` is - * returned. This negated index is guaranteed to be less than 0. To insert an - * item, negate it (again) and splice: - * - * ```js - * const array = [1, 3]; - * const needle = 2; - * const index = binarySearch(array, needle, (item, needle) => item - needle); - * - * assert.equal(index, -2); - * assert.equal(~index, 1); - * array.splice(~index, 0, needle); - * assert.deepEqual(array, [1, 2, 3]); - * ``` - */ -function binarySearch$2(haystack, needle, comparator, low, high) { - low = Math.max(low, 0); - while (low <= high) { - const mid = low + ((high - low) >> 1); - const cmp = comparator(haystack[mid], needle); - if (cmp === 0) { - return mid; - } - if (cmp < 0) { - low = mid + 1; - } - else { - high = mid - 1; - } - } - return ~low; -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * FastStringArray acts like a `Set` (allowing only one occurrence of a string - * `key`), but provides the index of the `key` in the backing array. - * - * This is designed to allow synchronizing a second array with the contents of - * the backing array, like how `sourcesContent[i]` is the source content - * associated with `source[i]`, and there are never duplicates. - */ -class FastStringArray { - constructor() { - this.indexes = Object.create(null); - this.array = []; - } - /** - * Puts `key` into the backing array, if it is not already present. Returns - * the index of the `key` in the backing array. - */ - put(key) { - const { array, indexes } = this; - // The key may or may not be present. If it is present, it's a number. - let index = indexes[key]; - // If it's not yet present, we need to insert it and track the index in the - // indexes. - if (index === undefined) { - index = indexes[key] = array.length; - array.push(key); - } - return index; - } -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * SourceMapTree represents a single sourcemap, with the ability to trace - * mappings into its child nodes (which may themselves be SourceMapTrees). - */ -class SourceMapTree { - constructor(map, sources) { - this.map = map; - this.sources = sources; - this.lastLine = 0; - this.lastColumn = 0; - this.lastIndex = 0; - } - /** - * traceMappings is only called on the root level SourceMapTree, and begins - * the process of resolving each mapping in terms of the original source - * files. - */ - traceMappings() { - const mappings = []; - const names = new FastStringArray(); - const sources = new FastStringArray(); - const sourcesContent = []; - const { mappings: rootMappings, names: rootNames } = this.map; - for (let i = 0; i < rootMappings.length; i++) { - const segments = rootMappings[i]; - const tracedSegments = []; - let lastTraced = undefined; - for (let j = 0; j < segments.length; j++) { - const segment = segments[j]; - // 1-length segments only move the current generated column, there's no - // source information to gather from it. - if (segment.length === 1) - continue; - const source = this.sources[segment[1]]; - const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); - if (!traced) - continue; - // So we traced a segment down into its original source file. Now push a - // new segment pointing to this location. - const { column, line, name } = traced; - const { content, filename } = traced.source; - // Store the source location, and ensure we keep sourcesContent up to - // date with the sources array. - const sourceIndex = sources.put(filename); - sourcesContent[sourceIndex] = content; - if (lastTraced && - lastTraced[1] === sourceIndex && - lastTraced[2] === line && - lastTraced[3] === column) { - // This is a duplicate mapping pointing at the exact same starting point in the source file. - // It doesn't provide any new information, and only bloats the sourcemap. - continue; - } - // This looks like unnecessary duplication, but it noticeably increases - // performance. If we were to push the nameIndex onto length-4 array, v8 - // would internally allocate 22 slots! That's 68 wasted bytes! Array - // literals have the same capacity as their length, saving memory. - if (name) { - lastTraced = [segment[0], sourceIndex, line, column, names.put(name)]; - } - else { - lastTraced = [segment[0], sourceIndex, line, column]; - } - tracedSegments.push(lastTraced); - } - mappings.push(tracedSegments); - } - // TODO: Make all sources relative to the sourceRoot. - return defaults({ - mappings, - names: names.array, - sources: sources.array, - sourcesContent, - }, this.map); - } - /** - * traceSegment is only called on children SourceMapTrees. It recurses down - * into its own child SourceMapTrees, until we find the original source map. - */ - traceSegment(line, column, name) { - const { mappings, names } = this.map; - // It's common for parent sourcemaps to have pointers to lines that have no - // mapping (like a "//# sourceMappingURL=") at the end of the child file. - if (line >= mappings.length) - return null; - const segments = mappings[line]; - if (segments.length === 0) - return null; - let low = 0; - let high = segments.length - 1; - if (line === this.lastLine) { - if (column >= this.lastColumn) { - low = this.lastIndex; - } - else { - high = this.lastIndex; - } - } - let index = binarySearch$2(segments, column, segmentComparator$1, low, high); - this.lastLine = line; - this.lastColumn = column; - if (index === -1) { - this.lastIndex = index; - return null; // we come before any mapped segment - } - // If we can't find a segment that lines up to this column, we use the - // segment before. - if (index < 0) { - index = ~index - 1; - } - this.lastIndex = index; - const segment = segments[index]; - // 1-length segments only move the current generated column, there's no - // source information to gather from it. - if (segment.length === 1) - return null; - const source = this.sources[segment[1]]; - // So now we can recurse down, until we hit the original source file. - return source.traceSegment(segment[2], segment[3], - // A child map's recorded name for this segment takes precedence over the - // parent's mapped name. Imagine a mangler changing the name over, etc. - segment.length === 5 ? names[segment[4]] : name); - } -} -function segmentComparator$1(segment, column) { - return segment[0] - column; -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Removes the filename from a path. - */ -function stripFilename(path) { - if (!path) - return ''; - const index = path.lastIndexOf('/'); - return path.slice(0, index + 1); -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function asArray(value) { - if (Array.isArray(value)) - return value; - return [value]; -} -/** - * Recursively builds a tree structure out of sourcemap files, with each node - * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of - * `OriginalSource`s and `SourceMapTree`s. - * - * Every sourcemap is composed of a collection of source files and mappings - * into locations of those source files. When we generate a `SourceMapTree` for - * the sourcemap, we attempt to load each source file's own sourcemap. If it - * does not have an associated sourcemap, it is considered an original, - * unmodified source file. - */ -function buildSourceMapTree(input, loader, relativeRoot) { - const maps = asArray(input).map(decodeSourceMap); - const map = maps.pop(); - for (let i = 0; i < maps.length; i++) { - if (maps[i].sources.length !== 1) { - throw new Error(`Transformation map ${i} must have exactly one source file.\n` + - 'Did you specify these with the most recent transformation maps first?'); - } - } - const { sourceRoot, sources, sourcesContent } = map; - const children = sources.map((sourceFile, i) => { - // Each source file is loaded relative to the sourcemap's own sourceRoot, - // which is itself relative to the sourcemap's parent. - const uri = resolve$1$1(sourceFile || '', resolve$1$1(sourceRoot || '', stripFilename(relativeRoot))); - // Use the provided loader callback to retrieve the file's sourcemap. - // TODO: We should eventually support async loading of sourcemap files. - const sourceMap = loader(uri); - // If there is no sourcemap, then it is an unmodified source file. - if (!sourceMap) { - // The source file's actual contents must be included in the sourcemap - // (done when generating the sourcemap) for it to be included as a - // sourceContent in the output sourcemap. - const sourceContent = sourcesContent ? sourcesContent[i] : null; - return new OriginalSource(uri, sourceContent); - } - // Else, it's a real sourcemap, and we need to recurse into it to load its - // source files. - return buildSourceMapTree(decodeSourceMap(sourceMap), loader, uri); - }); - let tree = new SourceMapTree(map, children); - for (let i = maps.length - 1; i >= 0; i--) { - tree = new SourceMapTree(maps[i], [tree]); - } - return tree; -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A SourceMap v3 compatible sourcemap, which only includes fields that were - * provided to it. - */ -class SourceMap$1 { - constructor(map, options) { - this.version = 3; // SourceMap spec says this should be first. - if ('file' in map) - this.file = map.file; - this.mappings = options.decodedMappings ? map.mappings : encode$1(map.mappings); - this.names = map.names; - // TODO: We first need to make all source URIs relative to the sourceRoot - // before we can support a sourceRoot. - // if ('sourceRoot' in map) this.sourceRoot = map.sourceRoot; - this.sources = map.sources; - if (!options.excludeContent && 'sourcesContent' in map) { - this.sourcesContent = map.sourcesContent; - } - } - toString() { - return JSON.stringify(this); - } -} - -/** - * Copyright 2019 The AMP HTML Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Traces through all the mappings in the root sourcemap, through the sources - * (and their sourcemaps), all the way back to the original source location. - * - * `loader` will be called every time we encounter a source file. If it returns - * a sourcemap, we will recurse into that sourcemap to continue the trace. If - * it returns a falsey value, that source file is treated as an original, - * unmodified source file. - * - * Pass `excludeContent` to exclude any self-containing source file content - * from the output sourcemap. - * - * Pass `decodedMappings` to receive a SourceMap with decoded (instead of - * VLQ encoded) mappings. - */ -function remapping(input, loader, options) { - const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; - const graph = buildSourceMapTree(input, loader); - return new SourceMap$1(graph.traceMappings(), opts); -} - -function slash$3(p) { - return p.replace(/\\/g, '/'); -} -// Strip valid id prefix. This is prepended to resolved Ids that are -// not valid browser import specifiers by the importAnalysis plugin. -function unwrapId$1(id) { - return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id; -} -const flattenId = (id) => id.replace(/(\s*>\s*)/g, '__').replace(/[\/\.]/g, '_'); -const normalizeId$1 = (id) => id.replace(/(\s*>\s*)/g, ' > '); -function isBuiltin(id) { - return builtinModules_1.includes(id); -} -const bareImportRE = /^[\w@](?!.*:\/\/)/; -const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//; -let isRunningWithYarnPnp; -try { - isRunningWithYarnPnp = Boolean(require('pnpapi')); -} -catch { } -const ssrExtensions = ['.js', '.cjs', '.json', '.node']; -function resolveFrom$3(id, basedir, preserveSymlinks = false, ssr = false) { - return resolve__default.sync(id, { - basedir, - extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS, - // necessary to work with pnpm - preserveSymlinks: preserveSymlinks || isRunningWithYarnPnp || false - }); -} -/** - * like `resolveFrom` but supports resolving `>` path in `id`, - * for example: `foo > bar > baz` - */ -function nestedResolveFrom(id, basedir, preserveSymlinks = false) { - const pkgs = id.split('>').map((pkg) => pkg.trim()); - try { - for (const pkg of pkgs) { - basedir = resolveFrom$3(pkg, basedir, preserveSymlinks); - } - } - catch { } - return basedir; -} -// set in bin/vite.js -const filter$1 = process.env.VITE_DEBUG_FILTER; -const DEBUG$1 = process.env.DEBUG; -function createDebugger(namespace, options = {}) { - const log = debug$f(namespace); - const { onlyWhenFocused } = options; - const focus = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; - return (msg, ...args) => { - if (filter$1 && !msg.includes(filter$1)) { - return; - } - if (onlyWhenFocused && !(DEBUG$1 === null || DEBUG$1 === void 0 ? void 0 : DEBUG$1.includes(focus))) { - return; - } - log(msg, ...args); - }; -} -const isWindows$4 = require$$0__default$1.platform() === 'win32'; -const VOLUME_RE = /^[A-Z]:/i; -function normalizePath$4(id) { - return path__default.posix.normalize(isWindows$4 ? slash$3(id) : id); -} -function fsPathFromId(id) { - const fsPath = normalizePath$4(id.slice(FS_PREFIX.length)); - return fsPath.startsWith('/') || fsPath.match(VOLUME_RE) - ? fsPath - : `/${fsPath}`; -} -function ensureVolumeInPath(file) { - return isWindows$4 ? path__default.resolve(file) : file; -} -const queryRE = /\?.*$/s; -const hashRE = /#.*$/s; -const cleanUrl = (url) => url.replace(hashRE, '').replace(queryRE, ''); -const externalRE = /^(https?:)?\/\//; -const isExternalUrl = (url) => externalRE.test(url); -const dataUrlRE = /^\s*data:/i; -const isDataUrl = (url) => dataUrlRE.test(url); -const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte|astro)($|\?)/; -const isJSRequest = (url) => { - url = cleanUrl(url); - if (knownJsSrcRE.test(url)) { - return true; - } - if (!path__default.extname(url) && !url.endsWith('/')) { - return true; - } - return false; -}; -const importQueryRE = /(\?|&)import=?(?:&|$)/; -const internalPrefixes = [ - FS_PREFIX, - VALID_ID_PREFIX, - CLIENT_PUBLIC_PATH, - ENV_PUBLIC_PATH -]; -const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`); -const trailingSeparatorRE = /[\?&]$/; -const isImportRequest = (url) => importQueryRE.test(url); -const isInternalRequest = (url) => InternalPrefixRE.test(url); -function removeImportQuery(url) { - return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, ''); -} -function injectQuery(url, queryToInject) { - // encode percents for consistent behavior with pathToFileURL - // see #2614 for details - let resolvedUrl = new require$$0$8.URL(url.replace(/%/g, '%25'), 'relative:///'); - if (resolvedUrl.protocol !== 'relative:') { - resolvedUrl = require$$0$8.pathToFileURL(url); - } - let { protocol, pathname, search, hash } = resolvedUrl; - if (protocol === 'file:') { - pathname = pathname.slice(1); - } - pathname = decodeURIComponent(pathname); - return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`; -} -const timestampRE = /\bt=\d{13}&?\b/; -function removeTimestampQuery(url) { - return url.replace(timestampRE, '').replace(trailingSeparatorRE, ''); -} -async function asyncReplace(input, re, replacer) { - let match; - let remaining = input; - let rewritten = ''; - while ((match = re.exec(remaining))) { - rewritten += remaining.slice(0, match.index); - rewritten += await replacer(match); - remaining = remaining.slice(match.index + match[0].length); - } - rewritten += remaining; - return rewritten; -} -function timeFrom(start, subtract = 0) { - const time = perf_hooks.performance.now() - start - subtract; - const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' '); - if (time < 10) { - return source.green(timeString); - } - else if (time < 50) { - return source.yellow(timeString); - } - else { - return source.red(timeString); - } -} -/** - * pretty url for logging. - */ -function prettifyUrl(url, root) { - url = removeTimestampQuery(url); - const isAbsoluteFile = url.startsWith(root); - if (isAbsoluteFile || url.startsWith(FS_PREFIX)) { - let file = path__default.relative(root, isAbsoluteFile ? url : fsPathFromId(url)); - const seg = file.split('/'); - const npmIndex = seg.indexOf(`node_modules`); - const isSourceMap = file.endsWith('.map'); - if (npmIndex > 0) { - file = seg[npmIndex + 1]; - if (file.startsWith('@')) { - file = `${file}/${seg[npmIndex + 2]}`; - } - file = `npm: ${source.dim(file)}${isSourceMap ? ` (source map)` : ``}`; - } - return source.dim(file); - } - else { - return source.dim(url); - } -} -function isObject$3(value) { - return Object.prototype.toString.call(value) === '[object Object]'; -} -function isDefined(value) { - return value != null; -} -function lookupFile(dir, formats, pathOnly = false) { - for (const format of formats) { - const fullPath = path__default.join(dir, format); - if (fs__default.existsSync(fullPath) && fs__default.statSync(fullPath).isFile()) { - return pathOnly ? fullPath : fs__default.readFileSync(fullPath, 'utf-8'); - } - } - const parentDir = path__default.dirname(dir); - if (parentDir !== dir) { - return lookupFile(parentDir, formats, pathOnly); - } -} -const splitRE = /\r?\n/; -const range$1 = 2; -function pad$1(source, n = 2) { - const lines = source.split(splitRE); - return lines.map((l) => ` `.repeat(n) + l).join(`\n`); -} -function posToNumber(source, pos) { - if (typeof pos === 'number') - return pos; - const lines = source.split(splitRE); - const { line, column } = pos; - let start = 0; - for (let i = 0; i < line - 1; i++) { - start += lines[i].length + 1; - } - return start + column; -} -function numberToPos(source, offset) { - if (typeof offset !== 'number') - return offset; - if (offset > source.length) { - throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`); - } - const lines = source.split(splitRE); - let counted = 0; - let line = 0; - let column = 0; - for (; line < lines.length; line++) { - const lineLength = lines[line].length + 1; - if (counted + lineLength >= offset) { - column = offset - counted + 1; - break; - } - counted += lineLength; - } - return { line: line + 1, column }; -} -function generateCodeFrame(source, start = 0, end) { - start = posToNumber(source, start); - end = end || start; - const lines = source.split(splitRE); - let count = 0; - const res = []; - for (let i = 0; i < lines.length; i++) { - count += lines[i].length + 1; - if (count >= start) { - for (let j = i - range$1; j <= i + range$1 || end > count; j++) { - if (j < 0 || j >= lines.length) - continue; - const line = j + 1; - res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); - const lineLength = lines[j].length; - if (j === i) { - // push underline - const pad = start - (count - lineLength) + 1; - const length = Math.max(1, end > count ? lineLength - pad : end - start); - res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)); - } - else if (j > i) { - if (end > count) { - const length = Math.max(Math.min(end - count, lineLength), 1); - res.push(` | ` + '^'.repeat(length)); - } - count += lineLength + 1; - } - } - break; - } - } - return res.join('\n'); -} -function writeFile(filename, content) { - const dir = path__default.dirname(filename); - if (!fs__default.existsSync(dir)) { - fs__default.mkdirSync(dir, { recursive: true }); - } - fs__default.writeFileSync(filename, content); -} -/** - * Delete every file and subdirectory. **The given directory must exist.** - * Pass an optional `skip` array to preserve files in the root directory. - */ -function emptyDir(dir, skip) { - for (const file of fs__default.readdirSync(dir)) { - if (skip === null || skip === void 0 ? void 0 : skip.includes(file)) { - continue; - } - const abs = path__default.resolve(dir, file); - // baseline is Node 12 so can't use rmSync :( - if (fs__default.lstatSync(abs).isDirectory()) { - emptyDir(abs); - fs__default.rmdirSync(abs); - } - else { - fs__default.unlinkSync(abs); - } - } -} -function copyDir(srcDir, destDir) { - fs__default.mkdirSync(destDir, { recursive: true }); - for (const file of fs__default.readdirSync(srcDir)) { - const srcFile = path__default.resolve(srcDir, file); - if (srcFile === destDir) { - continue; - } - const destFile = path__default.resolve(destDir, file); - const stat = fs__default.statSync(srcFile); - if (stat.isDirectory()) { - copyDir(srcFile, destFile); - } - else { - fs__default.copyFileSync(srcFile, destFile); - } - } -} -function ensureLeadingSlash(path) { - return !path.startsWith('/') ? '/' + path : path; -} -function ensureWatchedFile(watcher, file, root) { - if (file && - // only need to watch if out of root - !file.startsWith(root + '/') && - // some rollup plugins use null bytes for private resolved Ids - !file.includes('\0') && - fs__default.existsSync(file)) { - // resolve file to normalized system path - watcher.add(path__default.resolve(file)); - } -} -const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; -async function processSrcSet(srcs, replacer) { - const imageCandidates = srcs - .split(',') - .map((s) => { - const [url, descriptor] = s - .replace(escapedSpaceCharacters, ' ') - .trim() - .split(' ', 2); - return { url, descriptor }; - }) - .filter(({ url }) => !!url); - const ret = await Promise.all(imageCandidates.map(async ({ url, descriptor }) => { - return { - url: await replacer({ url, descriptor }), - descriptor - }; - })); - const url = ret.reduce((prev, { url, descriptor }, index) => { - descriptor = descriptor || ''; - return (prev += - url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`); - }, ''); - return url; -} -// based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221 -const nullSourceMap = { - names: [], - sources: [], - mappings: '', - version: 3 -}; -function combineSourcemaps(filename, sourcemapList) { - if (sourcemapList.length === 0 || - sourcemapList.every((m) => m.sources.length === 0)) { - return { ...nullSourceMap }; - } - // We don't declare type here so we can convert/fake/map as RawSourceMap - let map; //: SourceMap - let mapIndex = 1; - const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined; - if (useArrayInterface) { - map = remapping(sourcemapList, () => null, true); - } - else { - map = remapping(sourcemapList[0], function loader(sourcefile) { - if (sourcefile === filename && sourcemapList[mapIndex]) { - return sourcemapList[mapIndex++]; - } - else { - return { ...nullSourceMap }; - } - }, true); - } - if (!map.file) { - delete map.file; - } - return map; -} -function unique(arr) { - return Array.from(new Set(arr)); -} -function resolveHostname(optionsHost) { - let host; - if (optionsHost === undefined || - optionsHost === false || - optionsHost === 'localhost') { - // Use a secure default - host = '127.0.0.1'; - } - else if (optionsHost === true) { - // If passed --host in the CLI without arguments - host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs) - } - else { - host = optionsHost; - } - // Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1' - const name = (optionsHost !== '127.0.0.1' && host === '127.0.0.1') || - host === '0.0.0.0' || - host === '::' || - host === undefined - ? 'localhost' - : host; - return { host, name }; -} -function arraify(target) { - return Array.isArray(target) ? target : [target]; -} -function toUpperCaseDriveLetter(pathName) { - return pathName.replace(/^\w:/, (letter) => letter.toUpperCase()); -} -const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm; -const singlelineCommentsRE = /\/\/.*/g; -const usingDynamicImport = typeof jest === 'undefined'; -/** - * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup. - * - * As a temporary workaround for Jest's lack of stable ESM support, we fallback to require - * if we're in a Jest environment. - * See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077 - * - * @param file File path to import. - */ -const dynamicImport = usingDynamicImport ? new Function('file', 'return import(file)') : require; - -/* eslint no-console: 0 */ -const LogLevels = { - silent: 0, - error: 1, - warn: 2, - info: 3 -}; -let lastType; -let lastMsg; -let sameCount = 0; -function clearScreen() { - const repeatCount = process.stdout.rows - 2; - const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''; - console.log(blank); - readline__default.cursorTo(process.stdout, 0, 0); - readline__default.clearScreenDown(process.stdout); -} -function createLogger(level = 'info', options = {}) { - if (options.customLogger) { - return options.customLogger; - } - const loggedErrors = new WeakSet(); - const { prefix = '[vite]', allowClearScreen = true } = options; - const thresh = LogLevels[level]; - const clear = allowClearScreen && process.stdout.isTTY && !process.env.CI - ? clearScreen - : () => { }; - function output(type, msg, options = {}) { - if (thresh >= LogLevels[type]) { - const method = type === 'info' ? 'log' : type; - const format = () => { - if (options.timestamp) { - const tag = type === 'info' - ? source.cyan.bold(prefix) - : type === 'warn' - ? source.yellow.bold(prefix) - : source.red.bold(prefix); - return `${source.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`; - } - else { - return msg; - } - }; - if (options.error) { - loggedErrors.add(options.error); - } - if (type === lastType && msg === lastMsg) { - sameCount++; - clear(); - console[method](format(), source.yellow(`(x${sameCount + 1})`)); - } - else { - sameCount = 0; - lastMsg = msg; - lastType = type; - if (options.clear) { - clear(); - } - console[method](format()); - } - } - } - const warnedMessages = new Set(); - const logger = { - hasWarned: false, - info(msg, opts) { - output('info', msg, opts); - }, - warn(msg, opts) { - logger.hasWarned = true; - output('warn', msg, opts); - }, - warnOnce(msg, opts) { - if (warnedMessages.has(msg)) - return; - logger.hasWarned = true; - output('warn', msg, opts); - warnedMessages.add(msg); - }, - error(msg, opts) { - logger.hasWarned = true; - output('error', msg, opts); - }, - clearScreen(type) { - if (thresh >= LogLevels[type]) { - clear(); - } - }, - hasErrorLogged(error) { - return loggedErrors.has(error); - } - }; - return logger; -} -function printHttpServerUrls(server, config) { - const address = server.address(); - const isAddressInfo = (x) => x === null || x === void 0 ? void 0 : x.address; - if (isAddressInfo(address)) { - const hostname = resolveHostname(config.server.host); - const protocol = config.server.https ? 'https' : 'http'; - printServerUrls(hostname, protocol, address.port, config.base, config.logger.info); - } -} -function printServerUrls(hostname, protocol, port, base, info) { - if (hostname.host === '127.0.0.1') { - const url = `${protocol}://${hostname.name}:${source.bold(port)}${base}`; - info(` > Local: ${source.cyan(url)}`); - if (hostname.name !== '127.0.0.1') { - info(` > Network: ${source.dim('use `--host` to expose')}`); - } - } - else { - Object.values(require$$0__default$1.networkInterfaces()) - .flatMap((nInterface) => nInterface !== null && nInterface !== void 0 ? nInterface : []) - .filter((detail) => detail && detail.address && detail.family === 'IPv4') - .map((detail) => { - const type = detail.address.includes('127.0.0.1') - ? 'Local: ' - : 'Network: '; - const host = detail.address.replace('127.0.0.1', hostname.name); - const url = `${protocol}://${host}:${source.bold(port)}${base}`; - return ` > ${type} ${source.cyan(url)}`; - }) - .forEach((msg) => info(msg)); - } -} - -const writeColors = { - [0 /* JS */]: source.cyan, - [1 /* CSS */]: source.magenta, - [2 /* ASSET */]: source.green, - [3 /* HTML */]: source.blue, - [4 /* SOURCE_MAP */]: source.gray -}; -function buildReporterPlugin(config) { - const compress = require$$0$6.promisify(require$$0$9.gzip); - const chunkLimit = config.build.chunkSizeWarningLimit; - function isLarge(code) { - // bail out on particularly large chunks - return code.length / 1024 > chunkLimit; - } - async function getCompressedSize(code) { - if (config.build.ssr || - !config.build.reportCompressedSize || - config.build.brotliSize === false) { - return ''; - } - return ` / gzip: ${((await compress(typeof code === 'string' ? code : Buffer.from(code))) - .length / 1024).toFixed(2)} KiB`; - } - function printFileInfo(filePath, content, type, maxLength, compressedSize = '') { - const outDir = normalizePath$4(path__default.relative(config.root, path__default.resolve(config.root, config.build.outDir))) + '/'; - const kibs = content.length / 1024; - const sizeColor = kibs > chunkLimit ? source.yellow : source.dim; - config.logger.info(`${source.gray(source.white.dim(outDir))}${writeColors[type](filePath.padEnd(maxLength + 2))} ${sizeColor(`${kibs.toFixed(2)} KiB${compressedSize}`)}`); - } - const tty = process.stdout.isTTY && !process.env.CI; - const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info; - let hasTransformed = false; - let hasRenderedChunk = false; - let transformedCount = 0; - let chunkCount = 0; - const logTransform = throttle((id) => { - writeLine(`transforming (${transformedCount}) ${source.dim(path__default.relative(config.root, id))}`); - }); - return { - name: 'vite:reporter', - transform(_, id) { - transformedCount++; - if (shouldLogInfo) { - if (!tty) { - if (!hasTransformed) { - config.logger.info(`transforming...`); - } - } - else { - if (id.includes(`?`)) - return; - logTransform(id); - } - hasTransformed = true; - } - return null; - }, - buildEnd() { - if (shouldLogInfo) { - if (tty) { - process.stdout.clearLine(0); - process.stdout.cursorTo(0); - } - config.logger.info(`${source.green(`✓`)} ${transformedCount} modules transformed.`); - } - }, - renderStart() { - chunkCount = 0; - }, - renderChunk() { - chunkCount++; - if (shouldLogInfo) { - if (!tty) { - if (!hasRenderedChunk) { - config.logger.info('rendering chunks...'); - } - } - else { - writeLine(`rendering chunks (${chunkCount})...`); - } - hasRenderedChunk = true; - } - return null; - }, - generateBundle() { - if (shouldLogInfo && tty) { - process.stdout.clearLine(0); - process.stdout.cursorTo(0); - } - }, - async writeBundle(_, output) { - let hasLargeChunks = false; - if (shouldLogInfo) { - let longest = 0; - for (const file in output) { - const l = output[file].fileName.length; - if (l > longest) - longest = l; - } - // large chunks are deferred to be logged at the end so they are more - // visible. - const deferredLogs = []; - await Promise.all(Object.keys(output).map(async (file) => { - const chunk = output[file]; - if (chunk.type === 'chunk') { - const log = async () => { - printFileInfo(chunk.fileName, chunk.code, 0 /* JS */, longest, await getCompressedSize(chunk.code)); - if (chunk.map) { - printFileInfo(chunk.fileName + '.map', chunk.map.toString(), 4 /* SOURCE_MAP */, longest); - } - }; - if (isLarge(chunk.code)) { - hasLargeChunks = true; - deferredLogs.push(log); - } - else { - await log(); - } - } - else if (chunk.source) { - const isCSS = chunk.fileName.endsWith('.css'); - printFileInfo(chunk.fileName, chunk.source, isCSS ? 1 /* CSS */ : 2 /* ASSET */, longest, isCSS ? await getCompressedSize(chunk.source) : undefined); - } - })); - await Promise.all(deferredLogs.map((l) => l())); - } - else { - hasLargeChunks = Object.keys(output).some((file) => { - const chunk = output[file]; - return chunk.type === 'chunk' && chunk.code.length / 1024 > chunkLimit; - }); - } - if (hasLargeChunks && - config.build.minify && - !config.build.lib && - !config.build.ssr) { - config.logger.warn(source.yellow(`\n(!) Some chunks are larger than ${chunkLimit} KiB after minification. Consider:\n` + - `- Using dynamic import() to code-split the application\n` + - `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks\n` + - `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`)); - } - } - }; -} -function writeLine(output) { - process.stdout.clearLine(0); - process.stdout.cursorTo(0); - if (output.length < process.stdout.columns) { - process.stdout.write(output); - } - else { - process.stdout.write(output.substring(0, process.stdout.columns - 1)); - } -} -function throttle(fn) { - let timerHandle = null; - return (...args) => { - if (timerHandle) - return; - fn(...args); - timerHandle = setTimeout(() => { - timerHandle = null; - }, 100); - }; -} - -var charToInteger = {}; -var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -for (var i$1 = 0; i$1 < chars$1.length; i$1++) { - charToInteger[chars$1.charCodeAt(i$1)] = i$1; -} -function encode(decoded) { - var sourceFileIndex = 0; // second field - var sourceCodeLine = 0; // third field - var sourceCodeColumn = 0; // fourth field - var nameIndex = 0; // fifth field - var mappings = ''; - for (var i = 0; i < decoded.length; i++) { - var line = decoded[i]; - if (i > 0) - mappings += ';'; - if (line.length === 0) - continue; - var generatedCodeColumn = 0; // first field - var lineMappings = []; - for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { - var segment = line_1[_i]; - var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); - generatedCodeColumn = segment[0]; - if (segment.length > 1) { - segmentMappings += - encodeInteger(segment[1] - sourceFileIndex) + - encodeInteger(segment[2] - sourceCodeLine) + - encodeInteger(segment[3] - sourceCodeColumn); - sourceFileIndex = segment[1]; - sourceCodeLine = segment[2]; - sourceCodeColumn = segment[3]; - } - if (segment.length === 5) { - segmentMappings += encodeInteger(segment[4] - nameIndex); - nameIndex = segment[4]; - } - lineMappings.push(segmentMappings); - } - mappings += lineMappings.join(','); - } - return mappings; -} -function encodeInteger(num) { - var result = ''; - num = num < 0 ? (-num << 1) | 1 : num << 1; - do { - var clamped = num & 31; - num >>>= 5; - if (num > 0) { - clamped |= 32; - } - result += chars$1[clamped]; - } while (num > 0); - return result; -} - -var BitSet = function BitSet(arg) { - this.bits = arg instanceof BitSet ? arg.bits.slice() : []; -}; - -BitSet.prototype.add = function add (n) { - this.bits[n >> 5] |= 1 << (n & 31); -}; - -BitSet.prototype.has = function has (n) { - return !!(this.bits[n >> 5] & (1 << (n & 31))); -}; - -var Chunk = function Chunk(start, end, content) { - this.start = start; - this.end = end; - this.original = content; - - this.intro = ''; - this.outro = ''; - - this.content = content; - this.storeName = false; - this.edited = false; - - // we make these non-enumerable, for sanity while debugging - Object.defineProperties(this, { - previous: { writable: true, value: null }, - next: { writable: true, value: null } - }); -}; - -Chunk.prototype.appendLeft = function appendLeft (content) { - this.outro += content; -}; - -Chunk.prototype.appendRight = function appendRight (content) { - this.intro = this.intro + content; -}; - -Chunk.prototype.clone = function clone () { - var chunk = new Chunk(this.start, this.end, this.original); - - chunk.intro = this.intro; - chunk.outro = this.outro; - chunk.content = this.content; - chunk.storeName = this.storeName; - chunk.edited = this.edited; - - return chunk; -}; - -Chunk.prototype.contains = function contains (index) { - return this.start < index && index < this.end; -}; - -Chunk.prototype.eachNext = function eachNext (fn) { - var chunk = this; - while (chunk) { - fn(chunk); - chunk = chunk.next; - } -}; - -Chunk.prototype.eachPrevious = function eachPrevious (fn) { - var chunk = this; - while (chunk) { - fn(chunk); - chunk = chunk.previous; - } -}; - -Chunk.prototype.edit = function edit (content, storeName, contentOnly) { - this.content = content; - if (!contentOnly) { - this.intro = ''; - this.outro = ''; - } - this.storeName = storeName; - - this.edited = true; - - return this; -}; - -Chunk.prototype.prependLeft = function prependLeft (content) { - this.outro = content + this.outro; -}; - -Chunk.prototype.prependRight = function prependRight (content) { - this.intro = content + this.intro; -}; - -Chunk.prototype.split = function split (index) { - var sliceIndex = index - this.start; - - var originalBefore = this.original.slice(0, sliceIndex); - var originalAfter = this.original.slice(sliceIndex); - - this.original = originalBefore; - - var newChunk = new Chunk(index, this.end, originalAfter); - newChunk.outro = this.outro; - this.outro = ''; - - this.end = index; - - if (this.edited) { - // TODO is this block necessary?... - newChunk.edit('', false); - this.content = ''; - } else { - this.content = originalBefore; - } - - newChunk.next = this.next; - if (newChunk.next) { newChunk.next.previous = newChunk; } - newChunk.previous = this; - this.next = newChunk; - - return newChunk; -}; - -Chunk.prototype.toString = function toString () { - return this.intro + this.content + this.outro; -}; - -Chunk.prototype.trimEnd = function trimEnd (rx) { - this.outro = this.outro.replace(rx, ''); - if (this.outro.length) { return true; } - - var trimmed = this.content.replace(rx, ''); - - if (trimmed.length) { - if (trimmed !== this.content) { - this.split(this.start + trimmed.length).edit('', undefined, true); - } - return true; - - } else { - this.edit('', undefined, true); - - this.intro = this.intro.replace(rx, ''); - if (this.intro.length) { return true; } - } -}; - -Chunk.prototype.trimStart = function trimStart (rx) { - this.intro = this.intro.replace(rx, ''); - if (this.intro.length) { return true; } - - var trimmed = this.content.replace(rx, ''); - - if (trimmed.length) { - if (trimmed !== this.content) { - this.split(this.end - trimmed.length); - this.edit('', undefined, true); - } - return true; - - } else { - this.edit('', undefined, true); - - this.outro = this.outro.replace(rx, ''); - if (this.outro.length) { return true; } - } -}; - -var btoa$1 = function () { - throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); -}; -if (typeof window !== 'undefined' && typeof window.btoa === 'function') { - btoa$1 = function (str) { return window.btoa(unescape(encodeURIComponent(str))); }; -} else if (typeof Buffer === 'function') { - btoa$1 = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); }; -} - -var SourceMap = function SourceMap(properties) { - this.version = 3; - this.file = properties.file; - this.sources = properties.sources; - this.sourcesContent = properties.sourcesContent; - this.names = properties.names; - this.mappings = encode(properties.mappings); -}; - -SourceMap.prototype.toString = function toString () { - return JSON.stringify(this); -}; - -SourceMap.prototype.toUrl = function toUrl () { - return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString()); -}; - -function guessIndent(code) { - var lines = code.split('\n'); - - var tabbed = lines.filter(function (line) { return /^\t+/.test(line); }); - var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); }); - - if (tabbed.length === 0 && spaced.length === 0) { - return null; - } - - // More lines tabbed than spaced? Assume tabs, and - // default to tabs in the case of a tie (or nothing - // to go on) - if (tabbed.length >= spaced.length) { - return '\t'; - } - - // Otherwise, we need to guess the multiple - var min = spaced.reduce(function (previous, current) { - var numSpaces = /^ +/.exec(current)[0].length; - return Math.min(numSpaces, previous); - }, Infinity); - - return new Array(min + 1).join(' '); -} - -function getRelativePath(from, to) { - var fromParts = from.split(/[/\\]/); - var toParts = to.split(/[/\\]/); - - fromParts.pop(); // get dirname - - while (fromParts[0] === toParts[0]) { - fromParts.shift(); - toParts.shift(); - } - - if (fromParts.length) { - var i = fromParts.length; - while (i--) { fromParts[i] = '..'; } - } - - return fromParts.concat(toParts).join('/'); -} - -var toString$2 = Object.prototype.toString; - -function isObject$2(thing) { - return toString$2.call(thing) === '[object Object]'; -} - -function getLocator(source) { - var originalLines = source.split('\n'); - var lineOffsets = []; - - for (var i = 0, pos = 0; i < originalLines.length; i++) { - lineOffsets.push(pos); - pos += originalLines[i].length + 1; - } - - return function locate(index) { - var i = 0; - var j = lineOffsets.length; - while (i < j) { - var m = (i + j) >> 1; - if (index < lineOffsets[m]) { - j = m; - } else { - i = m + 1; - } - } - var line = i - 1; - var column = index - lineOffsets[line]; - return { line: line, column: column }; - }; -} - -var Mappings = function Mappings(hires) { - this.hires = hires; - this.generatedCodeLine = 0; - this.generatedCodeColumn = 0; - this.raw = []; - this.rawSegments = this.raw[this.generatedCodeLine] = []; - this.pending = null; -}; - -Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) { - if (content.length) { - var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; - if (nameIndex >= 0) { - segment.push(nameIndex); - } - this.rawSegments.push(segment); - } else if (this.pending) { - this.rawSegments.push(this.pending); - } - - this.advance(content); - this.pending = null; -}; - -Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) { - var originalCharIndex = chunk.start; - var first = true; - - while (originalCharIndex < chunk.end) { - if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { - this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); - } - - if (original[originalCharIndex] === '\n') { - loc.line += 1; - loc.column = 0; - this.generatedCodeLine += 1; - this.raw[this.generatedCodeLine] = this.rawSegments = []; - this.generatedCodeColumn = 0; - first = true; - } else { - loc.column += 1; - this.generatedCodeColumn += 1; - first = false; - } - - originalCharIndex += 1; - } - - this.pending = null; -}; - -Mappings.prototype.advance = function advance (str) { - if (!str) { return; } - - var lines = str.split('\n'); - - if (lines.length > 1) { - for (var i = 0; i < lines.length - 1; i++) { - this.generatedCodeLine++; - this.raw[this.generatedCodeLine] = this.rawSegments = []; - } - this.generatedCodeColumn = 0; - } - - this.generatedCodeColumn += lines[lines.length - 1].length; -}; - -var n = '\n'; - -var warned$1 = { - insertLeft: false, - insertRight: false, - storeName: false -}; - -var MagicString = function MagicString(string, options) { - if ( options === void 0 ) options = {}; - - var chunk = new Chunk(0, string.length, string); - - Object.defineProperties(this, { - original: { writable: true, value: string }, - outro: { writable: true, value: '' }, - intro: { writable: true, value: '' }, - firstChunk: { writable: true, value: chunk }, - lastChunk: { writable: true, value: chunk }, - lastSearchedChunk: { writable: true, value: chunk }, - byStart: { writable: true, value: {} }, - byEnd: { writable: true, value: {} }, - filename: { writable: true, value: options.filename }, - indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, - sourcemapLocations: { writable: true, value: new BitSet() }, - storedNames: { writable: true, value: {} }, - indentStr: { writable: true, value: guessIndent(string) } - }); - - this.byStart[0] = chunk; - this.byEnd[string.length] = chunk; -}; - -MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) { - this.sourcemapLocations.add(char); -}; - -MagicString.prototype.append = function append (content) { - if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } - - this.outro += content; - return this; -}; - -MagicString.prototype.appendLeft = function appendLeft (index, content) { - if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } - - this._split(index); - - var chunk = this.byEnd[index]; - - if (chunk) { - chunk.appendLeft(content); - } else { - this.intro += content; - } - return this; -}; - -MagicString.prototype.appendRight = function appendRight (index, content) { - if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } - - this._split(index); - - var chunk = this.byStart[index]; - - if (chunk) { - chunk.appendRight(content); - } else { - this.outro += content; - } - return this; -}; - -MagicString.prototype.clone = function clone () { - var cloned = new MagicString(this.original, { filename: this.filename }); - - var originalChunk = this.firstChunk; - var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); - - while (originalChunk) { - cloned.byStart[clonedChunk.start] = clonedChunk; - cloned.byEnd[clonedChunk.end] = clonedChunk; - - var nextOriginalChunk = originalChunk.next; - var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); - - if (nextClonedChunk) { - clonedChunk.next = nextClonedChunk; - nextClonedChunk.previous = clonedChunk; - - clonedChunk = nextClonedChunk; - } - - originalChunk = nextOriginalChunk; - } - - cloned.lastChunk = clonedChunk; - - if (this.indentExclusionRanges) { - cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); - } - - cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); - - cloned.intro = this.intro; - cloned.outro = this.outro; - - return cloned; -}; - -MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) { - var this$1$1 = this; - - options = options || {}; - - var sourceIndex = 0; - var names = Object.keys(this.storedNames); - var mappings = new Mappings(options.hires); - - var locate = getLocator(this.original); - - if (this.intro) { - mappings.advance(this.intro); - } - - this.firstChunk.eachNext(function (chunk) { - var loc = locate(chunk.start); - - if (chunk.intro.length) { mappings.advance(chunk.intro); } - - if (chunk.edited) { - mappings.addEdit( - sourceIndex, - chunk.content, - loc, - chunk.storeName ? names.indexOf(chunk.original) : -1 - ); - } else { - mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations); - } - - if (chunk.outro.length) { mappings.advance(chunk.outro); } - }); - - return { - file: options.file ? options.file.split(/[/\\]/).pop() : null, - sources: [options.source ? getRelativePath(options.file || '', options.source) : null], - sourcesContent: options.includeContent ? [this.original] : [null], - names: names, - mappings: mappings.raw - }; -}; - -MagicString.prototype.generateMap = function generateMap (options) { - return new SourceMap(this.generateDecodedMap(options)); -}; - -MagicString.prototype.getIndentString = function getIndentString () { - return this.indentStr === null ? '\t' : this.indentStr; -}; - -MagicString.prototype.indent = function indent (indentStr, options) { - var pattern = /^[^\r\n]/gm; - - if (isObject$2(indentStr)) { - options = indentStr; - indentStr = undefined; - } - - indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t'; - - if (indentStr === '') { return this; } // noop - - options = options || {}; - - // Process exclusion ranges - var isExcluded = {}; - - if (options.exclude) { - var exclusions = - typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; - exclusions.forEach(function (exclusion) { - for (var i = exclusion[0]; i < exclusion[1]; i += 1) { - isExcluded[i] = true; - } - }); - } - - var shouldIndentNextCharacter = options.indentStart !== false; - var replacer = function (match) { - if (shouldIndentNextCharacter) { return ("" + indentStr + match); } - shouldIndentNextCharacter = true; - return match; - }; - - this.intro = this.intro.replace(pattern, replacer); - - var charIndex = 0; - var chunk = this.firstChunk; - - while (chunk) { - var end = chunk.end; - - if (chunk.edited) { - if (!isExcluded[charIndex]) { - chunk.content = chunk.content.replace(pattern, replacer); - - if (chunk.content.length) { - shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; - } - } - } else { - charIndex = chunk.start; - - while (charIndex < end) { - if (!isExcluded[charIndex]) { - var char = this.original[charIndex]; - - if (char === '\n') { - shouldIndentNextCharacter = true; - } else if (char !== '\r' && shouldIndentNextCharacter) { - shouldIndentNextCharacter = false; - - if (charIndex === chunk.start) { - chunk.prependRight(indentStr); - } else { - this._splitChunk(chunk, charIndex); - chunk = chunk.next; - chunk.prependRight(indentStr); - } - } - } - - charIndex += 1; - } - } - - charIndex = chunk.end; - chunk = chunk.next; - } - - this.outro = this.outro.replace(pattern, replacer); - - return this; -}; - -MagicString.prototype.insert = function insert () { - throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'); -}; - -MagicString.prototype.insertLeft = function insertLeft (index, content) { - if (!warned$1.insertLeft) { - console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console - warned$1.insertLeft = true; - } - - return this.appendLeft(index, content); -}; - -MagicString.prototype.insertRight = function insertRight (index, content) { - if (!warned$1.insertRight) { - console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console - warned$1.insertRight = true; - } - - return this.prependRight(index, content); -}; - -MagicString.prototype.move = function move (start, end, index) { - if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); } - - this._split(start); - this._split(end); - this._split(index); - - var first = this.byStart[start]; - var last = this.byEnd[end]; - - var oldLeft = first.previous; - var oldRight = last.next; - - var newRight = this.byStart[index]; - if (!newRight && last === this.lastChunk) { return this; } - var newLeft = newRight ? newRight.previous : this.lastChunk; - - if (oldLeft) { oldLeft.next = oldRight; } - if (oldRight) { oldRight.previous = oldLeft; } - - if (newLeft) { newLeft.next = first; } - if (newRight) { newRight.previous = last; } - - if (!first.previous) { this.firstChunk = last.next; } - if (!last.next) { - this.lastChunk = first.previous; - this.lastChunk.next = null; - } - - first.previous = newLeft; - last.next = newRight || null; - - if (!newLeft) { this.firstChunk = first; } - if (!newRight) { this.lastChunk = last; } - return this; -}; - -MagicString.prototype.overwrite = function overwrite (start, end, content, options) { - if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); } - - while (start < 0) { start += this.original.length; } - while (end < 0) { end += this.original.length; } - - if (end > this.original.length) { throw new Error('end is out of bounds'); } - if (start === end) - { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); } - - this._split(start); - this._split(end); - - if (options === true) { - if (!warned$1.storeName) { - console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console - warned$1.storeName = true; - } - - options = { storeName: true }; - } - var storeName = options !== undefined ? options.storeName : false; - var contentOnly = options !== undefined ? options.contentOnly : false; - - if (storeName) { - var original = this.original.slice(start, end); - this.storedNames[original] = true; - } - - var first = this.byStart[start]; - var last = this.byEnd[end]; - - if (first) { - if (end > first.end && first.next !== this.byStart[first.end]) { - throw new Error('Cannot overwrite across a split point'); - } - - first.edit(content, storeName, contentOnly); - - if (first !== last) { - var chunk = first.next; - while (chunk !== last) { - chunk.edit('', false); - chunk = chunk.next; - } - - chunk.edit('', false); - } - } else { - // must be inserting at the end - var newChunk = new Chunk(start, end, '').edit(content, storeName); - - // TODO last chunk in the array may not be the last chunk, if it's moved... - last.next = newChunk; - newChunk.previous = last; - } - return this; -}; - -MagicString.prototype.prepend = function prepend (content) { - if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } - - this.intro = content + this.intro; - return this; -}; - -MagicString.prototype.prependLeft = function prependLeft (index, content) { - if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } - - this._split(index); - - var chunk = this.byEnd[index]; - - if (chunk) { - chunk.prependLeft(content); - } else { - this.intro = content + this.intro; - } - return this; -}; - -MagicString.prototype.prependRight = function prependRight (index, content) { - if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } - - this._split(index); - - var chunk = this.byStart[index]; - - if (chunk) { - chunk.prependRight(content); - } else { - this.outro = content + this.outro; - } - return this; -}; - -MagicString.prototype.remove = function remove (start, end) { - while (start < 0) { start += this.original.length; } - while (end < 0) { end += this.original.length; } - - if (start === end) { return this; } - - if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); } - if (start > end) { throw new Error('end must be greater than start'); } - - this._split(start); - this._split(end); - - var chunk = this.byStart[start]; - - while (chunk) { - chunk.intro = ''; - chunk.outro = ''; - chunk.edit(''); - - chunk = end > chunk.end ? this.byStart[chunk.end] : null; - } - return this; -}; - -MagicString.prototype.lastChar = function lastChar () { - if (this.outro.length) - { return this.outro[this.outro.length - 1]; } - var chunk = this.lastChunk; - do { - if (chunk.outro.length) - { return chunk.outro[chunk.outro.length - 1]; } - if (chunk.content.length) - { return chunk.content[chunk.content.length - 1]; } - if (chunk.intro.length) - { return chunk.intro[chunk.intro.length - 1]; } - } while (chunk = chunk.previous); - if (this.intro.length) - { return this.intro[this.intro.length - 1]; } - return ''; -}; - -MagicString.prototype.lastLine = function lastLine () { - var lineIndex = this.outro.lastIndexOf(n); - if (lineIndex !== -1) - { return this.outro.substr(lineIndex + 1); } - var lineStr = this.outro; - var chunk = this.lastChunk; - do { - if (chunk.outro.length > 0) { - lineIndex = chunk.outro.lastIndexOf(n); - if (lineIndex !== -1) - { return chunk.outro.substr(lineIndex + 1) + lineStr; } - lineStr = chunk.outro + lineStr; - } - - if (chunk.content.length > 0) { - lineIndex = chunk.content.lastIndexOf(n); - if (lineIndex !== -1) - { return chunk.content.substr(lineIndex + 1) + lineStr; } - lineStr = chunk.content + lineStr; - } - - if (chunk.intro.length > 0) { - lineIndex = chunk.intro.lastIndexOf(n); - if (lineIndex !== -1) - { return chunk.intro.substr(lineIndex + 1) + lineStr; } - lineStr = chunk.intro + lineStr; - } - } while (chunk = chunk.previous); - lineIndex = this.intro.lastIndexOf(n); - if (lineIndex !== -1) - { return this.intro.substr(lineIndex + 1) + lineStr; } - return this.intro + lineStr; -}; - -MagicString.prototype.slice = function slice (start, end) { - if ( start === void 0 ) start = 0; - if ( end === void 0 ) end = this.original.length; - - while (start < 0) { start += this.original.length; } - while (end < 0) { end += this.original.length; } - - var result = ''; - - // find start chunk - var chunk = this.firstChunk; - while (chunk && (chunk.start > start || chunk.end <= start)) { - // found end chunk before start - if (chunk.start < end && chunk.end >= end) { - return result; - } - - chunk = chunk.next; - } - - if (chunk && chunk.edited && chunk.start !== start) - { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); } - - var startChunk = chunk; - while (chunk) { - if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { - result += chunk.intro; - } - - var containsEnd = chunk.start < end && chunk.end >= end; - if (containsEnd && chunk.edited && chunk.end !== end) - { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); } - - var sliceStart = startChunk === chunk ? start - chunk.start : 0; - var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; - - result += chunk.content.slice(sliceStart, sliceEnd); - - if (chunk.outro && (!containsEnd || chunk.end === end)) { - result += chunk.outro; - } - - if (containsEnd) { - break; - } - - chunk = chunk.next; - } - - return result; -}; - -// TODO deprecate this? not really very useful -MagicString.prototype.snip = function snip (start, end) { - var clone = this.clone(); - clone.remove(0, start); - clone.remove(end, clone.original.length); - - return clone; -}; - -MagicString.prototype._split = function _split (index) { - if (this.byStart[index] || this.byEnd[index]) { return; } - - var chunk = this.lastSearchedChunk; - var searchForward = index > chunk.end; - - while (chunk) { - if (chunk.contains(index)) { return this._splitChunk(chunk, index); } - - chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; - } -}; - -MagicString.prototype._splitChunk = function _splitChunk (chunk, index) { - if (chunk.edited && chunk.content.length) { - // zero-length edited chunks are a special case (overlapping replacements) - var loc = getLocator(this.original)(index); - throw new Error( - ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") - ); - } - - var newChunk = chunk.split(index); - - this.byEnd[index] = chunk; - this.byStart[index] = newChunk; - this.byEnd[newChunk.end] = newChunk; - - if (chunk === this.lastChunk) { this.lastChunk = newChunk; } - - this.lastSearchedChunk = chunk; - return true; -}; - -MagicString.prototype.toString = function toString () { - var str = this.intro; - - var chunk = this.firstChunk; - while (chunk) { - str += chunk.toString(); - chunk = chunk.next; - } - - return str + this.outro; -}; - -MagicString.prototype.isEmpty = function isEmpty () { - var chunk = this.firstChunk; - do { - if (chunk.intro.length && chunk.intro.trim() || - chunk.content.length && chunk.content.trim() || - chunk.outro.length && chunk.outro.trim()) - { return false; } - } while (chunk = chunk.next); - return true; -}; - -MagicString.prototype.length = function length () { - var chunk = this.firstChunk; - var length = 0; - do { - length += chunk.intro.length + chunk.content.length + chunk.outro.length; - } while (chunk = chunk.next); - return length; -}; - -MagicString.prototype.trimLines = function trimLines () { - return this.trim('[\\r\\n]'); -}; - -MagicString.prototype.trim = function trim (charType) { - return this.trimStart(charType).trimEnd(charType); -}; - -MagicString.prototype.trimEndAborted = function trimEndAborted (charType) { - var rx = new RegExp((charType || '\\s') + '+$'); - - this.outro = this.outro.replace(rx, ''); - if (this.outro.length) { return true; } - - var chunk = this.lastChunk; - - do { - var end = chunk.end; - var aborted = chunk.trimEnd(rx); - - // if chunk was trimmed, we have a new lastChunk - if (chunk.end !== end) { - if (this.lastChunk === chunk) { - this.lastChunk = chunk.next; - } - - this.byEnd[chunk.end] = chunk; - this.byStart[chunk.next.start] = chunk.next; - this.byEnd[chunk.next.end] = chunk.next; - } - - if (aborted) { return true; } - chunk = chunk.previous; - } while (chunk); - - return false; -}; - -MagicString.prototype.trimEnd = function trimEnd (charType) { - this.trimEndAborted(charType); - return this; -}; -MagicString.prototype.trimStartAborted = function trimStartAborted (charType) { - var rx = new RegExp('^' + (charType || '\\s') + '+'); - - this.intro = this.intro.replace(rx, ''); - if (this.intro.length) { return true; } - - var chunk = this.firstChunk; - - do { - var end = chunk.end; - var aborted = chunk.trimStart(rx); - - if (chunk.end !== end) { - // special case... - if (chunk === this.lastChunk) { this.lastChunk = chunk.next; } - - this.byEnd[chunk.end] = chunk; - this.byStart[chunk.next.start] = chunk.next; - this.byEnd[chunk.next.end] = chunk.next; - } - - if (aborted) { return true; } - chunk = chunk.next; - } while (chunk); - - return false; -}; - -MagicString.prototype.trimStart = function trimStart (charType) { - this.trimStartAborted(charType); - return this; -}; - -/** - * @param typeMap [Object] Map of MIME type -> Array[extensions] - * @param ... - */ -function Mime$1() { - this._types = Object.create(null); - this._extensions = Object.create(null); - - for (let i = 0; i < arguments.length; i++) { - this.define(arguments[i]); - } - - this.define = this.define.bind(this); - this.getType = this.getType.bind(this); - this.getExtension = this.getExtension.bind(this); -} - -/** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * If a type declares an extension that has already been defined, an error will - * be thrown. To suppress this error and force the extension to be associated - * with the new type, pass `force`=true. Alternatively, you may prefix the - * extension with "*" to map the type to extension, without mapping the - * extension to the type. - * - * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); - * - * - * @param map (Object) type definitions - * @param force (Boolean) if true, force overriding of existing definitions - */ -Mime$1.prototype.define = function(typeMap, force) { - for (let type in typeMap) { - let extensions = typeMap[type].map(function(t) { - return t.toLowerCase(); - }); - type = type.toLowerCase(); - - for (let i = 0; i < extensions.length; i++) { - const ext = extensions[i]; - - // '*' prefix = not the preferred type for this extension. So fixup the - // extension, and skip it. - if (ext[0] === '*') { - continue; - } - - if (!force && (ext in this._types)) { - throw new Error( - 'Attempt to change mapping for "' + ext + - '" extension from "' + this._types[ext] + '" to "' + type + - '". Pass `force=true` to allow this, otherwise remove "' + ext + - '" from the list of extensions for "' + type + '".' - ); - } - - this._types[ext] = type; - } - - // Use first extension as default - if (force || !this._extensions[type]) { - const ext = extensions[0]; - this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1); - } - } -}; - -/** - * Lookup a mime type based on extension - */ -Mime$1.prototype.getType = function(path) { - path = String(path); - let last = path.replace(/^.*[/\\]/, '').toLowerCase(); - let ext = last.replace(/^.*\./, '').toLowerCase(); - - let hasPath = last.length < path.length; - let hasDot = ext.length < last.length - 1; - - return (hasDot || !hasPath) && this._types[ext] || null; -}; - -/** - * Return file extension associated with a mime type - */ -Mime$1.prototype.getExtension = function(type) { - type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; - return type && this._extensions[type.toLowerCase()] || null; -}; - -var Mime_1 = Mime$1; - -var standard = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma","es"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/mrb-consumer+xml":["*xdf"],"application/mrb-publish+xml":["*xdf"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["*xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-error+xml":["xer"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}; - -let Mime = Mime_1; -var lite = new Mime(standard); - -const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g; -// urls in JS must be quoted as strings, so when replacing them we need -// a different regex -const assetUrlQuotedRE = /"__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?"/g; -const rawRE = /(\?|&)raw(?:&|$)/; -const urlRE = /(\?|&)url(?:&|$)/; -const isURLRequest = (id) => urlRE.test(id) -const chunkToEmittedAssetsMap = new WeakMap(); -const assetCache = new WeakMap(); -const assetHashToFilenameMap = new WeakMap(); -// save hashes of the files that has been emitted in build watch -const emittedHashMap = new WeakMap(); -/** - * Also supports loading plain strings with import text from './foo.txt?raw' - */ -function assetPlugin(config) { - // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined - assetHashToFilenameMap.set(config, new Map()); - return { - name: 'vite:asset', - buildStart() { - assetCache.set(config, new Map()); - emittedHashMap.set(config, new Set()); - }, - resolveId(id) { - if (!config.assetsInclude(cleanUrl(id))) { - return; - } - // imports to absolute urls pointing to files in /public - // will fail to resolve in the main resolver. handle them here. - const publicFile = checkPublicFile(id, config); - if (publicFile) { - return id; - } - }, - async load(id) { - if (id.startsWith('\0')) { - // Rollup convention, this id should be handled by the - // plugin that marked it with \0 - return; - } - // raw requests, read from disk - if (rawRE.test(id)) { - const file = checkPublicFile(id, config) || cleanUrl(id); - // raw query, read file and return as string - return `export default ${JSON.stringify(await fs$r.promises.readFile(file, 'utf-8'))}`; - } - if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) { - return; - } - id = id.replace(urlRE, '$1').replace(/[\?&]$/, ''); - const url = await fileToUrl(id, config, this); - return `export default ${JSON.stringify(url)}`; - }, - renderChunk(code, chunk) { - let match; - let s; - while ((match = assetUrlQuotedRE.exec(code))) { - s = s || (s = new MagicString(code)); - const [full, hash, postfix = ''] = match; - // some internal plugins may still need to emit chunks (e.g. worker) so - // fallback to this.getFileName for that. - const file = getAssetFilename(hash, config) || this.getFileName(hash); - registerAssetToChunk(chunk, file); - const outputFilepath = config.base + file + postfix; - s.overwrite(match.index, match.index + full.length, JSON.stringify(outputFilepath)); - } - if (s) { - return { - code: s.toString(), - map: config.build.sourcemap ? s.generateMap({ hires: true }) : null - }; - } - else { - return null; - } - }, - generateBundle(_, bundle) { - // do not emit assets for SSR build - if (config.command === 'build' && config.build.ssr) { - for (const file in bundle) { - if (bundle[file].type === 'asset' && - !file.includes('ssr-manifest.json')) { - delete bundle[file]; - } - } - } - } - }; -} -function registerAssetToChunk(chunk, file) { - let emitted = chunkToEmittedAssetsMap.get(chunk); - if (!emitted) { - emitted = new Set(); - chunkToEmittedAssetsMap.set(chunk, emitted); - } - emitted.add(cleanUrl(file)); -} -function checkPublicFile(url, { publicDir }) { - // note if the file is in /public, the resolver would have returned it - // as-is so it's not going to be a fully resolved path. - if (!publicDir || !url.startsWith('/')) { - return; - } - const publicFile = path__default.join(publicDir, cleanUrl(url)); - if (fs__default.existsSync(publicFile)) { - return publicFile; - } - else { - return; - } -} -function fileToUrl(id, config, ctx) { - if (config.command === 'serve') { - return fileToDevUrl(id, config); - } - else { - return fileToBuiltUrl(id, config, ctx); - } -} -function fileToDevUrl(id, config) { - var _a, _b; - let rtn; - if (checkPublicFile(id, config)) { - // in public dir, keep the url as-is - rtn = id; - } - else if (id.startsWith(config.root)) { - // in project root, infer short public path - rtn = '/' + path__default.posix.relative(config.root, id); - } - else { - // outside of project root, use absolute fs path - // (this is special handled by the serve static middleware - rtn = path__default.posix.join(FS_PREFIX + id); - } - const origin = (_b = (_a = config.server) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : ''; - return origin + config.base + rtn.replace(/^\//, ''); -} -function getAssetFilename(hash, config) { - var _a; - return (_a = assetHashToFilenameMap.get(config)) === null || _a === void 0 ? void 0 : _a.get(hash); -} -/** - * converts the source filepath of the asset to the output filename based on the assetFileNames option. \ - * this function imitates the behavior of rollup.js. \ - * https://rollupjs.org/guide/en/#outputassetfilenames - * - * @example - * ```ts - * const content = Buffer.from('text'); - * const fileName = assetFileNamesToFileName( - * 'assets/[name].[hash][extname]', - * '/path/to/file.txt', - * getAssetHash(content), - * content - * ) - * // fileName: 'assets/file.982d9e3e.txt' - * ``` - * - * @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'` - * @param file filepath of the asset - * @param contentHash hash of the asset. used for `'[hash]'` placeholder - * @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function - * @returns output filename - */ -function assetFileNamesToFileName(assetFileNames, file, contentHash, content) { - const basename = path__default.basename(file); - // placeholders for `assetFileNames` - // `hash` is slightly different from the rollup's one - const extname = path__default.extname(basename); - const ext = extname.substr(1); - const name = basename.slice(0, -extname.length); - const hash = contentHash; - if (typeof assetFileNames === 'function') { - assetFileNames = assetFileNames({ - name: file, - source: content, - type: 'asset' - }); - if (typeof assetFileNames !== 'string') { - throw new TypeError('assetFileNames must return a string'); - } - } - else if (typeof assetFileNames !== 'string') { - throw new TypeError('assetFileNames must be a string or a function'); - } - const fileName = assetFileNames.replace(/\[\w+\]/g, (placeholder) => { - switch (placeholder) { - case '[ext]': - return ext; - case '[extname]': - return extname; - case '[hash]': - return hash; - case '[name]': - return name; - } - throw new Error(`invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"`); - }); - return fileName; -} -/** - * Register an asset to be emitted as part of the bundle (if necessary) - * and returns the resolved public URL - */ -async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) { - var _a, _b, _c; - if (!skipPublicCheck && checkPublicFile(id, config)) { - return config.base + id.slice(1); - } - const cache = assetCache.get(config); - const cached = cache.get(id); - if (cached) { - return cached; - } - const file = cleanUrl(id); - const content = await fs$r.promises.readFile(file); - let url; - if (config.build.lib || - (!file.endsWith('.svg') && - content.length < Number(config.build.assetsInlineLimit))) { - // base64 inlined as a string - url = `data:${lite.getType(file)};base64,${content.toString('base64')}`; - } - else { - // emit as asset - // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code - // that uses runtime url sniffing and it can be verbose when targeting - // non-module format. It also fails to cascade the asset content change - // into the chunk's hash, so we have to do our own content hashing here. - // https://bundlers.tooling.report/hashing/asset-cascade/ - // https://github.com/rollup/rollup/issues/3415 - const map = assetHashToFilenameMap.get(config); - const contentHash = getAssetHash(content); - const { search, hash } = require$$0$8.parse(id); - const postfix = (search || '') + (hash || ''); - const output = (_b = (_a = config.build) === null || _a === void 0 ? void 0 : _a.rollupOptions) === null || _b === void 0 ? void 0 : _b.output; - const assetFileNames = (_c = (output && !Array.isArray(output) ? output.assetFileNames : undefined)) !== null && _c !== void 0 ? _c : - // defaults to '/[name].[hash][extname]' - // slightly different from rollup's one ('assets/[name]-[hash][extname]') - path__default.posix.join(config.build.assetsDir, '[name].[hash][extname]'); - const fileName = assetFileNamesToFileName(assetFileNames, file, contentHash, content); - if (!map.has(contentHash)) { - map.set(contentHash, fileName); - } - const emittedSet = emittedHashMap.get(config); - if (!emittedSet.has(contentHash)) { - const name = normalizePath$4(path__default.relative(config.root, file)); - pluginContext.emitFile({ - name, - fileName, - type: 'asset', - source: content - }); - emittedSet.add(contentHash); - } - url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`; - } - cache.set(id, url); - return url; -} -function getAssetHash(content) { - return require$$1.createHash('sha256').update(content).digest('hex').slice(0, 8); -} -async function urlToBuiltUrl(url, importer, config, pluginContext) { - if (checkPublicFile(url, config)) { - return config.base + url.slice(1); - } - const file = url.startsWith('/') - ? path__default.join(config.root, url) - : path__default.join(path__default.dirname(importer), url); - return fileToBuiltUrl(file, config, pluginContext, - // skip public check since we just did it above - true); -} - -var tasks = {}; - -var utils$k = {}; - -var array$1 = {}; - -Object.defineProperty(array$1, "__esModule", { value: true }); -array$1.splitWhen = array$1.flatten = void 0; -function flatten$1(items) { - return items.reduce((collection, item) => [].concat(collection, item), []); -} -array$1.flatten = flatten$1; -function splitWhen(items, predicate) { - const result = [[]]; - let groupIndex = 0; - for (const item of items) { - if (predicate(item)) { - groupIndex++; - result[groupIndex] = []; - } - else { - result[groupIndex].push(item); - } - } - return result; -} -array$1.splitWhen = splitWhen; - -var errno$1 = {}; - -Object.defineProperty(errno$1, "__esModule", { value: true }); -errno$1.isEnoentCodeError = void 0; -function isEnoentCodeError(error) { - return error.code === 'ENOENT'; -} -errno$1.isEnoentCodeError = isEnoentCodeError; - -var fs$q = {}; - -Object.defineProperty(fs$q, "__esModule", { value: true }); -fs$q.createDirentFromStats = void 0; -class DirentFromStats$1 { - constructor(name, stats) { - this.name = name; - this.isBlockDevice = stats.isBlockDevice.bind(stats); - this.isCharacterDevice = stats.isCharacterDevice.bind(stats); - this.isDirectory = stats.isDirectory.bind(stats); - this.isFIFO = stats.isFIFO.bind(stats); - this.isFile = stats.isFile.bind(stats); - this.isSocket = stats.isSocket.bind(stats); - this.isSymbolicLink = stats.isSymbolicLink.bind(stats); - } -} -function createDirentFromStats$1(name, stats) { - return new DirentFromStats$1(name, stats); -} -fs$q.createDirentFromStats = createDirentFromStats$1; - -var path$s = {}; - -Object.defineProperty(path$s, "__esModule", { value: true }); -path$s.removeLeadingDotSegment = path$s.escape = path$s.makeAbsolute = path$s.unixify = void 0; -const path$r = path__default; -const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ -const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; -/** - * Designed to work only with simple paths: `dir\\file`. - */ -function unixify(filepath) { - return filepath.replace(/\\/g, '/'); -} -path$s.unixify = unixify; -function makeAbsolute(cwd, filepath) { - return path$r.resolve(cwd, filepath); -} -path$s.makeAbsolute = makeAbsolute; -function escape$1(pattern) { - return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); -} -path$s.escape = escape$1; -function removeLeadingDotSegment(entry) { - // We do not use `startsWith` because this is 10x slower than current implementation for some cases. - // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with - if (entry.charAt(0) === '.') { - const secondCharactery = entry.charAt(1); - if (secondCharactery === '/' || secondCharactery === '\\') { - return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); - } - } - return entry; -} -path$s.removeLeadingDotSegment = removeLeadingDotSegment; - -var pattern$1 = {}; - -/*! - * is-extglob - * - * Copyright (c) 2014-2016, Jon Schlinkert. - * Licensed under the MIT License. - */ - -var isExtglob$1 = function isExtglob(str) { - if (typeof str !== 'string' || str === '') { - return false; - } - - var match; - while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { - if (match[2]) return true; - str = str.slice(match.index + match[0].length); - } - - return false; -}; - -/*! - * is-glob - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -var isExtglob = isExtglob$1; -var chars = { '{': '}', '(': ')', '[': ']'}; -var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; -var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; - -var isGlob$2 = function isGlob(str, options) { - if (typeof str !== 'string' || str === '') { - return false; - } - - if (isExtglob(str)) { - return true; - } - - var regex = strictRegex; - var match; - - // optionally relax regex - if (options && options.strict === false) { - regex = relaxedRegex; - } - - while ((match = regex.exec(str))) { - if (match[2]) return true; - var idx = match.index + match[0].length; - - // if an open bracket/brace/paren is escaped, - // set the index to the next closing character - var open = match[1]; - var close = open ? chars[open] : null; - if (open && close) { - var n = str.indexOf(close, idx); - if (n !== -1) { - idx = n + 1; - } - } - - str = str.slice(idx); - } - return false; -}; - -var isGlob$1 = isGlob$2; -var pathPosixDirname = path__default.posix.dirname; -var isWin32 = require$$0__default$1.platform() === 'win32'; - -var slash$2 = '/'; -var backslash = /\\/g; -var enclosure = /[\{\[].*[\}\]]$/; -var globby$2 = /(^|[^\\])([\{\[]|\([^\)]+$)/; -var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; - -/** - * @param {string} str - * @param {Object} opts - * @param {boolean} [opts.flipBackslashes=true] - * @returns {string} - */ -var globParent$2 = function globParent(str, opts) { - var options = Object.assign({ flipBackslashes: true }, opts); - - // flip windows path separators - if (options.flipBackslashes && isWin32 && str.indexOf(slash$2) < 0) { - str = str.replace(backslash, slash$2); - } - - // special case for strings ending in enclosure containing path separator - if (enclosure.test(str)) { - str += slash$2; - } - - // preserves full path in case of trailing path separator - str += 'a'; - - // remove path parts that are globby - do { - str = pathPosixDirname(str); - } while (isGlob$1(str) || globby$2.test(str)); - - // remove escape chars and return result - return str.replace(escaped, '$1'); -}; - -var utils$j = {}; - -(function (exports) { - -exports.isInteger = num => { - if (typeof num === 'number') { - return Number.isInteger(num); - } - if (typeof num === 'string' && num.trim() !== '') { - return Number.isInteger(Number(num)); - } - return false; -}; - -/** - * Find a node of the given type - */ - -exports.find = (node, type) => node.nodes.find(node => node.type === type); - -/** - * Find a node of the given type - */ - -exports.exceedsLimit = (min, max, step = 1, limit) => { - if (limit === false) return false; - if (!exports.isInteger(min) || !exports.isInteger(max)) return false; - return ((Number(max) - Number(min)) / Number(step)) >= limit; -}; - -/** - * Escape the given node with '\\' before node.value - */ - -exports.escapeNode = (block, n = 0, type) => { - let node = block.nodes[n]; - if (!node) return; - - if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { - if (node.escaped !== true) { - node.value = '\\' + node.value; - node.escaped = true; - } - } -}; - -/** - * Returns true if the given brace node should be enclosed in literal braces - */ - -exports.encloseBrace = node => { - if (node.type !== 'brace') return false; - if ((node.commas >> 0 + node.ranges >> 0) === 0) { - node.invalid = true; - return true; - } - return false; -}; - -/** - * Returns true if a brace node is invalid. - */ - -exports.isInvalidBrace = block => { - if (block.type !== 'brace') return false; - if (block.invalid === true || block.dollar) return true; - if ((block.commas >> 0 + block.ranges >> 0) === 0) { - block.invalid = true; - return true; - } - if (block.open !== true || block.close !== true) { - block.invalid = true; - return true; - } - return false; -}; - -/** - * Returns true if a node is an open or close node - */ - -exports.isOpenOrClose = node => { - if (node.type === 'open' || node.type === 'close') { - return true; - } - return node.open === true || node.close === true; -}; - -/** - * Reduce an array of text nodes. - */ - -exports.reduce = nodes => nodes.reduce((acc, node) => { - if (node.type === 'text') acc.push(node.value); - if (node.type === 'range') node.type = 'text'; - return acc; -}, []); - -/** - * Flatten an array - */ - -exports.flatten = (...args) => { - const result = []; - const flat = arr => { - for (let i = 0; i < arr.length; i++) { - let ele = arr[i]; - Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); - } - return result; - }; - flat(args); - return result; -}; -}(utils$j)); - -const utils$i = utils$j; - -var stringify$7 = (ast, options = {}) => { - let stringify = (node, parent = {}) => { - let invalidBlock = options.escapeInvalid && utils$i.isInvalidBrace(parent); - let invalidNode = node.invalid === true && options.escapeInvalid === true; - let output = ''; - - if (node.value) { - if ((invalidBlock || invalidNode) && utils$i.isOpenOrClose(node)) { - return '\\' + node.value; - } - return node.value; - } - - if (node.value) { - return node.value; - } - - if (node.nodes) { - for (let child of node.nodes) { - output += stringify(child); - } - } - return output; - }; - - return stringify(ast); -}; - -/*! - * is-number - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Released under the MIT License. - */ - -var isNumber$2 = function(num) { - if (typeof num === 'number') { - return num - num === 0; - } - if (typeof num === 'string' && num.trim() !== '') { - return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); - } - return false; -}; - -/*! - * to-regex-range - * - * Copyright (c) 2015-present, Jon Schlinkert. - * Released under the MIT License. - */ - -const isNumber$1 = isNumber$2; - -const toRegexRange$1 = (min, max, options) => { - if (isNumber$1(min) === false) { - throw new TypeError('toRegexRange: expected the first argument to be a number'); - } - - if (max === void 0 || min === max) { - return String(min); - } - - if (isNumber$1(max) === false) { - throw new TypeError('toRegexRange: expected the second argument to be a number.'); - } - - let opts = { relaxZeros: true, ...options }; - if (typeof opts.strictZeros === 'boolean') { - opts.relaxZeros = opts.strictZeros === false; - } - - let relax = String(opts.relaxZeros); - let shorthand = String(opts.shorthand); - let capture = String(opts.capture); - let wrap = String(opts.wrap); - let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; - - if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) { - return toRegexRange$1.cache[cacheKey].result; - } - - let a = Math.min(min, max); - let b = Math.max(min, max); - - if (Math.abs(a - b) === 1) { - let result = min + '|' + max; - if (opts.capture) { - return `(${result})`; - } - if (opts.wrap === false) { - return result; - } - return `(?:${result})`; - } - - let isPadded = hasPadding(min) || hasPadding(max); - let state = { min, max, a, b }; - let positives = []; - let negatives = []; - - if (isPadded) { - state.isPadded = isPadded; - state.maxLen = String(state.max).length; - } - - if (a < 0) { - let newMin = b < 0 ? Math.abs(b) : 1; - negatives = splitToPatterns(newMin, Math.abs(a), state, opts); - a = state.a = 0; - } - - if (b >= 0) { - positives = splitToPatterns(a, b, state, opts); - } - - state.negatives = negatives; - state.positives = positives; - state.result = collatePatterns(negatives, positives); - - if (opts.capture === true) { - state.result = `(${state.result})`; - } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { - state.result = `(?:${state.result})`; - } - - toRegexRange$1.cache[cacheKey] = state; - return state.result; -}; - -function collatePatterns(neg, pos, options) { - let onlyNegative = filterPatterns(neg, pos, '-', false) || []; - let onlyPositive = filterPatterns(pos, neg, '', false) || []; - let intersected = filterPatterns(neg, pos, '-?', true) || []; - let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); - return subpatterns.join('|'); -} - -function splitToRanges(min, max) { - let nines = 1; - let zeros = 1; - - let stop = countNines(min, nines); - let stops = new Set([max]); - - while (min <= stop && stop <= max) { - stops.add(stop); - nines += 1; - stop = countNines(min, nines); - } - - stop = countZeros(max + 1, zeros) - 1; - - while (min < stop && stop <= max) { - stops.add(stop); - zeros += 1; - stop = countZeros(max + 1, zeros) - 1; - } - - stops = [...stops]; - stops.sort(compare); - return stops; -} - -/** - * Convert a range to a regex pattern - * @param {Number} `start` - * @param {Number} `stop` - * @return {String} - */ - -function rangeToPattern(start, stop, options) { - if (start === stop) { - return { pattern: start, count: [], digits: 0 }; - } - - let zipped = zip(start, stop); - let digits = zipped.length; - let pattern = ''; - let count = 0; - - for (let i = 0; i < digits; i++) { - let [startDigit, stopDigit] = zipped[i]; - - if (startDigit === stopDigit) { - pattern += startDigit; - - } else if (startDigit !== '0' || stopDigit !== '9') { - pattern += toCharacterClass(startDigit, stopDigit); - - } else { - count++; - } - } - - if (count) { - pattern += options.shorthand === true ? '\\d' : '[0-9]'; - } - - return { pattern, count: [count], digits }; -} - -function splitToPatterns(min, max, tok, options) { - let ranges = splitToRanges(min, max); - let tokens = []; - let start = min; - let prev; - - for (let i = 0; i < ranges.length; i++) { - let max = ranges[i]; - let obj = rangeToPattern(String(start), String(max), options); - let zeros = ''; - - if (!tok.isPadded && prev && prev.pattern === obj.pattern) { - if (prev.count.length > 1) { - prev.count.pop(); - } - - prev.count.push(obj.count[0]); - prev.string = prev.pattern + toQuantifier(prev.count); - start = max + 1; - continue; - } - - if (tok.isPadded) { - zeros = padZeros(max, tok, options); - } - - obj.string = zeros + obj.pattern + toQuantifier(obj.count); - tokens.push(obj); - start = max + 1; - prev = obj; - } - - return tokens; -} - -function filterPatterns(arr, comparison, prefix, intersection, options) { - let result = []; - - for (let ele of arr) { - let { string } = ele; - - // only push if _both_ are negative... - if (!intersection && !contains(comparison, 'string', string)) { - result.push(prefix + string); - } - - // or _both_ are positive - if (intersection && contains(comparison, 'string', string)) { - result.push(prefix + string); - } - } - return result; -} - -/** - * Zip strings - */ - -function zip(a, b) { - let arr = []; - for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); - return arr; -} - -function compare(a, b) { - return a > b ? 1 : b > a ? -1 : 0; -} - -function contains(arr, key, val) { - return arr.some(ele => ele[key] === val); -} - -function countNines(min, len) { - return Number(String(min).slice(0, -len) + '9'.repeat(len)); -} - -function countZeros(integer, zeros) { - return integer - (integer % Math.pow(10, zeros)); -} - -function toQuantifier(digits) { - let [start = 0, stop = ''] = digits; - if (stop || start > 1) { - return `{${start + (stop ? ',' + stop : '')}}`; - } - return ''; -} - -function toCharacterClass(a, b, options) { - return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; -} - -function hasPadding(str) { - return /^-?(0+)\d/.test(str); -} - -function padZeros(value, tok, options) { - if (!tok.isPadded) { - return value; - } - - let diff = Math.abs(tok.maxLen - String(value).length); - let relax = options.relaxZeros !== false; - - switch (diff) { - case 0: - return ''; - case 1: - return relax ? '0?' : '0'; - case 2: - return relax ? '0{0,2}' : '00'; - default: { - return relax ? `0{0,${diff}}` : `0{${diff}}`; - } - } -} - -/** - * Cache - */ - -toRegexRange$1.cache = {}; -toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {}); - -/** - * Expose `toRegexRange` - */ - -var toRegexRange_1 = toRegexRange$1; - -/*! - * fill-range - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Licensed under the MIT License. - */ - -const util$8 = require$$0__default$2; -const toRegexRange = toRegexRange_1; - -const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val); - -const transform = toNumber => { - return value => toNumber === true ? Number(value) : String(value); -}; - -const isValidValue = value => { - return typeof value === 'number' || (typeof value === 'string' && value !== ''); -}; - -const isNumber = num => Number.isInteger(+num); - -const zeros = input => { - let value = `${input}`; - let index = -1; - if (value[0] === '-') value = value.slice(1); - if (value === '0') return false; - while (value[++index] === '0'); - return index > 0; -}; - -const stringify$6 = (start, end, options) => { - if (typeof start === 'string' || typeof end === 'string') { - return true; - } - return options.stringify === true; -}; - -const pad = (input, maxLength, toNumber) => { - if (maxLength > 0) { - let dash = input[0] === '-' ? '-' : ''; - if (dash) input = input.slice(1); - input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); - } - if (toNumber === false) { - return String(input); - } - return input; -}; - -const toMaxLen = (input, maxLength) => { - let negative = input[0] === '-' ? '-' : ''; - if (negative) { - input = input.slice(1); - maxLength--; - } - while (input.length < maxLength) input = '0' + input; - return negative ? ('-' + input) : input; -}; - -const toSequence = (parts, options) => { - parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - - let prefix = options.capture ? '' : '?:'; - let positives = ''; - let negatives = ''; - let result; - - if (parts.positives.length) { - positives = parts.positives.join('|'); - } - - if (parts.negatives.length) { - negatives = `-(${prefix}${parts.negatives.join('|')})`; - } - - if (positives && negatives) { - result = `${positives}|${negatives}`; - } else { - result = positives || negatives; - } - - if (options.wrap) { - return `(${prefix}${result})`; - } - - return result; -}; - -const toRange = (a, b, isNumbers, options) => { - if (isNumbers) { - return toRegexRange(a, b, { wrap: false, ...options }); - } - - let start = String.fromCharCode(a); - if (a === b) return start; - - let stop = String.fromCharCode(b); - return `[${start}-${stop}]`; -}; - -const toRegex = (start, end, options) => { - if (Array.isArray(start)) { - let wrap = options.wrap === true; - let prefix = options.capture ? '' : '?:'; - return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); - } - return toRegexRange(start, end, options); -}; - -const rangeError = (...args) => { - return new RangeError('Invalid range arguments: ' + util$8.inspect(...args)); -}; - -const invalidRange = (start, end, options) => { - if (options.strictRanges === true) throw rangeError([start, end]); - return []; -}; - -const invalidStep = (step, options) => { - if (options.strictRanges === true) { - throw new TypeError(`Expected step "${step}" to be a number`); - } - return []; -}; - -const fillNumbers = (start, end, step = 1, options = {}) => { - let a = Number(start); - let b = Number(end); - - if (!Number.isInteger(a) || !Number.isInteger(b)) { - if (options.strictRanges === true) throw rangeError([start, end]); - return []; - } - - // fix negative zero - if (a === 0) a = 0; - if (b === 0) b = 0; - - let descending = a > b; - let startString = String(start); - let endString = String(end); - let stepString = String(step); - step = Math.max(Math.abs(step), 1); - - let padded = zeros(startString) || zeros(endString) || zeros(stepString); - let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; - let toNumber = padded === false && stringify$6(start, end, options) === false; - let format = options.transform || transform(toNumber); - - if (options.toRegex && step === 1) { - return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); - } - - let parts = { negatives: [], positives: [] }; - let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); - let range = []; - let index = 0; - - while (descending ? a >= b : a <= b) { - if (options.toRegex === true && step > 1) { - push(a); - } else { - range.push(pad(format(a, index), maxLen, toNumber)); - } - a = descending ? a - step : a + step; - index++; - } - - if (options.toRegex === true) { - return step > 1 - ? toSequence(parts, options) - : toRegex(range, null, { wrap: false, ...options }); - } - - return range; -}; - -const fillLetters = (start, end, step = 1, options = {}) => { - if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { - return invalidRange(start, end, options); - } - - - let format = options.transform || (val => String.fromCharCode(val)); - let a = `${start}`.charCodeAt(0); - let b = `${end}`.charCodeAt(0); - - let descending = a > b; - let min = Math.min(a, b); - let max = Math.max(a, b); - - if (options.toRegex && step === 1) { - return toRange(min, max, false, options); - } - - let range = []; - let index = 0; - - while (descending ? a >= b : a <= b) { - range.push(format(a, index)); - a = descending ? a - step : a + step; - index++; - } - - if (options.toRegex === true) { - return toRegex(range, null, { wrap: false, options }); - } - - return range; -}; - -const fill$2 = (start, end, step, options = {}) => { - if (end == null && isValidValue(start)) { - return [start]; - } - - if (!isValidValue(start) || !isValidValue(end)) { - return invalidRange(start, end, options); - } - - if (typeof step === 'function') { - return fill$2(start, end, 1, { transform: step }); - } - - if (isObject$1(step)) { - return fill$2(start, end, 0, step); - } - - let opts = { ...options }; - if (opts.capture === true) opts.wrap = true; - step = step || opts.step || 1; - - if (!isNumber(step)) { - if (step != null && !isObject$1(step)) return invalidStep(step, opts); - return fill$2(start, end, 1, step); - } - - if (isNumber(start) && isNumber(end)) { - return fillNumbers(start, end, step, opts); - } - - return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); -}; - -var fillRange = fill$2; - -const fill$1 = fillRange; -const utils$h = utils$j; - -const compile$1 = (ast, options = {}) => { - let walk = (node, parent = {}) => { - let invalidBlock = utils$h.isInvalidBrace(parent); - let invalidNode = node.invalid === true && options.escapeInvalid === true; - let invalid = invalidBlock === true || invalidNode === true; - let prefix = options.escapeInvalid === true ? '\\' : ''; - let output = ''; - - if (node.isOpen === true) { - return prefix + node.value; - } - if (node.isClose === true) { - return prefix + node.value; - } - - if (node.type === 'open') { - return invalid ? (prefix + node.value) : '('; - } - - if (node.type === 'close') { - return invalid ? (prefix + node.value) : ')'; - } - - if (node.type === 'comma') { - return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); - } - - if (node.value) { - return node.value; - } - - if (node.nodes && node.ranges > 0) { - let args = utils$h.reduce(node.nodes); - let range = fill$1(...args, { ...options, wrap: false, toRegex: true }); - - if (range.length !== 0) { - return args.length > 1 && range.length > 1 ? `(${range})` : range; - } - } - - if (node.nodes) { - for (let child of node.nodes) { - output += walk(child, node); - } - } - return output; - }; - - return walk(ast); -}; - -var compile_1 = compile$1; - -const fill = fillRange; -const stringify$5 = stringify$7; -const utils$g = utils$j; - -const append$1 = (queue = '', stash = '', enclose = false) => { - let result = []; - - queue = [].concat(queue); - stash = [].concat(stash); - - if (!stash.length) return queue; - if (!queue.length) { - return enclose ? utils$g.flatten(stash).map(ele => `{${ele}}`) : stash; - } - - for (let item of queue) { - if (Array.isArray(item)) { - for (let value of item) { - result.push(append$1(value, stash, enclose)); - } - } else { - for (let ele of stash) { - if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; - result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele)); - } - } - } - return utils$g.flatten(result); -}; - -const expand$3 = (ast, options = {}) => { - let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; - - let walk = (node, parent = {}) => { - node.queue = []; - - let p = parent; - let q = parent.queue; - - while (p.type !== 'brace' && p.type !== 'root' && p.parent) { - p = p.parent; - q = p.queue; - } - - if (node.invalid || node.dollar) { - q.push(append$1(q.pop(), stringify$5(node, options))); - return; - } - - if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { - q.push(append$1(q.pop(), ['{}'])); - return; - } - - if (node.nodes && node.ranges > 0) { - let args = utils$g.reduce(node.nodes); - - if (utils$g.exceedsLimit(...args, options.step, rangeLimit)) { - throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); - } - - let range = fill(...args, options); - if (range.length === 0) { - range = stringify$5(node, options); - } - - q.push(append$1(q.pop(), range)); - node.nodes = []; - return; - } - - let enclose = utils$g.encloseBrace(node); - let queue = node.queue; - let block = node; - - while (block.type !== 'brace' && block.type !== 'root' && block.parent) { - block = block.parent; - queue = block.queue; - } - - for (let i = 0; i < node.nodes.length; i++) { - let child = node.nodes[i]; - - if (child.type === 'comma' && node.type === 'brace') { - if (i === 1) queue.push(''); - queue.push(''); - continue; - } - - if (child.type === 'close') { - q.push(append$1(q.pop(), queue, enclose)); - continue; - } - - if (child.value && child.type !== 'open') { - queue.push(append$1(queue.pop(), child.value)); - continue; - } - - if (child.nodes) { - walk(child, node); - } - } - - return queue; - }; - - return utils$g.flatten(walk(ast)); -}; - -var expand_1 = expand$3; - -var constants$6 = { - MAX_LENGTH: 1024 * 64, - - // Digits - CHAR_0: '0', /* 0 */ - CHAR_9: '9', /* 9 */ - - // Alphabet chars. - CHAR_UPPERCASE_A: 'A', /* A */ - CHAR_LOWERCASE_A: 'a', /* a */ - CHAR_UPPERCASE_Z: 'Z', /* Z */ - CHAR_LOWERCASE_Z: 'z', /* z */ - - CHAR_LEFT_PARENTHESES: '(', /* ( */ - CHAR_RIGHT_PARENTHESES: ')', /* ) */ - - CHAR_ASTERISK: '*', /* * */ - - // Non-alphabetic chars. - CHAR_AMPERSAND: '&', /* & */ - CHAR_AT: '@', /* @ */ - CHAR_BACKSLASH: '\\', /* \ */ - CHAR_BACKTICK: '`', /* ` */ - CHAR_CARRIAGE_RETURN: '\r', /* \r */ - CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ - CHAR_COLON: ':', /* : */ - CHAR_COMMA: ',', /* , */ - CHAR_DOLLAR: '$', /* . */ - CHAR_DOT: '.', /* . */ - CHAR_DOUBLE_QUOTE: '"', /* " */ - CHAR_EQUAL: '=', /* = */ - CHAR_EXCLAMATION_MARK: '!', /* ! */ - CHAR_FORM_FEED: '\f', /* \f */ - CHAR_FORWARD_SLASH: '/', /* / */ - CHAR_HASH: '#', /* # */ - CHAR_HYPHEN_MINUS: '-', /* - */ - CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ - CHAR_LEFT_CURLY_BRACE: '{', /* { */ - CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ - CHAR_LINE_FEED: '\n', /* \n */ - CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ - CHAR_PERCENT: '%', /* % */ - CHAR_PLUS: '+', /* + */ - CHAR_QUESTION_MARK: '?', /* ? */ - CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ - CHAR_RIGHT_CURLY_BRACE: '}', /* } */ - CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ - CHAR_SEMICOLON: ';', /* ; */ - CHAR_SINGLE_QUOTE: '\'', /* ' */ - CHAR_SPACE: ' ', /* */ - CHAR_TAB: '\t', /* \t */ - CHAR_UNDERSCORE: '_', /* _ */ - CHAR_VERTICAL_LINE: '|', /* | */ - CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ -}; - -const stringify$4 = stringify$7; - -/** - * Constants - */ - -const { - MAX_LENGTH: MAX_LENGTH$1, - CHAR_BACKSLASH, /* \ */ - CHAR_BACKTICK, /* ` */ - CHAR_COMMA: CHAR_COMMA$1, /* , */ - CHAR_DOT: CHAR_DOT$1, /* . */ - CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ - CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ - CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ - CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ - CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ - CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */ - CHAR_DOUBLE_QUOTE, /* " */ - CHAR_SINGLE_QUOTE, /* ' */ - CHAR_NO_BREAK_SPACE, - CHAR_ZERO_WIDTH_NOBREAK_SPACE -} = constants$6; - -/** - * parse - */ - -const parse$l = (input, options = {}) => { - if (typeof input !== 'string') { - throw new TypeError('Expected a string'); - } - - let opts = options || {}; - let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; - if (input.length > max) { - throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); - } - - let ast = { type: 'root', input, nodes: [] }; - let stack = [ast]; - let block = ast; - let prev = ast; - let brackets = 0; - let length = input.length; - let index = 0; - let depth = 0; - let value; - - /** - * Helpers - */ - - const advance = () => input[index++]; - const push = node => { - if (node.type === 'text' && prev.type === 'dot') { - prev.type = 'text'; - } - - if (prev && prev.type === 'text' && node.type === 'text') { - prev.value += node.value; - return; - } - - block.nodes.push(node); - node.parent = block; - node.prev = prev; - prev = node; - return node; - }; - - push({ type: 'bos' }); - - while (index < length) { - block = stack[stack.length - 1]; - value = advance(); - - /** - * Invalid chars - */ - - if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { - continue; - } - - /** - * Escaped chars - */ - - if (value === CHAR_BACKSLASH) { - push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); - continue; - } - - /** - * Right square bracket (literal): ']' - */ - - if (value === CHAR_RIGHT_SQUARE_BRACKET$1) { - push({ type: 'text', value: '\\' + value }); - continue; - } - - /** - * Left square bracket: '[' - */ - - if (value === CHAR_LEFT_SQUARE_BRACKET$1) { - brackets++; - let next; - - while (index < length && (next = advance())) { - value += next; - - if (next === CHAR_LEFT_SQUARE_BRACKET$1) { - brackets++; - continue; - } - - if (next === CHAR_BACKSLASH) { - value += advance(); - continue; - } - - if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { - brackets--; - - if (brackets === 0) { - break; - } - } - } - - push({ type: 'text', value }); - continue; - } - - /** - * Parentheses - */ - - if (value === CHAR_LEFT_PARENTHESES$1) { - block = push({ type: 'paren', nodes: [] }); - stack.push(block); - push({ type: 'text', value }); - continue; - } - - if (value === CHAR_RIGHT_PARENTHESES$1) { - if (block.type !== 'paren') { - push({ type: 'text', value }); - continue; - } - block = stack.pop(); - push({ type: 'text', value }); - block = stack[stack.length - 1]; - continue; - } - - /** - * Quotes: '|"|` - */ - - if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { - let open = value; - let next; - - if (options.keepQuotes !== true) { - value = ''; - } - - while (index < length && (next = advance())) { - if (next === CHAR_BACKSLASH) { - value += next + advance(); - continue; - } - - if (next === open) { - if (options.keepQuotes === true) value += next; - break; - } - - value += next; - } - - push({ type: 'text', value }); - continue; - } - - /** - * Left curly brace: '{' - */ - - if (value === CHAR_LEFT_CURLY_BRACE$1) { - depth++; - - let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; - let brace = { - type: 'brace', - open: true, - close: false, - dollar, - depth, - commas: 0, - ranges: 0, - nodes: [] - }; - - block = push(brace); - stack.push(block); - push({ type: 'open', value }); - continue; - } - - /** - * Right curly brace: '}' - */ - - if (value === CHAR_RIGHT_CURLY_BRACE$1) { - if (block.type !== 'brace') { - push({ type: 'text', value }); - continue; - } - - let type = 'close'; - block = stack.pop(); - block.close = true; - - push({ type, value }); - depth--; - - block = stack[stack.length - 1]; - continue; - } - - /** - * Comma: ',' - */ - - if (value === CHAR_COMMA$1 && depth > 0) { - if (block.ranges > 0) { - block.ranges = 0; - let open = block.nodes.shift(); - block.nodes = [open, { type: 'text', value: stringify$4(block) }]; - } - - push({ type: 'comma', value }); - block.commas++; - continue; - } - - /** - * Dot: '.' - */ - - if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) { - let siblings = block.nodes; - - if (depth === 0 || siblings.length === 0) { - push({ type: 'text', value }); - continue; - } - - if (prev.type === 'dot') { - block.range = []; - prev.value += value; - prev.type = 'range'; - - if (block.nodes.length !== 3 && block.nodes.length !== 5) { - block.invalid = true; - block.ranges = 0; - prev.type = 'text'; - continue; - } - - block.ranges++; - block.args = []; - continue; - } - - if (prev.type === 'range') { - siblings.pop(); - - let before = siblings[siblings.length - 1]; - before.value += prev.value + value; - prev = before; - block.ranges--; - continue; - } - - push({ type: 'dot', value }); - continue; - } - - /** - * Text - */ - - push({ type: 'text', value }); - } - - // Mark imbalanced braces and brackets as invalid - do { - block = stack.pop(); - - if (block.type !== 'root') { - block.nodes.forEach(node => { - if (!node.nodes) { - if (node.type === 'open') node.isOpen = true; - if (node.type === 'close') node.isClose = true; - if (!node.nodes) node.type = 'text'; - node.invalid = true; - } - }); - - // get the location of the block on parent.nodes (block's siblings) - let parent = stack[stack.length - 1]; - let index = parent.nodes.indexOf(block); - // replace the (invalid) block with it's nodes - parent.nodes.splice(index, 1, ...block.nodes); - } - } while (stack.length > 0); - - push({ type: 'eos' }); - return ast; -}; - -var parse_1$2 = parse$l; - -const stringify$3 = stringify$7; -const compile = compile_1; -const expand$2 = expand_1; -const parse$k = parse_1$2; - -/** - * Expand the given pattern or create a regex-compatible string. - * - * ```js - * const braces = require('braces'); - * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] - * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {String} - * @api public - */ - -const braces$2 = (input, options = {}) => { - let output = []; - - if (Array.isArray(input)) { - for (let pattern of input) { - let result = braces$2.create(pattern, options); - if (Array.isArray(result)) { - output.push(...result); - } else { - output.push(result); - } - } - } else { - output = [].concat(braces$2.create(input, options)); - } - - if (options && options.expand === true && options.nodupes === true) { - output = [...new Set(output)]; - } - return output; -}; - -/** - * Parse the given `str` with the given `options`. - * - * ```js - * // braces.parse(pattern, [, options]); - * const ast = braces.parse('a/{b,c}/d'); - * console.log(ast); - * ``` - * @param {String} pattern Brace pattern to parse - * @param {Object} options - * @return {Object} Returns an AST - * @api public - */ - -braces$2.parse = (input, options = {}) => parse$k(input, options); - -/** - * Creates a braces string from an AST, or an AST node. - * - * ```js - * const braces = require('braces'); - * let ast = braces.parse('foo/{a,b}/bar'); - * console.log(stringify(ast.nodes[2])); //=> '{a,b}' - * ``` - * @param {String} `input` Brace pattern or AST. - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ - -braces$2.stringify = (input, options = {}) => { - if (typeof input === 'string') { - return stringify$3(braces$2.parse(input, options), options); - } - return stringify$3(input, options); -}; - -/** - * Compiles a brace pattern into a regex-compatible, optimized string. - * This method is called by the main [braces](#braces) function by default. - * - * ```js - * const braces = require('braces'); - * console.log(braces.compile('a/{b,c}/d')); - * //=> ['a/(b|c)/d'] - * ``` - * @param {String} `input` Brace pattern or AST. - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ - -braces$2.compile = (input, options = {}) => { - if (typeof input === 'string') { - input = braces$2.parse(input, options); - } - return compile(input, options); -}; - -/** - * Expands a brace pattern into an array. This method is called by the - * main [braces](#braces) function when `options.expand` is true. Before - * using this method it's recommended that you read the [performance notes](#performance)) - * and advantages of using [.compile](#compile) instead. - * - * ```js - * const braces = require('braces'); - * console.log(braces.expand('a/{b,c}/d')); - * //=> ['a/b/d', 'a/c/d']; - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ - -braces$2.expand = (input, options = {}) => { - if (typeof input === 'string') { - input = braces$2.parse(input, options); - } - - let result = expand$2(input, options); - - // filter out empty strings if specified - if (options.noempty === true) { - result = result.filter(Boolean); - } - - // filter out duplicates if specified - if (options.nodupes === true) { - result = [...new Set(result)]; - } - - return result; -}; - -/** - * Processes a brace pattern and returns either an expanded array - * (if `options.expand` is true), a highly optimized regex-compatible string. - * This method is called by the main [braces](#braces) function. - * - * ```js - * const braces = require('braces'); - * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) - * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ - -braces$2.create = (input, options = {}) => { - if (input === '' || input.length < 3) { - return [input]; - } - - return options.expand !== true - ? braces$2.compile(input, options) - : braces$2.expand(input, options); -}; - -/** - * Expose "braces" - */ - -var braces_1 = braces$2; - -var utils$f = {}; - -const path$q = path__default; -const WIN_SLASH = '\\\\/'; -const WIN_NO_SLASH = `[^${WIN_SLASH}]`; - -/** - * Posix glob regex - */ - -const DOT_LITERAL = '\\.'; -const PLUS_LITERAL = '\\+'; -const QMARK_LITERAL = '\\?'; -const SLASH_LITERAL = '\\/'; -const ONE_CHAR = '(?=.)'; -const QMARK = '[^/]'; -const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; -const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; -const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; -const NO_DOT = `(?!${DOT_LITERAL})`; -const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; -const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; -const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; -const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; -const STAR$1 = `${QMARK}*?`; - -const POSIX_CHARS = { - DOT_LITERAL, - PLUS_LITERAL, - QMARK_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - QMARK, - END_ANCHOR, - DOTS_SLASH, - NO_DOT, - NO_DOTS, - NO_DOT_SLASH, - NO_DOTS_SLASH, - QMARK_NO_DOT, - STAR: STAR$1, - START_ANCHOR -}; - -/** - * Windows glob regex - */ - -const WINDOWS_CHARS = { - ...POSIX_CHARS, - - SLASH_LITERAL: `[${WIN_SLASH}]`, - QMARK: WIN_NO_SLASH, - STAR: `${WIN_NO_SLASH}*?`, - DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, - NO_DOT: `(?!${DOT_LITERAL})`, - NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, - NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, - NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, - QMARK_NO_DOT: `[^.${WIN_SLASH}]`, - START_ANCHOR: `(?:^|[${WIN_SLASH}])`, - END_ANCHOR: `(?:[${WIN_SLASH}]|$)` -}; - -/** - * POSIX Bracket Regex - */ - -const POSIX_REGEX_SOURCE$1 = { - alnum: 'a-zA-Z0-9', - alpha: 'a-zA-Z', - ascii: '\\x00-\\x7F', - blank: ' \\t', - cntrl: '\\x00-\\x1F\\x7F', - digit: '0-9', - graph: '\\x21-\\x7E', - lower: 'a-z', - print: '\\x20-\\x7E ', - punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', - space: ' \\t\\r\\n\\v\\f', - upper: 'A-Z', - word: 'A-Za-z0-9_', - xdigit: 'A-Fa-f0-9' -}; - -var constants$5 = { - MAX_LENGTH: 1024 * 64, - POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, - - // regular expressions - REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, - REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, - REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, - REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, - REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, - REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, - - // Replace globs with equivalent patterns to reduce parsing time. - REPLACEMENTS: { - '***': '*', - '**/**': '**', - '**/**/**': '**' - }, - - // Digits - CHAR_0: 48, /* 0 */ - CHAR_9: 57, /* 9 */ - - // Alphabet chars. - CHAR_UPPERCASE_A: 65, /* A */ - CHAR_LOWERCASE_A: 97, /* a */ - CHAR_UPPERCASE_Z: 90, /* Z */ - CHAR_LOWERCASE_Z: 122, /* z */ - - CHAR_LEFT_PARENTHESES: 40, /* ( */ - CHAR_RIGHT_PARENTHESES: 41, /* ) */ - - CHAR_ASTERISK: 42, /* * */ - - // Non-alphabetic chars. - CHAR_AMPERSAND: 38, /* & */ - CHAR_AT: 64, /* @ */ - CHAR_BACKWARD_SLASH: 92, /* \ */ - CHAR_CARRIAGE_RETURN: 13, /* \r */ - CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ - CHAR_COLON: 58, /* : */ - CHAR_COMMA: 44, /* , */ - CHAR_DOT: 46, /* . */ - CHAR_DOUBLE_QUOTE: 34, /* " */ - CHAR_EQUAL: 61, /* = */ - CHAR_EXCLAMATION_MARK: 33, /* ! */ - CHAR_FORM_FEED: 12, /* \f */ - CHAR_FORWARD_SLASH: 47, /* / */ - CHAR_GRAVE_ACCENT: 96, /* ` */ - CHAR_HASH: 35, /* # */ - CHAR_HYPHEN_MINUS: 45, /* - */ - CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ - CHAR_LEFT_CURLY_BRACE: 123, /* { */ - CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ - CHAR_LINE_FEED: 10, /* \n */ - CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ - CHAR_PERCENT: 37, /* % */ - CHAR_PLUS: 43, /* + */ - CHAR_QUESTION_MARK: 63, /* ? */ - CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ - CHAR_RIGHT_CURLY_BRACE: 125, /* } */ - CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ - CHAR_SEMICOLON: 59, /* ; */ - CHAR_SINGLE_QUOTE: 39, /* ' */ - CHAR_SPACE: 32, /* */ - CHAR_TAB: 9, /* \t */ - CHAR_UNDERSCORE: 95, /* _ */ - CHAR_VERTICAL_LINE: 124, /* | */ - CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ - - SEP: path$q.sep, - - /** - * Create EXTGLOB_CHARS - */ - - extglobChars(chars) { - return { - '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, - '?': { type: 'qmark', open: '(?:', close: ')?' }, - '+': { type: 'plus', open: '(?:', close: ')+' }, - '*': { type: 'star', open: '(?:', close: ')*' }, - '@': { type: 'at', open: '(?:', close: ')' } - }; - }, - - /** - * Create GLOB_CHARS - */ - - globChars(win32) { - return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; - } -}; - -(function (exports) { - -const path = path__default; -const win32 = process.platform === 'win32'; -const { - REGEX_BACKSLASH, - REGEX_REMOVE_BACKSLASH, - REGEX_SPECIAL_CHARS, - REGEX_SPECIAL_CHARS_GLOBAL -} = constants$5; - -exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); -exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); -exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); -exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); -exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); - -exports.removeBackslashes = str => { - return str.replace(REGEX_REMOVE_BACKSLASH, match => { - return match === '\\' ? '' : match; - }); -}; - -exports.supportsLookbehinds = () => { - const segs = process.version.slice(1).split('.').map(Number); - if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { - return true; - } - return false; -}; - -exports.isWindows = options => { - if (options && typeof options.windows === 'boolean') { - return options.windows; - } - return win32 === true || path.sep === '\\'; -}; - -exports.escapeLast = (input, char, lastIdx) => { - const idx = input.lastIndexOf(char, lastIdx); - if (idx === -1) return input; - if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); - return `${input.slice(0, idx)}\\${input.slice(idx)}`; -}; - -exports.removePrefix = (input, state = {}) => { - let output = input; - if (output.startsWith('./')) { - output = output.slice(2); - state.prefix = './'; - } - return output; -}; - -exports.wrapOutput = (input, state = {}, options = {}) => { - const prepend = options.contains ? '' : '^'; - const append = options.contains ? '' : '$'; - - let output = `${prepend}(?:${input})${append}`; - if (state.negated === true) { - output = `(?:^(?!${output}).*$)`; - } - return output; -}; -}(utils$f)); - -const utils$e = utils$f; -const { - CHAR_ASTERISK, /* * */ - CHAR_AT, /* @ */ - CHAR_BACKWARD_SLASH, /* \ */ - CHAR_COMMA, /* , */ - CHAR_DOT, /* . */ - CHAR_EXCLAMATION_MARK, /* ! */ - CHAR_FORWARD_SLASH, /* / */ - CHAR_LEFT_CURLY_BRACE, /* { */ - CHAR_LEFT_PARENTHESES, /* ( */ - CHAR_LEFT_SQUARE_BRACKET, /* [ */ - CHAR_PLUS, /* + */ - CHAR_QUESTION_MARK, /* ? */ - CHAR_RIGHT_CURLY_BRACE, /* } */ - CHAR_RIGHT_PARENTHESES, /* ) */ - CHAR_RIGHT_SQUARE_BRACKET /* ] */ -} = constants$5; - -const isPathSeparator = code => { - return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; -}; - -const depth = token => { - if (token.isPrefix !== true) { - token.depth = token.isGlobstar ? Infinity : 1; - } -}; - -/** - * Quickly scans a glob pattern and returns an object with a handful of - * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), - * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not - * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). - * - * ```js - * const pm = require('picomatch'); - * console.log(pm.scan('foo/bar/*.js')); - * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {Object} Returns an object with tokens and regex source string. - * @api public - */ - -const scan$1 = (input, options) => { - const opts = options || {}; - - const length = input.length - 1; - const scanToEnd = opts.parts === true || opts.scanToEnd === true; - const slashes = []; - const tokens = []; - const parts = []; - - let str = input; - let index = -1; - let start = 0; - let lastIndex = 0; - let isBrace = false; - let isBracket = false; - let isGlob = false; - let isExtglob = false; - let isGlobstar = false; - let braceEscaped = false; - let backslashes = false; - let negated = false; - let negatedExtglob = false; - let finished = false; - let braces = 0; - let prev; - let code; - let token = { value: '', depth: 0, isGlob: false }; - - const eos = () => index >= length; - const peek = () => str.charCodeAt(index + 1); - const advance = () => { - prev = code; - return str.charCodeAt(++index); - }; - - while (index < length) { - code = advance(); - let next; - - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - code = advance(); - - if (code === CHAR_LEFT_CURLY_BRACE) { - braceEscaped = true; - } - continue; - } - - if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { - braces++; - - while (eos() !== true && (code = advance())) { - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - advance(); - continue; - } - - if (code === CHAR_LEFT_CURLY_BRACE) { - braces++; - continue; - } - - if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { - isBrace = token.isBrace = true; - isGlob = token.isGlob = true; - finished = true; - - if (scanToEnd === true) { - continue; - } - - break; - } - - if (braceEscaped !== true && code === CHAR_COMMA) { - isBrace = token.isBrace = true; - isGlob = token.isGlob = true; - finished = true; - - if (scanToEnd === true) { - continue; - } - - break; - } - - if (code === CHAR_RIGHT_CURLY_BRACE) { - braces--; - - if (braces === 0) { - braceEscaped = false; - isBrace = token.isBrace = true; - finished = true; - break; - } - } - } - - if (scanToEnd === true) { - continue; - } - - break; - } - - if (code === CHAR_FORWARD_SLASH) { - slashes.push(index); - tokens.push(token); - token = { value: '', depth: 0, isGlob: false }; - - if (finished === true) continue; - if (prev === CHAR_DOT && index === (start + 1)) { - start += 2; - continue; - } - - lastIndex = index + 1; - continue; - } - - if (opts.noext !== true) { - const isExtglobChar = code === CHAR_PLUS - || code === CHAR_AT - || code === CHAR_ASTERISK - || code === CHAR_QUESTION_MARK - || code === CHAR_EXCLAMATION_MARK; - - if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { - isGlob = token.isGlob = true; - isExtglob = token.isExtglob = true; - finished = true; - if (code === CHAR_EXCLAMATION_MARK && index === start) { - negatedExtglob = true; - } - - if (scanToEnd === true) { - while (eos() !== true && (code = advance())) { - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - code = advance(); - continue; - } - - if (code === CHAR_RIGHT_PARENTHESES) { - isGlob = token.isGlob = true; - finished = true; - break; - } - } - continue; - } - break; - } - } - - if (code === CHAR_ASTERISK) { - if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; - isGlob = token.isGlob = true; - finished = true; - - if (scanToEnd === true) { - continue; - } - break; - } - - if (code === CHAR_QUESTION_MARK) { - isGlob = token.isGlob = true; - finished = true; - - if (scanToEnd === true) { - continue; - } - break; - } - - if (code === CHAR_LEFT_SQUARE_BRACKET) { - while (eos() !== true && (next = advance())) { - if (next === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - advance(); - continue; - } - - if (next === CHAR_RIGHT_SQUARE_BRACKET) { - isBracket = token.isBracket = true; - isGlob = token.isGlob = true; - finished = true; - break; - } - } - - if (scanToEnd === true) { - continue; - } - - break; - } - - if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { - negated = token.negated = true; - start++; - continue; - } - - if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { - isGlob = token.isGlob = true; - - if (scanToEnd === true) { - while (eos() !== true && (code = advance())) { - if (code === CHAR_LEFT_PARENTHESES) { - backslashes = token.backslashes = true; - code = advance(); - continue; - } - - if (code === CHAR_RIGHT_PARENTHESES) { - finished = true; - break; - } - } - continue; - } - break; - } - - if (isGlob === true) { - finished = true; - - if (scanToEnd === true) { - continue; - } - - break; - } - } - - if (opts.noext === true) { - isExtglob = false; - isGlob = false; - } - - let base = str; - let prefix = ''; - let glob = ''; - - if (start > 0) { - prefix = str.slice(0, start); - str = str.slice(start); - lastIndex -= start; - } - - if (base && isGlob === true && lastIndex > 0) { - base = str.slice(0, lastIndex); - glob = str.slice(lastIndex); - } else if (isGlob === true) { - base = ''; - glob = str; - } else { - base = str; - } - - if (base && base !== '' && base !== '/' && base !== str) { - if (isPathSeparator(base.charCodeAt(base.length - 1))) { - base = base.slice(0, -1); - } - } - - if (opts.unescape === true) { - if (glob) glob = utils$e.removeBackslashes(glob); - - if (base && backslashes === true) { - base = utils$e.removeBackslashes(base); - } - } - - const state = { - prefix, - input, - start, - base, - glob, - isBrace, - isBracket, - isGlob, - isExtglob, - isGlobstar, - negated, - negatedExtglob - }; - - if (opts.tokens === true) { - state.maxDepth = 0; - if (!isPathSeparator(code)) { - tokens.push(token); - } - state.tokens = tokens; - } - - if (opts.parts === true || opts.tokens === true) { - let prevIndex; - - for (let idx = 0; idx < slashes.length; idx++) { - const n = prevIndex ? prevIndex + 1 : start; - const i = slashes[idx]; - const value = input.slice(n, i); - if (opts.tokens) { - if (idx === 0 && start !== 0) { - tokens[idx].isPrefix = true; - tokens[idx].value = prefix; - } else { - tokens[idx].value = value; - } - depth(tokens[idx]); - state.maxDepth += tokens[idx].depth; - } - if (idx !== 0 || value !== '') { - parts.push(value); - } - prevIndex = i; - } - - if (prevIndex && prevIndex + 1 < input.length) { - const value = input.slice(prevIndex + 1); - parts.push(value); - - if (opts.tokens) { - tokens[tokens.length - 1].value = value; - depth(tokens[tokens.length - 1]); - state.maxDepth += tokens[tokens.length - 1].depth; - } - } - - state.slashes = slashes; - state.parts = parts; - } - - return state; -}; - -var scan_1 = scan$1; - -const constants$4 = constants$5; -const utils$d = utils$f; - -/** - * Constants - */ - -const { - MAX_LENGTH, - POSIX_REGEX_SOURCE, - REGEX_NON_SPECIAL_CHARS, - REGEX_SPECIAL_CHARS_BACKREF, - REPLACEMENTS -} = constants$4; - -/** - * Helpers - */ - -const expandRange = (args, options) => { - if (typeof options.expandRange === 'function') { - return options.expandRange(...args, options); - } - - args.sort(); - const value = `[${args.join('-')}]`; - - return value; -}; - -/** - * Create the message for a syntax error - */ - -const syntaxError = (type, char) => { - return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; -}; - -/** - * Parse the given input string. - * @param {String} input - * @param {Object} options - * @return {Object} - */ - -const parse$j = (input, options) => { - if (typeof input !== 'string') { - throw new TypeError('Expected a string'); - } - - input = REPLACEMENTS[input] || input; - - const opts = { ...options }; - const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - - let len = input.length; - if (len > max) { - throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); - } - - const bos = { type: 'bos', value: '', output: opts.prepend || '' }; - const tokens = [bos]; - - const capture = opts.capture ? '' : '?:'; - const win32 = utils$d.isWindows(options); - - // create constants based on platform, for windows or posix - const PLATFORM_CHARS = constants$4.globChars(win32); - const EXTGLOB_CHARS = constants$4.extglobChars(PLATFORM_CHARS); - - const { - DOT_LITERAL, - PLUS_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - DOTS_SLASH, - NO_DOT, - NO_DOT_SLASH, - NO_DOTS_SLASH, - QMARK, - QMARK_NO_DOT, - STAR, - START_ANCHOR - } = PLATFORM_CHARS; - - const globstar = opts => { - return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; - }; - - const nodot = opts.dot ? '' : NO_DOT; - const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; - let star = opts.bash === true ? globstar(opts) : STAR; - - if (opts.capture) { - star = `(${star})`; - } - - // minimatch options support - if (typeof opts.noext === 'boolean') { - opts.noextglob = opts.noext; - } - - const state = { - input, - index: -1, - start: 0, - dot: opts.dot === true, - consumed: '', - output: '', - prefix: '', - backtrack: false, - negated: false, - brackets: 0, - braces: 0, - parens: 0, - quotes: 0, - globstar: false, - tokens - }; - - input = utils$d.removePrefix(input, state); - len = input.length; - - const extglobs = []; - const braces = []; - const stack = []; - let prev = bos; - let value; - - /** - * Tokenizing helpers - */ - - const eos = () => state.index === len - 1; - const peek = state.peek = (n = 1) => input[state.index + n]; - const advance = state.advance = () => input[++state.index] || ''; - const remaining = () => input.slice(state.index + 1); - const consume = (value = '', num = 0) => { - state.consumed += value; - state.index += num; - }; - - const append = token => { - state.output += token.output != null ? token.output : token.value; - consume(token.value); - }; - - const negate = () => { - let count = 1; - - while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { - advance(); - state.start++; - count++; - } - - if (count % 2 === 0) { - return false; - } - - state.negated = true; - state.start++; - return true; - }; - - const increment = type => { - state[type]++; - stack.push(type); - }; - - const decrement = type => { - state[type]--; - stack.pop(); - }; - - /** - * Push tokens onto the tokens array. This helper speeds up - * tokenizing by 1) helping us avoid backtracking as much as possible, - * and 2) helping us avoid creating extra tokens when consecutive - * characters are plain text. This improves performance and simplifies - * lookbehinds. - */ - - const push = tok => { - if (prev.type === 'globstar') { - const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); - const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); - - if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { - state.output = state.output.slice(0, -prev.output.length); - prev.type = 'star'; - prev.value = '*'; - prev.output = star; - state.output += prev.output; - } - } - - if (extglobs.length && tok.type !== 'paren') { - extglobs[extglobs.length - 1].inner += tok.value; - } - - if (tok.value || tok.output) append(tok); - if (prev && prev.type === 'text' && tok.type === 'text') { - prev.value += tok.value; - prev.output = (prev.output || '') + tok.value; - return; - } - - tok.prev = prev; - tokens.push(tok); - prev = tok; - }; - - const extglobOpen = (type, value) => { - const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; - - token.prev = prev; - token.parens = state.parens; - token.output = state.output; - const output = (opts.capture ? '(' : '') + token.open; - - increment('parens'); - push({ type, value, output: state.output ? '' : ONE_CHAR }); - push({ type: 'paren', extglob: true, value: advance(), output }); - extglobs.push(token); - }; - - const extglobClose = token => { - let output = token.close + (opts.capture ? ')' : ''); - let rest; - - if (token.type === 'negate') { - let extglobStar = star; - - if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { - extglobStar = globstar(opts); - } - - if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { - output = token.close = `)$))${extglobStar}`; - } - - if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { - output = token.close = `)${rest})${extglobStar})`; - } - - if (token.prev.type === 'bos') { - state.negatedExtglob = true; - } - } - - push({ type: 'paren', extglob: true, value, output }); - decrement('parens'); - }; - - /** - * Fast paths - */ - - if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { - let backslashes = false; - - let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { - if (first === '\\') { - backslashes = true; - return m; - } - - if (first === '?') { - if (esc) { - return esc + first + (rest ? QMARK.repeat(rest.length) : ''); - } - if (index === 0) { - return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); - } - return QMARK.repeat(chars.length); - } - - if (first === '.') { - return DOT_LITERAL.repeat(chars.length); - } - - if (first === '*') { - if (esc) { - return esc + first + (rest ? star : ''); - } - return star; - } - return esc ? m : `\\${m}`; - }); - - if (backslashes === true) { - if (opts.unescape === true) { - output = output.replace(/\\/g, ''); - } else { - output = output.replace(/\\+/g, m => { - return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); - }); - } - } - - if (output === input && opts.contains === true) { - state.output = input; - return state; - } - - state.output = utils$d.wrapOutput(output, state, options); - return state; - } - - /** - * Tokenize input until we reach end-of-string - */ - - while (!eos()) { - value = advance(); - - if (value === '\u0000') { - continue; - } - - /** - * Escaped characters - */ - - if (value === '\\') { - const next = peek(); - - if (next === '/' && opts.bash !== true) { - continue; - } - - if (next === '.' || next === ';') { - continue; - } - - if (!next) { - value += '\\'; - push({ type: 'text', value }); - continue; - } - - // collapse slashes to reduce potential for exploits - const match = /^\\+/.exec(remaining()); - let slashes = 0; - - if (match && match[0].length > 2) { - slashes = match[0].length; - state.index += slashes; - if (slashes % 2 !== 0) { - value += '\\'; - } - } - - if (opts.unescape === true) { - value = advance(); - } else { - value += advance(); - } - - if (state.brackets === 0) { - push({ type: 'text', value }); - continue; - } - } - - /** - * If we're inside a regex character class, continue - * until we reach the closing bracket. - */ - - if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { - if (opts.posix !== false && value === ':') { - const inner = prev.value.slice(1); - if (inner.includes('[')) { - prev.posix = true; - - if (inner.includes(':')) { - const idx = prev.value.lastIndexOf('['); - const pre = prev.value.slice(0, idx); - const rest = prev.value.slice(idx + 2); - const posix = POSIX_REGEX_SOURCE[rest]; - if (posix) { - prev.value = pre + posix; - state.backtrack = true; - advance(); - - if (!bos.output && tokens.indexOf(prev) === 1) { - bos.output = ONE_CHAR; - } - continue; - } - } - } - } - - if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { - value = `\\${value}`; - } - - if (value === ']' && (prev.value === '[' || prev.value === '[^')) { - value = `\\${value}`; - } - - if (opts.posix === true && value === '!' && prev.value === '[') { - value = '^'; - } - - prev.value += value; - append({ value }); - continue; - } - - /** - * If we're inside a quoted string, continue - * until we reach the closing double quote. - */ - - if (state.quotes === 1 && value !== '"') { - value = utils$d.escapeRegex(value); - prev.value += value; - append({ value }); - continue; - } - - /** - * Double quotes - */ - - if (value === '"') { - state.quotes = state.quotes === 1 ? 0 : 1; - if (opts.keepQuotes === true) { - push({ type: 'text', value }); - } - continue; - } - - /** - * Parentheses - */ - - if (value === '(') { - increment('parens'); - push({ type: 'paren', value }); - continue; - } - - if (value === ')') { - if (state.parens === 0 && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('opening', '(')); - } - - const extglob = extglobs[extglobs.length - 1]; - if (extglob && state.parens === extglob.parens + 1) { - extglobClose(extglobs.pop()); - continue; - } - - push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); - decrement('parens'); - continue; - } - - /** - * Square brackets - */ - - if (value === '[') { - if (opts.nobracket === true || !remaining().includes(']')) { - if (opts.nobracket !== true && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('closing', ']')); - } - - value = `\\${value}`; - } else { - increment('brackets'); - } - - push({ type: 'bracket', value }); - continue; - } - - if (value === ']') { - if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { - push({ type: 'text', value, output: `\\${value}` }); - continue; - } - - if (state.brackets === 0) { - if (opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('opening', '[')); - } - - push({ type: 'text', value, output: `\\${value}` }); - continue; - } - - decrement('brackets'); - - const prevValue = prev.value.slice(1); - if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { - value = `/${value}`; - } - - prev.value += value; - append({ value }); - - // when literal brackets are explicitly disabled - // assume we should match with a regex character class - if (opts.literalBrackets === false || utils$d.hasRegexChars(prevValue)) { - continue; - } - - const escaped = utils$d.escapeRegex(prev.value); - state.output = state.output.slice(0, -prev.value.length); - - // when literal brackets are explicitly enabled - // assume we should escape the brackets to match literal characters - if (opts.literalBrackets === true) { - state.output += escaped; - prev.value = escaped; - continue; - } - - // when the user specifies nothing, try to match both - prev.value = `(${capture}${escaped}|${prev.value})`; - state.output += prev.value; - continue; - } - - /** - * Braces - */ - - if (value === '{' && opts.nobrace !== true) { - increment('braces'); - - const open = { - type: 'brace', - value, - output: '(', - outputIndex: state.output.length, - tokensIndex: state.tokens.length - }; - - braces.push(open); - push(open); - continue; - } - - if (value === '}') { - const brace = braces[braces.length - 1]; - - if (opts.nobrace === true || !brace) { - push({ type: 'text', value, output: value }); - continue; - } - - let output = ')'; - - if (brace.dots === true) { - const arr = tokens.slice(); - const range = []; - - for (let i = arr.length - 1; i >= 0; i--) { - tokens.pop(); - if (arr[i].type === 'brace') { - break; - } - if (arr[i].type !== 'dots') { - range.unshift(arr[i].value); - } - } - - output = expandRange(range, opts); - state.backtrack = true; - } - - if (brace.comma !== true && brace.dots !== true) { - const out = state.output.slice(0, brace.outputIndex); - const toks = state.tokens.slice(brace.tokensIndex); - brace.value = brace.output = '\\{'; - value = output = '\\}'; - state.output = out; - for (const t of toks) { - state.output += (t.output || t.value); - } - } - - push({ type: 'brace', value, output }); - decrement('braces'); - braces.pop(); - continue; - } - - /** - * Pipes - */ - - if (value === '|') { - if (extglobs.length > 0) { - extglobs[extglobs.length - 1].conditions++; - } - push({ type: 'text', value }); - continue; - } - - /** - * Commas - */ - - if (value === ',') { - let output = value; - - const brace = braces[braces.length - 1]; - if (brace && stack[stack.length - 1] === 'braces') { - brace.comma = true; - output = '|'; - } - - push({ type: 'comma', value, output }); - continue; - } - - /** - * Slashes - */ - - if (value === '/') { - // if the beginning of the glob is "./", advance the start - // to the current index, and don't add the "./" characters - // to the state. This greatly simplifies lookbehinds when - // checking for BOS characters like "!" and "." (not "./") - if (prev.type === 'dot' && state.index === state.start + 1) { - state.start = state.index + 1; - state.consumed = ''; - state.output = ''; - tokens.pop(); - prev = bos; // reset "prev" to the first token - continue; - } - - push({ type: 'slash', value, output: SLASH_LITERAL }); - continue; - } - - /** - * Dots - */ - - if (value === '.') { - if (state.braces > 0 && prev.type === 'dot') { - if (prev.value === '.') prev.output = DOT_LITERAL; - const brace = braces[braces.length - 1]; - prev.type = 'dots'; - prev.output += value; - prev.value += value; - brace.dots = true; - continue; - } - - if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { - push({ type: 'text', value, output: DOT_LITERAL }); - continue; - } - - push({ type: 'dot', value, output: DOT_LITERAL }); - continue; - } - - /** - * Question marks - */ - - if (value === '?') { - const isGroup = prev && prev.value === '('; - if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - extglobOpen('qmark', value); - continue; - } - - if (prev && prev.type === 'paren') { - const next = peek(); - let output = value; - - if (next === '<' && !utils$d.supportsLookbehinds()) { - throw new Error('Node.js v10 or higher is required for regex lookbehinds'); - } - - if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { - output = `\\${value}`; - } - - push({ type: 'text', value, output }); - continue; - } - - if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { - push({ type: 'qmark', value, output: QMARK_NO_DOT }); - continue; - } - - push({ type: 'qmark', value, output: QMARK }); - continue; - } - - /** - * Exclamation - */ - - if (value === '!') { - if (opts.noextglob !== true && peek() === '(') { - if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { - extglobOpen('negate', value); - continue; - } - } - - if (opts.nonegate !== true && state.index === 0) { - negate(); - continue; - } - } - - /** - * Plus - */ - - if (value === '+') { - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - extglobOpen('plus', value); - continue; - } - - if ((prev && prev.value === '(') || opts.regex === false) { - push({ type: 'plus', value, output: PLUS_LITERAL }); - continue; - } - - if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { - push({ type: 'plus', value }); - continue; - } - - push({ type: 'plus', value: PLUS_LITERAL }); - continue; - } - - /** - * Plain text - */ - - if (value === '@') { - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - push({ type: 'at', extglob: true, value, output: '' }); - continue; - } - - push({ type: 'text', value }); - continue; - } - - /** - * Plain text - */ - - if (value !== '*') { - if (value === '$' || value === '^') { - value = `\\${value}`; - } - - const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); - if (match) { - value += match[0]; - state.index += match[0].length; - } - - push({ type: 'text', value }); - continue; - } - - /** - * Stars - */ - - if (prev && (prev.type === 'globstar' || prev.star === true)) { - prev.type = 'star'; - prev.star = true; - prev.value += value; - prev.output = star; - state.backtrack = true; - state.globstar = true; - consume(value); - continue; - } - - let rest = remaining(); - if (opts.noextglob !== true && /^\([^?]/.test(rest)) { - extglobOpen('star', value); - continue; - } - - if (prev.type === 'star') { - if (opts.noglobstar === true) { - consume(value); - continue; - } - - const prior = prev.prev; - const before = prior.prev; - const isStart = prior.type === 'slash' || prior.type === 'bos'; - const afterStar = before && (before.type === 'star' || before.type === 'globstar'); - - if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { - push({ type: 'star', value, output: '' }); - continue; - } - - const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); - const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); - if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { - push({ type: 'star', value, output: '' }); - continue; - } - - // strip consecutive `/**/` - while (rest.slice(0, 3) === '/**') { - const after = input[state.index + 4]; - if (after && after !== '/') { - break; - } - rest = rest.slice(3); - consume('/**', 3); - } - - if (prior.type === 'bos' && eos()) { - prev.type = 'globstar'; - prev.value += value; - prev.output = globstar(opts); - state.output = prev.output; - state.globstar = true; - consume(value); - continue; - } - - if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = `(?:${prior.output}`; - - prev.type = 'globstar'; - prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); - prev.value += value; - state.globstar = true; - state.output += prior.output + prev.output; - consume(value); - continue; - } - - if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { - const end = rest[1] !== void 0 ? '|$' : ''; - - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = `(?:${prior.output}`; - - prev.type = 'globstar'; - prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; - prev.value += value; - - state.output += prior.output + prev.output; - state.globstar = true; - - consume(value + advance()); - - push({ type: 'slash', value: '/', output: '' }); - continue; - } - - if (prior.type === 'bos' && rest[0] === '/') { - prev.type = 'globstar'; - prev.value += value; - prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; - state.output = prev.output; - state.globstar = true; - consume(value + advance()); - push({ type: 'slash', value: '/', output: '' }); - continue; - } - - // remove single star from output - state.output = state.output.slice(0, -prev.output.length); - - // reset previous token to globstar - prev.type = 'globstar'; - prev.output = globstar(opts); - prev.value += value; - - // reset output with globstar - state.output += prev.output; - state.globstar = true; - consume(value); - continue; - } - - const token = { type: 'star', value, output: star }; - - if (opts.bash === true) { - token.output = '.*?'; - if (prev.type === 'bos' || prev.type === 'slash') { - token.output = nodot + token.output; - } - push(token); - continue; - } - - if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { - token.output = value; - push(token); - continue; - } - - if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { - if (prev.type === 'dot') { - state.output += NO_DOT_SLASH; - prev.output += NO_DOT_SLASH; - - } else if (opts.dot === true) { - state.output += NO_DOTS_SLASH; - prev.output += NO_DOTS_SLASH; - - } else { - state.output += nodot; - prev.output += nodot; - } - - if (peek() !== '*') { - state.output += ONE_CHAR; - prev.output += ONE_CHAR; - } - } - - push(token); - } - - while (state.brackets > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); - state.output = utils$d.escapeLast(state.output, '['); - decrement('brackets'); - } - - while (state.parens > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); - state.output = utils$d.escapeLast(state.output, '('); - decrement('parens'); - } - - while (state.braces > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); - state.output = utils$d.escapeLast(state.output, '{'); - decrement('braces'); - } - - if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { - push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); - } - - // rebuild the output if we had to backtrack at any point - if (state.backtrack === true) { - state.output = ''; - - for (const token of state.tokens) { - state.output += token.output != null ? token.output : token.value; - - if (token.suffix) { - state.output += token.suffix; - } - } - } - - return state; -}; - -/** - * Fast paths for creating regular expressions for common glob patterns. - * This can significantly speed up processing and has very little downside - * impact when none of the fast paths match. - */ - -parse$j.fastpaths = (input, options) => { - const opts = { ...options }; - const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - const len = input.length; - if (len > max) { - throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); - } - - input = REPLACEMENTS[input] || input; - const win32 = utils$d.isWindows(options); - - // create constants based on platform, for windows or posix - const { - DOT_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - DOTS_SLASH, - NO_DOT, - NO_DOTS, - NO_DOTS_SLASH, - STAR, - START_ANCHOR - } = constants$4.globChars(win32); - - const nodot = opts.dot ? NO_DOTS : NO_DOT; - const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; - const capture = opts.capture ? '' : '?:'; - const state = { negated: false, prefix: '' }; - let star = opts.bash === true ? '.*?' : STAR; - - if (opts.capture) { - star = `(${star})`; - } - - const globstar = opts => { - if (opts.noglobstar === true) return star; - return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; - }; - - const create = str => { - switch (str) { - case '*': - return `${nodot}${ONE_CHAR}${star}`; - - case '.*': - return `${DOT_LITERAL}${ONE_CHAR}${star}`; - - case '*.*': - return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - - case '*/*': - return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; - - case '**': - return nodot + globstar(opts); - - case '**/*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; - - case '**/*.*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - - case '**/.*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; - - default: { - const match = /^(.*?)\.(\w+)$/.exec(str); - if (!match) return; - - const source = create(match[1]); - if (!source) return; - - return source + DOT_LITERAL + match[2]; - } - } - }; - - const output = utils$d.removePrefix(input, state); - let source = create(output); - - if (source && opts.strictSlashes !== true) { - source += `${SLASH_LITERAL}?`; - } - - return source; -}; - -var parse_1$1 = parse$j; - -const path$p = path__default; -const scan = scan_1; -const parse$i = parse_1$1; -const utils$c = utils$f; -const constants$3 = constants$5; -const isObject = val => val && typeof val === 'object' && !Array.isArray(val); - -/** - * Creates a matcher function from one or more glob patterns. The - * returned function takes a string to match as its first argument, - * and returns true if the string is a match. The returned matcher - * function also takes a boolean as the second argument that, when true, - * returns an object with additional information. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch(glob[, options]); - * - * const isMatch = picomatch('*.!(*a)'); - * console.log(isMatch('a.a')); //=> false - * console.log(isMatch('a.b')); //=> true - * ``` - * @name picomatch - * @param {String|Array} `globs` One or more glob patterns. - * @param {Object=} `options` - * @return {Function=} Returns a matcher function. - * @api public - */ - -const picomatch$4 = (glob, options, returnState = false) => { - if (Array.isArray(glob)) { - const fns = glob.map(input => picomatch$4(input, options, returnState)); - const arrayMatcher = str => { - for (const isMatch of fns) { - const state = isMatch(str); - if (state) return state; - } - return false; - }; - return arrayMatcher; - } - - const isState = isObject(glob) && glob.tokens && glob.input; - - if (glob === '' || (typeof glob !== 'string' && !isState)) { - throw new TypeError('Expected pattern to be a non-empty string'); - } - - const opts = options || {}; - const posix = utils$c.isWindows(options); - const regex = isState - ? picomatch$4.compileRe(glob, options) - : picomatch$4.makeRe(glob, options, false, true); - - const state = regex.state; - delete regex.state; - - let isIgnored = () => false; - if (opts.ignore) { - const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; - isIgnored = picomatch$4(opts.ignore, ignoreOpts, returnState); - } - - const matcher = (input, returnObject = false) => { - const { isMatch, match, output } = picomatch$4.test(input, regex, options, { glob, posix }); - const result = { glob, state, regex, posix, input, output, match, isMatch }; - - if (typeof opts.onResult === 'function') { - opts.onResult(result); - } - - if (isMatch === false) { - result.isMatch = false; - return returnObject ? result : false; - } - - if (isIgnored(input)) { - if (typeof opts.onIgnore === 'function') { - opts.onIgnore(result); - } - result.isMatch = false; - return returnObject ? result : false; - } - - if (typeof opts.onMatch === 'function') { - opts.onMatch(result); - } - return returnObject ? result : true; - }; - - if (returnState) { - matcher.state = state; - } - - return matcher; -}; - -/** - * Test `input` with the given `regex`. This is used by the main - * `picomatch()` function to test the input string. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.test(input, regex[, options]); - * - * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); - * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } - * ``` - * @param {String} `input` String to test. - * @param {RegExp} `regex` - * @return {Object} Returns an object with matching info. - * @api public - */ - -picomatch$4.test = (input, regex, options, { glob, posix } = {}) => { - if (typeof input !== 'string') { - throw new TypeError('Expected input to be a string'); - } - - if (input === '') { - return { isMatch: false, output: '' }; - } - - const opts = options || {}; - const format = opts.format || (posix ? utils$c.toPosixSlashes : null); - let match = input === glob; - let output = (match && format) ? format(input) : input; - - if (match === false) { - output = format ? format(input) : input; - match = output === glob; - } - - if (match === false || opts.capture === true) { - if (opts.matchBase === true || opts.basename === true) { - match = picomatch$4.matchBase(input, regex, options, posix); - } else { - match = regex.exec(output); - } - } - - return { isMatch: Boolean(match), match, output }; -}; - -/** - * Match the basename of a filepath. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.matchBase(input, glob[, options]); - * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true - * ``` - * @param {String} `input` String to test. - * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). - * @return {Boolean} - * @api public - */ - -picomatch$4.matchBase = (input, glob, options, posix = utils$c.isWindows(options)) => { - const regex = glob instanceof RegExp ? glob : picomatch$4.makeRe(glob, options); - return regex.test(path$p.basename(input)); -}; - -/** - * Returns true if **any** of the given glob `patterns` match the specified `string`. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.isMatch(string, patterns[, options]); - * - * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true - * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false - * ``` - * @param {String|Array} str The string to test. - * @param {String|Array} patterns One or more glob patterns to use for matching. - * @param {Object} [options] See available [options](#options). - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ - -picomatch$4.isMatch = (str, patterns, options) => picomatch$4(patterns, options)(str); - -/** - * Parse a glob pattern to create the source string for a regular - * expression. - * - * ```js - * const picomatch = require('picomatch'); - * const result = picomatch.parse(pattern[, options]); - * ``` - * @param {String} `pattern` - * @param {Object} `options` - * @return {Object} Returns an object with useful properties and output to be used as a regex source string. - * @api public - */ - -picomatch$4.parse = (pattern, options) => { - if (Array.isArray(pattern)) return pattern.map(p => picomatch$4.parse(p, options)); - return parse$i(pattern, { ...options, fastpaths: false }); -}; - -/** - * Scan a glob pattern to separate the pattern into segments. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.scan(input[, options]); - * - * const result = picomatch.scan('!./foo/*.js'); - * console.log(result); - * { prefix: '!./', - * input: '!./foo/*.js', - * start: 3, - * base: 'foo', - * glob: '*.js', - * isBrace: false, - * isBracket: false, - * isGlob: true, - * isExtglob: false, - * isGlobstar: false, - * negated: true } - * ``` - * @param {String} `input` Glob pattern to scan. - * @param {Object} `options` - * @return {Object} Returns an object with - * @api public - */ - -picomatch$4.scan = (input, options) => scan(input, options); - -/** - * Compile a regular expression from the `state` object returned by the - * [parse()](#parse) method. - * - * @param {Object} `state` - * @param {Object} `options` - * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. - * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. - * @return {RegExp} - * @api public - */ - -picomatch$4.compileRe = (state, options, returnOutput = false, returnState = false) => { - if (returnOutput === true) { - return state.output; - } - - const opts = options || {}; - const prepend = opts.contains ? '' : '^'; - const append = opts.contains ? '' : '$'; - - let source = `${prepend}(?:${state.output})${append}`; - if (state && state.negated === true) { - source = `^(?!${source}).*$`; - } - - const regex = picomatch$4.toRegex(source, options); - if (returnState === true) { - regex.state = state; - } - - return regex; -}; - -/** - * Create a regular expression from a parsed glob pattern. - * - * ```js - * const picomatch = require('picomatch'); - * const state = picomatch.parse('*.js'); - * // picomatch.compileRe(state[, options]); - * - * console.log(picomatch.compileRe(state)); - * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ - * ``` - * @param {String} `state` The object returned from the `.parse` method. - * @param {Object} `options` - * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. - * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. - * @return {RegExp} Returns a regex created from the given pattern. - * @api public - */ - -picomatch$4.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { - if (!input || typeof input !== 'string') { - throw new TypeError('Expected a non-empty string'); - } - - let parsed = { negated: false, fastpaths: true }; - - if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { - parsed.output = parse$i.fastpaths(input, options); - } - - if (!parsed.output) { - parsed = parse$i(input, options); - } - - return picomatch$4.compileRe(parsed, options, returnOutput, returnState); -}; - -/** - * Create a regular expression from the given regex source string. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.toRegex(source[, options]); - * - * const { output } = picomatch.parse('*.js'); - * console.log(picomatch.toRegex(output)); - * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ - * ``` - * @param {String} `source` Regular expression source string. - * @param {Object} `options` - * @return {RegExp} - * @api public - */ - -picomatch$4.toRegex = (source, options) => { - try { - const opts = options || {}; - return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); - } catch (err) { - if (options && options.debug === true) throw err; - return /$^/; - } -}; - -/** - * Picomatch constants. - * @return {Object} - */ - -picomatch$4.constants = constants$3; - -/** - * Expose "picomatch" - */ - -var picomatch_1 = picomatch$4; - -var picomatch$3 = picomatch_1; - -const util$7 = require$$0__default$2; -const braces$1 = braces_1; -const picomatch$2 = picomatch$3; -const utils$b = utils$f; -const isEmptyString = val => val === '' || val === './'; - -/** - * Returns an array of strings that match one or more glob patterns. - * - * ```js - * const mm = require('micromatch'); - * // mm(list, patterns[, options]); - * - * console.log(mm(['a.js', 'a.txt'], ['*.js'])); - * //=> [ 'a.js' ] - * ``` - * @param {String|Array} `list` List of strings to match. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) - * @return {Array} Returns an array of matches - * @summary false - * @api public - */ - -const micromatch$1 = (list, patterns, options) => { - patterns = [].concat(patterns); - list = [].concat(list); - - let omit = new Set(); - let keep = new Set(); - let items = new Set(); - let negatives = 0; - - let onResult = state => { - items.add(state.output); - if (options && options.onResult) { - options.onResult(state); - } - }; - - for (let i = 0; i < patterns.length; i++) { - let isMatch = picomatch$2(String(patterns[i]), { ...options, onResult }, true); - let negated = isMatch.state.negated || isMatch.state.negatedExtglob; - if (negated) negatives++; - - for (let item of list) { - let matched = isMatch(item, true); - - let match = negated ? !matched.isMatch : matched.isMatch; - if (!match) continue; - - if (negated) { - omit.add(matched.output); - } else { - omit.delete(matched.output); - keep.add(matched.output); - } - } - } - - let result = negatives === patterns.length ? [...items] : [...keep]; - let matches = result.filter(item => !omit.has(item)); - - if (options && matches.length === 0) { - if (options.failglob === true) { - throw new Error(`No matches found for "${patterns.join(', ')}"`); - } - - if (options.nonull === true || options.nullglob === true) { - return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; - } - } - - return matches; -}; - -/** - * Backwards compatibility - */ - -micromatch$1.match = micromatch$1; - -/** - * Returns a matcher function from the given glob `pattern` and `options`. - * The returned function takes a string to match as its only argument and returns - * true if the string is a match. - * - * ```js - * const mm = require('micromatch'); - * // mm.matcher(pattern[, options]); - * - * const isMatch = mm.matcher('*.!(*a)'); - * console.log(isMatch('a.a')); //=> false - * console.log(isMatch('a.b')); //=> true - * ``` - * @param {String} `pattern` Glob pattern - * @param {Object} `options` - * @return {Function} Returns a matcher function. - * @api public - */ - -micromatch$1.matcher = (pattern, options) => picomatch$2(pattern, options); - -/** - * Returns true if **any** of the given glob `patterns` match the specified `string`. - * - * ```js - * const mm = require('micromatch'); - * // mm.isMatch(string, patterns[, options]); - * - * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true - * console.log(mm.isMatch('a.a', 'b.*')); //=> false - * ``` - * @param {String} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `[options]` See available [options](#options). - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ - -micromatch$1.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str); - -/** - * Backwards compatibility - */ - -micromatch$1.any = micromatch$1.isMatch; - -/** - * Returns a list of strings that _**do not match any**_ of the given `patterns`. - * - * ```js - * const mm = require('micromatch'); - * // mm.not(list, patterns[, options]); - * - * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); - * //=> ['b.b', 'c.c'] - * ``` - * @param {Array} `list` Array of strings to match. - * @param {String|Array} `patterns` One or more glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of strings that **do not match** the given patterns. - * @api public - */ - -micromatch$1.not = (list, patterns, options = {}) => { - patterns = [].concat(patterns).map(String); - let result = new Set(); - let items = []; - - let onResult = state => { - if (options.onResult) options.onResult(state); - items.push(state.output); - }; - - let matches = micromatch$1(list, patterns, { ...options, onResult }); - - for (let item of items) { - if (!matches.includes(item)) { - result.add(item); - } - } - return [...result]; -}; - -/** - * Returns true if the given `string` contains the given pattern. Similar - * to [.isMatch](#isMatch) but the pattern can match any part of the string. - * - * ```js - * var mm = require('micromatch'); - * // mm.contains(string, pattern[, options]); - * - * console.log(mm.contains('aa/bb/cc', '*b')); - * //=> true - * console.log(mm.contains('aa/bb/cc', '*d')); - * //=> false - * ``` - * @param {String} `str` The string to match. - * @param {String|Array} `patterns` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any of the patterns matches any part of `str`. - * @api public - */ - -micromatch$1.contains = (str, pattern, options) => { - if (typeof str !== 'string') { - throw new TypeError(`Expected a string: "${util$7.inspect(str)}"`); - } - - if (Array.isArray(pattern)) { - return pattern.some(p => micromatch$1.contains(str, p, options)); - } - - if (typeof pattern === 'string') { - if (isEmptyString(str) || isEmptyString(pattern)) { - return false; - } - - if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { - return true; - } - } - - return micromatch$1.isMatch(str, pattern, { ...options, contains: true }); -}; - -/** - * Filter the keys of the given object with the given `glob` pattern - * and `options`. Does not attempt to match nested keys. If you need this feature, - * use [glob-object][] instead. - * - * ```js - * const mm = require('micromatch'); - * // mm.matchKeys(object, patterns[, options]); - * - * const obj = { aa: 'a', ab: 'b', ac: 'c' }; - * console.log(mm.matchKeys(obj, '*b')); - * //=> { ab: 'b' } - * ``` - * @param {Object} `object` The object with keys to filter. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Object} Returns an object with only keys that match the given patterns. - * @api public - */ - -micromatch$1.matchKeys = (obj, patterns, options) => { - if (!utils$b.isObject(obj)) { - throw new TypeError('Expected the first argument to be an object'); - } - let keys = micromatch$1(Object.keys(obj), patterns, options); - let res = {}; - for (let key of keys) res[key] = obj[key]; - return res; -}; - -/** - * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. - * - * ```js - * const mm = require('micromatch'); - * // mm.some(list, patterns[, options]); - * - * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // true - * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` - * @api public - */ - -micromatch$1.some = (list, patterns, options) => { - let items = [].concat(list); - - for (let pattern of [].concat(patterns)) { - let isMatch = picomatch$2(String(pattern), options); - if (items.some(item => isMatch(item))) { - return true; - } - } - return false; -}; - -/** - * Returns true if every string in the given `list` matches - * any of the given glob `patterns`. - * - * ```js - * const mm = require('micromatch'); - * // mm.every(list, patterns[, options]); - * - * console.log(mm.every('foo.js', ['foo.js'])); - * // true - * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); - * // true - * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // false - * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` - * @api public - */ - -micromatch$1.every = (list, patterns, options) => { - let items = [].concat(list); - - for (let pattern of [].concat(patterns)) { - let isMatch = picomatch$2(String(pattern), options); - if (!items.every(item => isMatch(item))) { - return false; - } - } - return true; -}; - -/** - * Returns true if **all** of the given `patterns` match - * the specified string. - * - * ```js - * const mm = require('micromatch'); - * // mm.all(string, patterns[, options]); - * - * console.log(mm.all('foo.js', ['foo.js'])); - * // true - * - * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); - * // false - * - * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); - * // true - * - * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); - * // true - * ``` - * @param {String|Array} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ - -micromatch$1.all = (str, patterns, options) => { - if (typeof str !== 'string') { - throw new TypeError(`Expected a string: "${util$7.inspect(str)}"`); - } - - return [].concat(patterns).every(p => picomatch$2(p, options)(str)); -}; - -/** - * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. - * - * ```js - * const mm = require('micromatch'); - * // mm.capture(pattern, string[, options]); - * - * console.log(mm.capture('test/*.js', 'test/foo.js')); - * //=> ['foo'] - * console.log(mm.capture('test/*.js', 'foo/bar.css')); - * //=> null - * ``` - * @param {String} `glob` Glob pattern to use for matching. - * @param {String} `input` String to match - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. - * @api public - */ - -micromatch$1.capture = (glob, input, options) => { - let posix = utils$b.isWindows(options); - let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true }); - let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input); - - if (match) { - return match.slice(1).map(v => v === void 0 ? '' : v); - } -}; - -/** - * Create a regular expression from the given glob `pattern`. - * - * ```js - * const mm = require('micromatch'); - * // mm.makeRe(pattern[, options]); - * - * console.log(mm.makeRe('*.js')); - * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ - * ``` - * @param {String} `pattern` A glob pattern to convert to regex. - * @param {Object} `options` - * @return {RegExp} Returns a regex created from the given pattern. - * @api public - */ - -micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args); - -/** - * Scan a glob pattern to separate the pattern into segments. Used - * by the [split](#split) method. - * - * ```js - * const mm = require('micromatch'); - * const state = mm.scan(pattern[, options]); - * ``` - * @param {String} `pattern` - * @param {Object} `options` - * @return {Object} Returns an object with - * @api public - */ - -micromatch$1.scan = (...args) => picomatch$2.scan(...args); - -/** - * Parse a glob pattern to create the source string for a regular - * expression. - * - * ```js - * const mm = require('micromatch'); - * const state = mm(pattern[, options]); - * ``` - * @param {String} `glob` - * @param {Object} `options` - * @return {Object} Returns an object with useful properties and output to be used as regex source string. - * @api public - */ - -micromatch$1.parse = (patterns, options) => { - let res = []; - for (let pattern of [].concat(patterns || [])) { - for (let str of braces$1(String(pattern), options)) { - res.push(picomatch$2.parse(str, options)); - } - } - return res; -}; - -/** - * Process the given brace `pattern`. - * - * ```js - * const { braces } = require('micromatch'); - * console.log(braces('foo/{a,b,c}/bar')); - * //=> [ 'foo/(a|b|c)/bar' ] - * - * console.log(braces('foo/{a,b,c}/bar', { expand: true })); - * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] - * ``` - * @param {String} `pattern` String with brace pattern to process. - * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. - * @return {Array} - * @api public - */ - -micromatch$1.braces = (pattern, options) => { - if (typeof pattern !== 'string') throw new TypeError('Expected a string'); - if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { - return [pattern]; - } - return braces$1(pattern, options); -}; - -/** - * Expand braces - */ - -micromatch$1.braceExpand = (pattern, options) => { - if (typeof pattern !== 'string') throw new TypeError('Expected a string'); - return micromatch$1.braces(pattern, { ...options, expand: true }); -}; - -/** - * Expose micromatch - */ - -var micromatch_1 = micromatch$1; - -Object.defineProperty(pattern$1, "__esModule", { value: true }); -pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0; -const path$o = path__default; -const globParent$1 = globParent$2; -const micromatch = micromatch_1; -const GLOBSTAR$2 = '**'; -const ESCAPE_SYMBOL = '\\'; -const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; -const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/; -const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/; -const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/; -const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/; -function isStaticPattern(pattern, options = {}) { - return !isDynamicPattern(pattern, options); -} -pattern$1.isStaticPattern = isStaticPattern; -function isDynamicPattern(pattern, options = {}) { - /** - * A special case with an empty string is necessary for matching patterns that start with a forward slash. - * An empty string cannot be a dynamic pattern. - * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. - */ - if (pattern === '') { - return false; - } - /** - * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check - * filepath directly (without read directory). - */ - if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { - return true; - } - if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { - return true; - } - if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { - return true; - } - if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) { - return true; - } - return false; -} -pattern$1.isDynamicPattern = isDynamicPattern; -function convertToPositivePattern(pattern) { - return isNegativePattern(pattern) ? pattern.slice(1) : pattern; -} -pattern$1.convertToPositivePattern = convertToPositivePattern; -function convertToNegativePattern(pattern) { - return '!' + pattern; -} -pattern$1.convertToNegativePattern = convertToNegativePattern; -function isNegativePattern(pattern) { - return pattern.startsWith('!') && pattern[1] !== '('; -} -pattern$1.isNegativePattern = isNegativePattern; -function isPositivePattern(pattern) { - return !isNegativePattern(pattern); -} -pattern$1.isPositivePattern = isPositivePattern; -function getNegativePatterns(patterns) { - return patterns.filter(isNegativePattern); -} -pattern$1.getNegativePatterns = getNegativePatterns; -function getPositivePatterns$1(patterns) { - return patterns.filter(isPositivePattern); -} -pattern$1.getPositivePatterns = getPositivePatterns$1; -/** - * Returns patterns that can be applied inside the current directory. - * - * @example - * // ['./*', '*', 'a/*'] - * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) - */ -function getPatternsInsideCurrentDirectory(patterns) { - return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); -} -pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; -/** - * Returns patterns to be expanded relative to (outside) the current directory. - * - * @example - * // ['../*', './../*'] - * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) - */ -function getPatternsOutsideCurrentDirectory(patterns) { - return patterns.filter(isPatternRelatedToParentDirectory); -} -pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; -function isPatternRelatedToParentDirectory(pattern) { - return pattern.startsWith('..') || pattern.startsWith('./..'); -} -pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; -function getBaseDirectory(pattern) { - return globParent$1(pattern, { flipBackslashes: false }); -} -pattern$1.getBaseDirectory = getBaseDirectory; -function hasGlobStar(pattern) { - return pattern.includes(GLOBSTAR$2); -} -pattern$1.hasGlobStar = hasGlobStar; -function endsWithSlashGlobStar(pattern) { - return pattern.endsWith('/' + GLOBSTAR$2); -} -pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar; -function isAffectDepthOfReadingPattern(pattern) { - const basename = path$o.basename(pattern); - return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); -} -pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; -function expandPatternsWithBraceExpansion(patterns) { - return patterns.reduce((collection, pattern) => { - return collection.concat(expandBraceExpansion(pattern)); - }, []); -} -pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; -function expandBraceExpansion(pattern) { - return micromatch.braces(pattern, { - expand: true, - nodupes: true - }); -} -pattern$1.expandBraceExpansion = expandBraceExpansion; -function getPatternParts(pattern, options) { - let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); - /** - * The scan method returns an empty array in some cases. - * See micromatch/picomatch#58 for more details. - */ - if (parts.length === 0) { - parts = [pattern]; - } - /** - * The scan method does not return an empty part for the pattern with a forward slash. - * This is another part of micromatch/picomatch#58. - */ - if (parts[0].startsWith('/')) { - parts[0] = parts[0].slice(1); - parts.unshift(''); - } - return parts; -} -pattern$1.getPatternParts = getPatternParts; -function makeRe$1(pattern, options) { - return micromatch.makeRe(pattern, options); -} -pattern$1.makeRe = makeRe$1; -function convertPatternsToRe(patterns, options) { - return patterns.map((pattern) => makeRe$1(pattern, options)); -} -pattern$1.convertPatternsToRe = convertPatternsToRe; -function matchAny(entry, patternsRe) { - return patternsRe.some((patternRe) => patternRe.test(entry)); -} -pattern$1.matchAny = matchAny; - -var stream$7 = {}; - -/* - * merge2 - * https://github.com/teambition/merge2 - * - * Copyright (c) 2014-2020 Teambition - * Licensed under the MIT license. - */ -const Stream = require$$0__default$4; -const PassThrough$1 = Stream.PassThrough; -const slice$1 = Array.prototype.slice; - -var merge2_1 = merge2$2; - -function merge2$2 () { - const streamsQueue = []; - const args = slice$1.call(arguments); - let merging = false; - let options = args[args.length - 1]; - - if (options && !Array.isArray(options) && options.pipe == null) { - args.pop(); - } else { - options = {}; - } - - const doEnd = options.end !== false; - const doPipeError = options.pipeError === true; - if (options.objectMode == null) { - options.objectMode = true; - } - if (options.highWaterMark == null) { - options.highWaterMark = 64 * 1024; - } - const mergedStream = PassThrough$1(options); - - function addStream () { - for (let i = 0, len = arguments.length; i < len; i++) { - streamsQueue.push(pauseStreams(arguments[i], options)); - } - mergeStream(); - return this - } - - function mergeStream () { - if (merging) { - return - } - merging = true; - - let streams = streamsQueue.shift(); - if (!streams) { - process.nextTick(endStream); - return - } - if (!Array.isArray(streams)) { - streams = [streams]; - } - - let pipesCount = streams.length + 1; - - function next () { - if (--pipesCount > 0) { - return - } - merging = false; - mergeStream(); - } - - function pipe (stream) { - function onend () { - stream.removeListener('merge2UnpipeEnd', onend); - stream.removeListener('end', onend); - if (doPipeError) { - stream.removeListener('error', onerror); - } - next(); - } - function onerror (err) { - mergedStream.emit('error', err); - } - // skip ended stream - if (stream._readableState.endEmitted) { - return next() - } - - stream.on('merge2UnpipeEnd', onend); - stream.on('end', onend); - - if (doPipeError) { - stream.on('error', onerror); - } - - stream.pipe(mergedStream, { end: false }); - // compatible for old stream - stream.resume(); - } - - for (let i = 0; i < streams.length; i++) { - pipe(streams[i]); - } - - next(); - } - - function endStream () { - merging = false; - // emit 'queueDrain' when all streams merged. - mergedStream.emit('queueDrain'); - if (doEnd) { - mergedStream.end(); - } - } - - mergedStream.setMaxListeners(0); - mergedStream.add = addStream; - mergedStream.on('unpipe', function (stream) { - stream.emit('merge2UnpipeEnd'); - }); - - if (args.length) { - addStream.apply(null, args); - } - return mergedStream -} - -// check and pause streams for pipe. -function pauseStreams (streams, options) { - if (!Array.isArray(streams)) { - // Backwards-compat with old-style streams - if (!streams._readableState && streams.pipe) { - streams = streams.pipe(PassThrough$1(options)); - } - if (!streams._readableState || !streams.pause || !streams.pipe) { - throw new Error('Only readable stream can be merged.') - } - streams.pause(); - } else { - for (let i = 0, len = streams.length; i < len; i++) { - streams[i] = pauseStreams(streams[i], options); - } - } - return streams -} - -Object.defineProperty(stream$7, "__esModule", { value: true }); -stream$7.merge = void 0; -const merge2$1 = merge2_1; -function merge$1(streams) { - const mergedStream = merge2$1(streams); - streams.forEach((stream) => { - stream.once('error', (error) => mergedStream.emit('error', error)); - }); - mergedStream.once('close', () => propagateCloseEventToSources(streams)); - mergedStream.once('end', () => propagateCloseEventToSources(streams)); - return mergedStream; -} -stream$7.merge = merge$1; -function propagateCloseEventToSources(streams) { - streams.forEach((stream) => stream.emit('close')); -} - -var string$2 = {}; - -Object.defineProperty(string$2, "__esModule", { value: true }); -string$2.isEmpty = string$2.isString = void 0; -function isString$1(input) { - return typeof input === 'string'; -} -string$2.isString = isString$1; -function isEmpty(input) { - return input === ''; -} -string$2.isEmpty = isEmpty; - -Object.defineProperty(utils$k, "__esModule", { value: true }); -utils$k.string = utils$k.stream = utils$k.pattern = utils$k.path = utils$k.fs = utils$k.errno = utils$k.array = void 0; -const array = array$1; -utils$k.array = array; -const errno = errno$1; -utils$k.errno = errno; -const fs$p = fs$q; -utils$k.fs = fs$p; -const path$n = path$s; -utils$k.path = path$n; -const pattern = pattern$1; -utils$k.pattern = pattern; -const stream$6 = stream$7; -utils$k.stream = stream$6; -const string$1 = string$2; -utils$k.string = string$1; - -Object.defineProperty(tasks, "__esModule", { value: true }); -tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0; -const utils$a = utils$k; -function generate(patterns, settings) { - const positivePatterns = getPositivePatterns(patterns); - const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); - const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings)); - const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings)); - const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); - const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); - return staticTasks.concat(dynamicTasks); -} -tasks.generate = generate; -/** - * Returns tasks grouped by basic pattern directories. - * - * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. - * This is necessary because directory traversal starts at the base directory and goes deeper. - */ -function convertPatternsToTasks(positive, negative, dynamic) { - const tasks = []; - const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive); - const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive); - const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); - const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); - tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); - /* - * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory - * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. - */ - if ('.' in insideCurrentDirectoryGroup) { - tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); - } - else { - tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); - } - return tasks; -} -tasks.convertPatternsToTasks = convertPatternsToTasks; -function getPositivePatterns(patterns) { - return utils$a.pattern.getPositivePatterns(patterns); -} -tasks.getPositivePatterns = getPositivePatterns; -function getNegativePatternsAsPositive(patterns, ignore) { - const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore); - const positive = negative.map(utils$a.pattern.convertToPositivePattern); - return positive; -} -tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive; -function groupPatternsByBaseDirectory(patterns) { - const group = {}; - return patterns.reduce((collection, pattern) => { - const base = utils$a.pattern.getBaseDirectory(pattern); - if (base in collection) { - collection[base].push(pattern); - } - else { - collection[base] = [pattern]; - } - return collection; - }, group); -} -tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; -function convertPatternGroupsToTasks(positive, negative, dynamic) { - return Object.keys(positive).map((base) => { - return convertPatternGroupToTask(base, positive[base], negative, dynamic); - }); -} -tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks; -function convertPatternGroupToTask(base, positive, negative, dynamic) { - return { - dynamic, - positive, - negative, - base, - patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern)) - }; -} -tasks.convertPatternGroupToTask = convertPatternGroupToTask; - -var async$6 = {}; - -var stream$5 = {}; - -var out$3 = {}; - -var async$5 = {}; - -Object.defineProperty(async$5, "__esModule", { value: true }); -async$5.read = void 0; -function read$3(path, settings, callback) { - settings.fs.lstat(path, (lstatError, lstat) => { - if (lstatError !== null) { - callFailureCallback$2(callback, lstatError); - return; - } - if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { - callSuccessCallback$2(callback, lstat); - return; - } - settings.fs.stat(path, (statError, stat) => { - if (statError !== null) { - if (settings.throwErrorOnBrokenSymbolicLink) { - callFailureCallback$2(callback, statError); - return; - } - callSuccessCallback$2(callback, lstat); - return; - } - if (settings.markSymbolicLink) { - stat.isSymbolicLink = () => true; - } - callSuccessCallback$2(callback, stat); - }); - }); -} -async$5.read = read$3; -function callFailureCallback$2(callback, error) { - callback(error); -} -function callSuccessCallback$2(callback, result) { - callback(null, result); -} - -var sync$b = {}; - -Object.defineProperty(sync$b, "__esModule", { value: true }); -sync$b.read = void 0; -function read$2(path, settings) { - const lstat = settings.fs.lstatSync(path); - if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { - return lstat; - } - try { - const stat = settings.fs.statSync(path); - if (settings.markSymbolicLink) { - stat.isSymbolicLink = () => true; - } - return stat; - } - catch (error) { - if (!settings.throwErrorOnBrokenSymbolicLink) { - return lstat; - } - throw error; - } -} -sync$b.read = read$2; - -var settings$3 = {}; - -var fs$o = {}; - -(function (exports) { -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; -const fs = fs__default; -exports.FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - stat: fs.stat, - lstatSync: fs.lstatSync, - statSync: fs.statSync -}; -function createFileSystemAdapter(fsMethods) { - if (fsMethods === undefined) { - return exports.FILE_SYSTEM_ADAPTER; - } - return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); -} -exports.createFileSystemAdapter = createFileSystemAdapter; -}(fs$o)); - -Object.defineProperty(settings$3, "__esModule", { value: true }); -const fs$n = fs$o; -class Settings$2 { - constructor(_options = {}) { - this._options = _options; - this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); - this.fs = fs$n.createFileSystemAdapter(this._options.fs); - this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); - } - _getValue(option, value) { - return option !== null && option !== void 0 ? option : value; - } -} -settings$3.default = Settings$2; - -Object.defineProperty(out$3, "__esModule", { value: true }); -out$3.statSync = out$3.stat = out$3.Settings = void 0; -const async$4 = async$5; -const sync$a = sync$b; -const settings_1$3 = settings$3; -out$3.Settings = settings_1$3.default; -function stat$4(path, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === 'function') { - async$4.read(path, getSettings$2(), optionsOrSettingsOrCallback); - return; - } - async$4.read(path, getSettings$2(optionsOrSettingsOrCallback), callback); -} -out$3.stat = stat$4; -function statSync(path, optionsOrSettings) { - const settings = getSettings$2(optionsOrSettings); - return sync$a.read(path, settings); -} -out$3.statSync = statSync; -function getSettings$2(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings_1$3.default) { - return settingsOrOptions; - } - return new settings_1$3.default(settingsOrOptions); -} - -var out$2 = {}; - -var async$3 = {}; - -var async$2 = {}; - -var out$1 = {}; - -var async$1 = {}; - -/*! queue-microtask. MIT License. Feross Aboukhadijeh */ - -let promise$1; - -var queueMicrotask_1 = typeof queueMicrotask === 'function' - ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal) - // reuse resolved promise, and allocate it lazily - : cb => (promise$1 || (promise$1 = Promise.resolve())) - .then(cb) - .catch(err => setTimeout(() => { throw err }, 0)); - -/*! run-parallel. MIT License. Feross Aboukhadijeh */ - -var runParallel_1 = runParallel; - -const queueMicrotask$1 = queueMicrotask_1; - -function runParallel (tasks, cb) { - let results, pending, keys; - let isSync = true; - - if (Array.isArray(tasks)) { - results = []; - pending = tasks.length; - } else { - keys = Object.keys(tasks); - results = {}; - pending = keys.length; - } - - function done (err) { - function end () { - if (cb) cb(err, results); - cb = null; - } - if (isSync) queueMicrotask$1(end); - else end(); - } - - function each (i, err, result) { - results[i] = result; - if (--pending === 0 || err) { - done(err); - } - } - - if (!pending) { - // empty - done(null); - } else if (keys) { - // object - keys.forEach(function (key) { - tasks[key](function (err, result) { each(key, err, result); }); - }); - } else { - // array - tasks.forEach(function (task, i) { - task(function (err, result) { each(i, err, result); }); - }); - } - - isSync = false; -} - -var constants$2 = {}; - -Object.defineProperty(constants$2, "__esModule", { value: true }); -constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; -const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); -if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { - throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); -} -const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); -const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); -const SUPPORTED_MAJOR_VERSION = 10; -const SUPPORTED_MINOR_VERSION = 10; -const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; -const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; -/** - * IS `true` for Node.js 10.10 and greater. - */ -constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; - -var utils$9 = {}; - -var fs$m = {}; - -Object.defineProperty(fs$m, "__esModule", { value: true }); -fs$m.createDirentFromStats = void 0; -class DirentFromStats { - constructor(name, stats) { - this.name = name; - this.isBlockDevice = stats.isBlockDevice.bind(stats); - this.isCharacterDevice = stats.isCharacterDevice.bind(stats); - this.isDirectory = stats.isDirectory.bind(stats); - this.isFIFO = stats.isFIFO.bind(stats); - this.isFile = stats.isFile.bind(stats); - this.isSocket = stats.isSocket.bind(stats); - this.isSymbolicLink = stats.isSymbolicLink.bind(stats); - } -} -function createDirentFromStats(name, stats) { - return new DirentFromStats(name, stats); -} -fs$m.createDirentFromStats = createDirentFromStats; - -Object.defineProperty(utils$9, "__esModule", { value: true }); -utils$9.fs = void 0; -const fs$l = fs$m; -utils$9.fs = fs$l; - -var common$d = {}; - -Object.defineProperty(common$d, "__esModule", { value: true }); -common$d.joinPathSegments = void 0; -function joinPathSegments$1(a, b, separator) { - /** - * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). - */ - if (a.endsWith(separator)) { - return a + b; - } - return a + separator + b; -} -common$d.joinPathSegments = joinPathSegments$1; - -Object.defineProperty(async$1, "__esModule", { value: true }); -async$1.readdir = async$1.readdirWithFileTypes = async$1.read = void 0; -const fsStat$5 = out$3; -const rpl = runParallel_1; -const constants_1$1 = constants$2; -const utils$8 = utils$9; -const common$c = common$d; -function read$1(directory, settings, callback) { - if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { - readdirWithFileTypes$1(directory, settings, callback); - return; - } - readdir$3(directory, settings, callback); -} -async$1.read = read$1; -function readdirWithFileTypes$1(directory, settings, callback) { - settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { - if (readdirError !== null) { - callFailureCallback$1(callback, readdirError); - return; - } - const entries = dirents.map((dirent) => ({ - dirent, - name: dirent.name, - path: common$c.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) - })); - if (!settings.followSymbolicLinks) { - callSuccessCallback$1(callback, entries); - return; - } - const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); - rpl(tasks, (rplError, rplEntries) => { - if (rplError !== null) { - callFailureCallback$1(callback, rplError); - return; - } - callSuccessCallback$1(callback, rplEntries); - }); - }); -} -async$1.readdirWithFileTypes = readdirWithFileTypes$1; -function makeRplTaskEntry(entry, settings) { - return (done) => { - if (!entry.dirent.isSymbolicLink()) { - done(null, entry); - return; - } - settings.fs.stat(entry.path, (statError, stats) => { - if (statError !== null) { - if (settings.throwErrorOnBrokenSymbolicLink) { - done(statError); - return; - } - done(null, entry); - return; - } - entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats); - done(null, entry); - }); - }; -} -function readdir$3(directory, settings, callback) { - settings.fs.readdir(directory, (readdirError, names) => { - if (readdirError !== null) { - callFailureCallback$1(callback, readdirError); - return; - } - const tasks = names.map((name) => { - const path = common$c.joinPathSegments(directory, name, settings.pathSegmentSeparator); - return (done) => { - fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => { - if (error !== null) { - done(error); - return; - } - const entry = { - name, - path, - dirent: utils$8.fs.createDirentFromStats(name, stats) - }; - if (settings.stats) { - entry.stats = stats; - } - done(null, entry); - }); - }; - }); - rpl(tasks, (rplError, entries) => { - if (rplError !== null) { - callFailureCallback$1(callback, rplError); - return; - } - callSuccessCallback$1(callback, entries); - }); - }); -} -async$1.readdir = readdir$3; -function callFailureCallback$1(callback, error) { - callback(error); -} -function callSuccessCallback$1(callback, result) { - callback(null, result); -} - -var sync$9 = {}; - -Object.defineProperty(sync$9, "__esModule", { value: true }); -sync$9.readdir = sync$9.readdirWithFileTypes = sync$9.read = void 0; -const fsStat$4 = out$3; -const constants_1 = constants$2; -const utils$7 = utils$9; -const common$b = common$d; -function read(directory, settings) { - if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { - return readdirWithFileTypes(directory, settings); - } - return readdir$2(directory, settings); -} -sync$9.read = read; -function readdirWithFileTypes(directory, settings) { - const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); - return dirents.map((dirent) => { - const entry = { - dirent, - name: dirent.name, - path: common$b.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) - }; - if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { - try { - const stats = settings.fs.statSync(entry.path); - entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats); - } - catch (error) { - if (settings.throwErrorOnBrokenSymbolicLink) { - throw error; - } - } - } - return entry; - }); -} -sync$9.readdirWithFileTypes = readdirWithFileTypes; -function readdir$2(directory, settings) { - const names = settings.fs.readdirSync(directory); - return names.map((name) => { - const entryPath = common$b.joinPathSegments(directory, name, settings.pathSegmentSeparator); - const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings); - const entry = { - name, - path: entryPath, - dirent: utils$7.fs.createDirentFromStats(name, stats) - }; - if (settings.stats) { - entry.stats = stats; - } - return entry; - }); -} -sync$9.readdir = readdir$2; - -var settings$2 = {}; - -var fs$k = {}; - -(function (exports) { -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; -const fs = fs__default; -exports.FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - stat: fs.stat, - lstatSync: fs.lstatSync, - statSync: fs.statSync, - readdir: fs.readdir, - readdirSync: fs.readdirSync -}; -function createFileSystemAdapter(fsMethods) { - if (fsMethods === undefined) { - return exports.FILE_SYSTEM_ADAPTER; - } - return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); -} -exports.createFileSystemAdapter = createFileSystemAdapter; -}(fs$k)); - -Object.defineProperty(settings$2, "__esModule", { value: true }); -const path$m = path__default; -const fsStat$3 = out$3; -const fs$j = fs$k; -class Settings$1 { - constructor(_options = {}) { - this._options = _options; - this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); - this.fs = fs$j.createFileSystemAdapter(this._options.fs); - this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$m.sep); - this.stats = this._getValue(this._options.stats, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); - this.fsStatSettings = new fsStat$3.Settings({ - followSymbolicLink: this.followSymbolicLinks, - fs: this.fs, - throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink - }); - } - _getValue(option, value) { - return option !== null && option !== void 0 ? option : value; - } -} -settings$2.default = Settings$1; - -Object.defineProperty(out$1, "__esModule", { value: true }); -out$1.Settings = out$1.scandirSync = out$1.scandir = void 0; -const async = async$1; -const sync$8 = sync$9; -const settings_1$2 = settings$2; -out$1.Settings = settings_1$2.default; -function scandir(path, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === 'function') { - async.read(path, getSettings$1(), optionsOrSettingsOrCallback); - return; - } - async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback); -} -out$1.scandir = scandir; -function scandirSync(path, optionsOrSettings) { - const settings = getSettings$1(optionsOrSettings); - return sync$8.read(path, settings); -} -out$1.scandirSync = scandirSync; -function getSettings$1(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings_1$2.default) { - return settingsOrOptions; - } - return new settings_1$2.default(settingsOrOptions); -} - -var queue = {exports: {}}; - -function reusify$1 (Constructor) { - var head = new Constructor(); - var tail = head; - - function get () { - var current = head; - - if (current.next) { - head = current.next; - } else { - head = new Constructor(); - tail = head; - } - - current.next = null; - - return current - } - - function release (obj) { - tail.next = obj; - tail = obj; - } - - return { - get: get, - release: release - } -} - -var reusify_1 = reusify$1; - -/* eslint-disable no-var */ - -var reusify = reusify_1; - -function fastqueue (context, worker, concurrency) { - if (typeof context === 'function') { - concurrency = worker; - worker = context; - context = null; - } - - if (concurrency < 1) { - throw new Error('fastqueue concurrency must be greater than 1') - } - - var cache = reusify(Task); - var queueHead = null; - var queueTail = null; - var _running = 0; - var errorHandler = null; - - var self = { - push: push, - drain: noop$3, - saturated: noop$3, - pause: pause, - paused: false, - concurrency: concurrency, - running: running, - resume: resume, - idle: idle, - length: length, - getQueue: getQueue, - unshift: unshift, - empty: noop$3, - kill: kill, - killAndDrain: killAndDrain, - error: error - }; - - return self - - function running () { - return _running - } - - function pause () { - self.paused = true; - } - - function length () { - var current = queueHead; - var counter = 0; - - while (current) { - current = current.next; - counter++; - } - - return counter - } - - function getQueue () { - var current = queueHead; - var tasks = []; - - while (current) { - tasks.push(current.value); - current = current.next; - } - - return tasks - } - - function resume () { - if (!self.paused) return - self.paused = false; - for (var i = 0; i < self.concurrency; i++) { - _running++; - release(); - } - } - - function idle () { - return _running === 0 && self.length() === 0 - } - - function push (value, done) { - var current = cache.get(); - - current.context = context; - current.release = release; - current.value = value; - current.callback = done || noop$3; - current.errorHandler = errorHandler; - - if (_running === self.concurrency || self.paused) { - if (queueTail) { - queueTail.next = current; - queueTail = current; - } else { - queueHead = current; - queueTail = current; - self.saturated(); - } - } else { - _running++; - worker.call(context, current.value, current.worked); - } - } - - function unshift (value, done) { - var current = cache.get(); - - current.context = context; - current.release = release; - current.value = value; - current.callback = done || noop$3; - - if (_running === self.concurrency || self.paused) { - if (queueHead) { - current.next = queueHead; - queueHead = current; - } else { - queueHead = current; - queueTail = current; - self.saturated(); - } - } else { - _running++; - worker.call(context, current.value, current.worked); - } - } - - function release (holder) { - if (holder) { - cache.release(holder); - } - var next = queueHead; - if (next) { - if (!self.paused) { - if (queueTail === queueHead) { - queueTail = null; - } - queueHead = next.next; - next.next = null; - worker.call(context, next.value, next.worked); - if (queueTail === null) { - self.empty(); - } - } else { - _running--; - } - } else if (--_running === 0) { - self.drain(); - } - } - - function kill () { - queueHead = null; - queueTail = null; - self.drain = noop$3; - } - - function killAndDrain () { - queueHead = null; - queueTail = null; - self.drain(); - self.drain = noop$3; - } - - function error (handler) { - errorHandler = handler; - } -} - -function noop$3 () {} - -function Task () { - this.value = null; - this.callback = noop$3; - this.next = null; - this.release = noop$3; - this.context = null; - this.errorHandler = null; - - var self = this; - - this.worked = function worked (err, result) { - var callback = self.callback; - var errorHandler = self.errorHandler; - var val = self.value; - self.value = null; - self.callback = noop$3; - if (self.errorHandler) { - errorHandler(err, val); - } - callback.call(self.context, err, result); - self.release(self); - }; -} - -function queueAsPromised (context, worker, concurrency) { - if (typeof context === 'function') { - concurrency = worker; - worker = context; - context = null; - } - - function asyncWrapper (arg, cb) { - worker.call(this, arg) - .then(function (res) { - cb(null, res); - }, cb); - } - - var queue = fastqueue(context, asyncWrapper, concurrency); - - var pushCb = queue.push; - var unshiftCb = queue.unshift; - - queue.push = push; - queue.unshift = unshift; - queue.drained = drained; - - return queue - - function push (value) { - var p = new Promise(function (resolve, reject) { - pushCb(value, function (err, result) { - if (err) { - reject(err); - return - } - resolve(result); - }); - }); - - // Let's fork the promise chain to - // make the error bubble up to the user but - // not lead to a unhandledRejection - p.catch(noop$3); - - return p - } - - function unshift (value) { - var p = new Promise(function (resolve, reject) { - unshiftCb(value, function (err, result) { - if (err) { - reject(err); - return - } - resolve(result); - }); - }); - - // Let's fork the promise chain to - // make the error bubble up to the user but - // not lead to a unhandledRejection - p.catch(noop$3); - - return p - } - - function drained () { - var previousDrain = queue.drain; - - var p = new Promise(function (resolve) { - queue.drain = function () { - previousDrain(); - resolve(); - }; - }); - - return p - } -} - -queue.exports = fastqueue; -queue.exports.promise = queueAsPromised; - -var common$a = {}; - -Object.defineProperty(common$a, "__esModule", { value: true }); -common$a.joinPathSegments = common$a.replacePathSegmentSeparator = common$a.isAppliedFilter = common$a.isFatalError = void 0; -function isFatalError(settings, error) { - if (settings.errorFilter === null) { - return true; - } - return !settings.errorFilter(error); -} -common$a.isFatalError = isFatalError; -function isAppliedFilter(filter, value) { - return filter === null || filter(value); -} -common$a.isAppliedFilter = isAppliedFilter; -function replacePathSegmentSeparator(filepath, separator) { - return filepath.split(/[/\\]/).join(separator); -} -common$a.replacePathSegmentSeparator = replacePathSegmentSeparator; -function joinPathSegments(a, b, separator) { - if (a === '') { - return b; - } - /** - * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). - */ - if (a.endsWith(separator)) { - return a + b; - } - return a + separator + b; -} -common$a.joinPathSegments = joinPathSegments; - -var reader$1 = {}; - -Object.defineProperty(reader$1, "__esModule", { value: true }); -const common$9 = common$a; -class Reader$1 { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._root = common$9.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); - } -} -reader$1.default = Reader$1; - -Object.defineProperty(async$2, "__esModule", { value: true }); -const events_1 = require$$0__default$5; -const fsScandir$2 = out$1; -const fastq = queue.exports; -const common$8 = common$a; -const reader_1$3 = reader$1; -class AsyncReader extends reader_1$3.default { - constructor(_root, _settings) { - super(_root, _settings); - this._settings = _settings; - this._scandir = fsScandir$2.scandir; - this._emitter = new events_1.EventEmitter(); - this._queue = fastq(this._worker.bind(this), this._settings.concurrency); - this._isFatalError = false; - this._isDestroyed = false; - this._queue.drain = () => { - if (!this._isFatalError) { - this._emitter.emit('end'); - } - }; - } - read() { - this._isFatalError = false; - this._isDestroyed = false; - setImmediate(() => { - this._pushToQueue(this._root, this._settings.basePath); - }); - return this._emitter; - } - get isDestroyed() { - return this._isDestroyed; - } - destroy() { - if (this._isDestroyed) { - throw new Error('The reader is already destroyed'); - } - this._isDestroyed = true; - this._queue.killAndDrain(); - } - onEntry(callback) { - this._emitter.on('entry', callback); - } - onError(callback) { - this._emitter.once('error', callback); - } - onEnd(callback) { - this._emitter.once('end', callback); - } - _pushToQueue(directory, base) { - const queueItem = { directory, base }; - this._queue.push(queueItem, (error) => { - if (error !== null) { - this._handleError(error); - } - }); - } - _worker(item, done) { - this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { - if (error !== null) { - done(error, undefined); - return; - } - for (const entry of entries) { - this._handleEntry(entry, item.base); - } - done(null, undefined); - }); - } - _handleError(error) { - if (this._isDestroyed || !common$8.isFatalError(this._settings, error)) { - return; - } - this._isFatalError = true; - this._isDestroyed = true; - this._emitter.emit('error', error); - } - _handleEntry(entry, base) { - if (this._isDestroyed || this._isFatalError) { - return; - } - const fullpath = entry.path; - if (base !== undefined) { - entry.path = common$8.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); - } - if (common$8.isAppliedFilter(this._settings.entryFilter, entry)) { - this._emitEntry(entry); - } - if (entry.dirent.isDirectory() && common$8.isAppliedFilter(this._settings.deepFilter, entry)) { - this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); - } - } - _emitEntry(entry) { - this._emitter.emit('entry', entry); - } -} -async$2.default = AsyncReader; - -Object.defineProperty(async$3, "__esModule", { value: true }); -const async_1$3 = async$2; -class AsyncProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new async_1$3.default(this._root, this._settings); - this._storage = []; - } - read(callback) { - this._reader.onError((error) => { - callFailureCallback(callback, error); - }); - this._reader.onEntry((entry) => { - this._storage.push(entry); - }); - this._reader.onEnd(() => { - callSuccessCallback(callback, this._storage); - }); - this._reader.read(); - } -} -async$3.default = AsyncProvider; -function callFailureCallback(callback, error) { - callback(error); -} -function callSuccessCallback(callback, entries) { - callback(null, entries); -} - -var stream$4 = {}; - -Object.defineProperty(stream$4, "__esModule", { value: true }); -const stream_1$5 = require$$0__default$4; -const async_1$2 = async$2; -class StreamProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new async_1$2.default(this._root, this._settings); - this._stream = new stream_1$5.Readable({ - objectMode: true, - read: () => { }, - destroy: () => { - if (!this._reader.isDestroyed) { - this._reader.destroy(); - } - } - }); - } - read() { - this._reader.onError((error) => { - this._stream.emit('error', error); - }); - this._reader.onEntry((entry) => { - this._stream.push(entry); - }); - this._reader.onEnd(() => { - this._stream.push(null); - }); - this._reader.read(); - return this._stream; - } -} -stream$4.default = StreamProvider; - -var sync$7 = {}; - -var sync$6 = {}; - -Object.defineProperty(sync$6, "__esModule", { value: true }); -const fsScandir$1 = out$1; -const common$7 = common$a; -const reader_1$2 = reader$1; -class SyncReader extends reader_1$2.default { - constructor() { - super(...arguments); - this._scandir = fsScandir$1.scandirSync; - this._storage = []; - this._queue = new Set(); - } - read() { - this._pushToQueue(this._root, this._settings.basePath); - this._handleQueue(); - return this._storage; - } - _pushToQueue(directory, base) { - this._queue.add({ directory, base }); - } - _handleQueue() { - for (const item of this._queue.values()) { - this._handleDirectory(item.directory, item.base); - } - } - _handleDirectory(directory, base) { - try { - const entries = this._scandir(directory, this._settings.fsScandirSettings); - for (const entry of entries) { - this._handleEntry(entry, base); - } - } - catch (error) { - this._handleError(error); - } - } - _handleError(error) { - if (!common$7.isFatalError(this._settings, error)) { - return; - } - throw error; - } - _handleEntry(entry, base) { - const fullpath = entry.path; - if (base !== undefined) { - entry.path = common$7.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); - } - if (common$7.isAppliedFilter(this._settings.entryFilter, entry)) { - this._pushToStorage(entry); - } - if (entry.dirent.isDirectory() && common$7.isAppliedFilter(this._settings.deepFilter, entry)) { - this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); - } - } - _pushToStorage(entry) { - this._storage.push(entry); - } -} -sync$6.default = SyncReader; - -Object.defineProperty(sync$7, "__esModule", { value: true }); -const sync_1$3 = sync$6; -class SyncProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new sync_1$3.default(this._root, this._settings); - } - read() { - return this._reader.read(); - } -} -sync$7.default = SyncProvider; - -var settings$1 = {}; - -Object.defineProperty(settings$1, "__esModule", { value: true }); -const path$l = path__default; -const fsScandir = out$1; -class Settings { - constructor(_options = {}) { - this._options = _options; - this.basePath = this._getValue(this._options.basePath, undefined); - this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); - this.deepFilter = this._getValue(this._options.deepFilter, null); - this.entryFilter = this._getValue(this._options.entryFilter, null); - this.errorFilter = this._getValue(this._options.errorFilter, null); - this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$l.sep); - this.fsScandirSettings = new fsScandir.Settings({ - followSymbolicLinks: this._options.followSymbolicLinks, - fs: this._options.fs, - pathSegmentSeparator: this._options.pathSegmentSeparator, - stats: this._options.stats, - throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink - }); - } - _getValue(option, value) { - return option !== null && option !== void 0 ? option : value; - } -} -settings$1.default = Settings; - -Object.defineProperty(out$2, "__esModule", { value: true }); -out$2.Settings = out$2.walkStream = out$2.walkSync = out$2.walk = void 0; -const async_1$1 = async$3; -const stream_1$4 = stream$4; -const sync_1$2 = sync$7; -const settings_1$1 = settings$1; -out$2.Settings = settings_1$1.default; -function walk$3(directory, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === 'function') { - new async_1$1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); - return; - } - new async_1$1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); -} -out$2.walk = walk$3; -function walkSync(directory, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - const provider = new sync_1$2.default(directory, settings); - return provider.read(); -} -out$2.walkSync = walkSync; -function walkStream(directory, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - const provider = new stream_1$4.default(directory, settings); - return provider.read(); -} -out$2.walkStream = walkStream; -function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings_1$1.default) { - return settingsOrOptions; - } - return new settings_1$1.default(settingsOrOptions); -} - -var reader = {}; - -Object.defineProperty(reader, "__esModule", { value: true }); -const path$k = path__default; -const fsStat$2 = out$3; -const utils$6 = utils$k; -class Reader { - constructor(_settings) { - this._settings = _settings; - this._fsStatSettings = new fsStat$2.Settings({ - followSymbolicLink: this._settings.followSymbolicLinks, - fs: this._settings.fs, - throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks - }); - } - _getFullEntryPath(filepath) { - return path$k.resolve(this._settings.cwd, filepath); - } - _makeEntry(stats, pattern) { - const entry = { - name: pattern, - path: pattern, - dirent: utils$6.fs.createDirentFromStats(pattern, stats) - }; - if (this._settings.stats) { - entry.stats = stats; - } - return entry; - } - _isFatalError(error) { - return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; - } -} -reader.default = Reader; - -Object.defineProperty(stream$5, "__esModule", { value: true }); -const stream_1$3 = require$$0__default$4; -const fsStat$1 = out$3; -const fsWalk$1 = out$2; -const reader_1$1 = reader; -class ReaderStream extends reader_1$1.default { - constructor() { - super(...arguments); - this._walkStream = fsWalk$1.walkStream; - this._stat = fsStat$1.stat; - } - dynamic(root, options) { - return this._walkStream(root, options); - } - static(patterns, options) { - const filepaths = patterns.map(this._getFullEntryPath, this); - const stream = new stream_1$3.PassThrough({ objectMode: true }); - stream._write = (index, _enc, done) => { - return this._getEntry(filepaths[index], patterns[index], options) - .then((entry) => { - if (entry !== null && options.entryFilter(entry)) { - stream.push(entry); - } - if (index === filepaths.length - 1) { - stream.end(); - } - done(); - }) - .catch(done); - }; - for (let i = 0; i < filepaths.length; i++) { - stream.write(i); - } - return stream; - } - _getEntry(filepath, pattern, options) { - return this._getStat(filepath) - .then((stats) => this._makeEntry(stats, pattern)) - .catch((error) => { - if (options.errorFilter(error)) { - return null; - } - throw error; - }); - } - _getStat(filepath) { - return new Promise((resolve, reject) => { - this._stat(filepath, this._fsStatSettings, (error, stats) => { - return error === null ? resolve(stats) : reject(error); - }); - }); - } -} -stream$5.default = ReaderStream; - -var provider = {}; - -var deep = {}; - -var partial = {}; - -var matcher = {}; - -Object.defineProperty(matcher, "__esModule", { value: true }); -const utils$5 = utils$k; -class Matcher { - constructor(_patterns, _settings, _micromatchOptions) { - this._patterns = _patterns; - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - this._storage = []; - this._fillStorage(); - } - _fillStorage() { - /** - * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). - * So, before expand patterns with brace expansion into separated patterns. - */ - const patterns = utils$5.pattern.expandPatternsWithBraceExpansion(this._patterns); - for (const pattern of patterns) { - const segments = this._getPatternSegments(pattern); - const sections = this._splitSegmentsIntoSections(segments); - this._storage.push({ - complete: sections.length <= 1, - pattern, - segments, - sections - }); - } - } - _getPatternSegments(pattern) { - const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions); - return parts.map((part) => { - const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings); - if (!dynamic) { - return { - dynamic: false, - pattern: part - }; - } - return { - dynamic: true, - pattern: part, - patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions) - }; - }); - } - _splitSegmentsIntoSections(segments) { - return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern)); - } -} -matcher.default = Matcher; - -Object.defineProperty(partial, "__esModule", { value: true }); -const matcher_1 = matcher; -class PartialMatcher extends matcher_1.default { - match(filepath) { - const parts = filepath.split('/'); - const levels = parts.length; - const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); - for (const pattern of patterns) { - const section = pattern.sections[0]; - /** - * In this case, the pattern has a globstar and we must read all directories unconditionally, - * but only if the level has reached the end of the first group. - * - * fixtures/{a,b}/** - * ^ true/false ^ always true - */ - if (!pattern.complete && levels > section.length) { - return true; - } - const match = parts.every((part, index) => { - const segment = pattern.segments[index]; - if (segment.dynamic && segment.patternRe.test(part)) { - return true; - } - if (!segment.dynamic && segment.pattern === part) { - return true; - } - return false; - }); - if (match) { - return true; - } - } - return false; - } -} -partial.default = PartialMatcher; - -Object.defineProperty(deep, "__esModule", { value: true }); -const utils$4 = utils$k; -const partial_1 = partial; -class DeepFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - } - getFilter(basePath, positive, negative) { - const matcher = this._getMatcher(positive); - const negativeRe = this._getNegativePatternsRe(negative); - return (entry) => this._filter(basePath, entry, matcher, negativeRe); - } - _getMatcher(patterns) { - return new partial_1.default(patterns, this._settings, this._micromatchOptions); - } - _getNegativePatternsRe(patterns) { - const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern); - return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); - } - _filter(basePath, entry, matcher, negativeRe) { - if (this._isSkippedByDeep(basePath, entry.path)) { - return false; - } - if (this._isSkippedSymbolicLink(entry)) { - return false; - } - const filepath = utils$4.path.removeLeadingDotSegment(entry.path); - if (this._isSkippedByPositivePatterns(filepath, matcher)) { - return false; - } - return this._isSkippedByNegativePatterns(filepath, negativeRe); - } - _isSkippedByDeep(basePath, entryPath) { - /** - * Avoid unnecessary depth calculations when it doesn't matter. - */ - if (this._settings.deep === Infinity) { - return false; - } - return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; - } - _getEntryLevel(basePath, entryPath) { - const entryPathDepth = entryPath.split('/').length; - if (basePath === '') { - return entryPathDepth; - } - const basePathDepth = basePath.split('/').length; - return entryPathDepth - basePathDepth; - } - _isSkippedSymbolicLink(entry) { - return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); - } - _isSkippedByPositivePatterns(entryPath, matcher) { - return !this._settings.baseNameMatch && !matcher.match(entryPath); - } - _isSkippedByNegativePatterns(entryPath, patternsRe) { - return !utils$4.pattern.matchAny(entryPath, patternsRe); - } -} -deep.default = DeepFilter; - -var entry$1 = {}; - -Object.defineProperty(entry$1, "__esModule", { value: true }); -const utils$3 = utils$k; -class EntryFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - this.index = new Map(); - } - getFilter(positive, negative) { - const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); - const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions); - return (entry) => this._filter(entry, positiveRe, negativeRe); - } - _filter(entry, positiveRe, negativeRe) { - if (this._settings.unique && this._isDuplicateEntry(entry)) { - return false; - } - if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { - return false; - } - if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { - return false; - } - const filepath = this._settings.baseNameMatch ? entry.name : entry.path; - const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); - if (this._settings.unique && isMatched) { - this._createIndexRecord(entry); - } - return isMatched; - } - _isDuplicateEntry(entry) { - return this.index.has(entry.path); - } - _createIndexRecord(entry) { - this.index.set(entry.path, undefined); - } - _onlyFileFilter(entry) { - return this._settings.onlyFiles && !entry.dirent.isFile(); - } - _onlyDirectoryFilter(entry) { - return this._settings.onlyDirectories && !entry.dirent.isDirectory(); - } - _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { - if (!this._settings.absolute) { - return false; - } - const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath); - return utils$3.pattern.matchAny(fullpath, patternsRe); - } - _isMatchToPatterns(entryPath, patternsRe) { - const filepath = utils$3.path.removeLeadingDotSegment(entryPath); - return utils$3.pattern.matchAny(filepath, patternsRe); - } -} -entry$1.default = EntryFilter; - -var error$4 = {}; - -Object.defineProperty(error$4, "__esModule", { value: true }); -const utils$2 = utils$k; -class ErrorFilter { - constructor(_settings) { - this._settings = _settings; - } - getFilter() { - return (error) => this._isNonFatalError(error); - } - _isNonFatalError(error) { - return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors; - } -} -error$4.default = ErrorFilter; - -var entry = {}; - -Object.defineProperty(entry, "__esModule", { value: true }); -const utils$1 = utils$k; -class EntryTransformer { - constructor(_settings) { - this._settings = _settings; - } - getTransformer() { - return (entry) => this._transform(entry); - } - _transform(entry) { - let filepath = entry.path; - if (this._settings.absolute) { - filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath); - filepath = utils$1.path.unixify(filepath); - } - if (this._settings.markDirectories && entry.dirent.isDirectory()) { - filepath += '/'; - } - if (!this._settings.objectMode) { - return filepath; - } - return Object.assign(Object.assign({}, entry), { path: filepath }); - } -} -entry.default = EntryTransformer; - -Object.defineProperty(provider, "__esModule", { value: true }); -const path$j = path__default; -const deep_1 = deep; -const entry_1 = entry$1; -const error_1 = error$4; -const entry_2 = entry; -class Provider { - constructor(_settings) { - this._settings = _settings; - this.errorFilter = new error_1.default(this._settings); - this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); - this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); - this.entryTransformer = new entry_2.default(this._settings); - } - _getRootDirectory(task) { - return path$j.resolve(this._settings.cwd, task.base); - } - _getReaderOptions(task) { - const basePath = task.base === '.' ? '' : task.base; - return { - basePath, - pathSegmentSeparator: '/', - concurrency: this._settings.concurrency, - deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), - entryFilter: this.entryFilter.getFilter(task.positive, task.negative), - errorFilter: this.errorFilter.getFilter(), - followSymbolicLinks: this._settings.followSymbolicLinks, - fs: this._settings.fs, - stats: this._settings.stats, - throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, - transform: this.entryTransformer.getTransformer() - }; - } - _getMicromatchOptions() { - return { - dot: this._settings.dot, - matchBase: this._settings.baseNameMatch, - nobrace: !this._settings.braceExpansion, - nocase: !this._settings.caseSensitiveMatch, - noext: !this._settings.extglob, - noglobstar: !this._settings.globstar, - posix: true, - strictSlashes: false - }; - } -} -provider.default = Provider; - -Object.defineProperty(async$6, "__esModule", { value: true }); -const stream_1$2 = stream$5; -const provider_1$2 = provider; -class ProviderAsync extends provider_1$2.default { - constructor() { - super(...arguments); - this._reader = new stream_1$2.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const entries = []; - return new Promise((resolve, reject) => { - const stream = this.api(root, task, options); - stream.once('error', reject); - stream.on('data', (entry) => entries.push(options.transform(entry))); - stream.once('end', () => resolve(entries)); - }); - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } -} -async$6.default = ProviderAsync; - -var stream$3 = {}; - -Object.defineProperty(stream$3, "__esModule", { value: true }); -const stream_1$1 = require$$0__default$4; -const stream_2 = stream$5; -const provider_1$1 = provider; -class ProviderStream extends provider_1$1.default { - constructor() { - super(...arguments); - this._reader = new stream_2.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const source = this.api(root, task, options); - const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } }); - source - .once('error', (error) => destination.emit('error', error)) - .on('data', (entry) => destination.emit('data', options.transform(entry))) - .once('end', () => destination.emit('end')); - destination - .once('close', () => source.destroy()); - return destination; - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } -} -stream$3.default = ProviderStream; - -var sync$5 = {}; - -var sync$4 = {}; - -Object.defineProperty(sync$4, "__esModule", { value: true }); -const fsStat = out$3; -const fsWalk = out$2; -const reader_1 = reader; -class ReaderSync extends reader_1.default { - constructor() { - super(...arguments); - this._walkSync = fsWalk.walkSync; - this._statSync = fsStat.statSync; - } - dynamic(root, options) { - return this._walkSync(root, options); - } - static(patterns, options) { - const entries = []; - for (const pattern of patterns) { - const filepath = this._getFullEntryPath(pattern); - const entry = this._getEntry(filepath, pattern, options); - if (entry === null || !options.entryFilter(entry)) { - continue; - } - entries.push(entry); - } - return entries; - } - _getEntry(filepath, pattern, options) { - try { - const stats = this._getStat(filepath); - return this._makeEntry(stats, pattern); - } - catch (error) { - if (options.errorFilter(error)) { - return null; - } - throw error; - } - } - _getStat(filepath) { - return this._statSync(filepath, this._fsStatSettings); - } -} -sync$4.default = ReaderSync; - -Object.defineProperty(sync$5, "__esModule", { value: true }); -const sync_1$1 = sync$4; -const provider_1 = provider; -class ProviderSync extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new sync_1$1.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const entries = this.api(root, task, options); - return entries.map(options.transform); - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } -} -sync$5.default = ProviderSync; - -var settings = {}; - -(function (exports) { -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; -const fs = fs__default; -const os = require$$0__default$1; -/** - * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. - * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 - */ -const CPU_COUNT = Math.max(os.cpus().length, 1); -exports.DEFAULT_FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - lstatSync: fs.lstatSync, - stat: fs.stat, - statSync: fs.statSync, - readdir: fs.readdir, - readdirSync: fs.readdirSync -}; -class Settings { - constructor(_options = {}) { - this._options = _options; - this.absolute = this._getValue(this._options.absolute, false); - this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); - this.braceExpansion = this._getValue(this._options.braceExpansion, true); - this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); - this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); - this.cwd = this._getValue(this._options.cwd, process.cwd()); - this.deep = this._getValue(this._options.deep, Infinity); - this.dot = this._getValue(this._options.dot, false); - this.extglob = this._getValue(this._options.extglob, true); - this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); - this.fs = this._getFileSystemMethods(this._options.fs); - this.globstar = this._getValue(this._options.globstar, true); - this.ignore = this._getValue(this._options.ignore, []); - this.markDirectories = this._getValue(this._options.markDirectories, false); - this.objectMode = this._getValue(this._options.objectMode, false); - this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); - this.onlyFiles = this._getValue(this._options.onlyFiles, true); - this.stats = this._getValue(this._options.stats, false); - this.suppressErrors = this._getValue(this._options.suppressErrors, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); - this.unique = this._getValue(this._options.unique, true); - if (this.onlyDirectories) { - this.onlyFiles = false; - } - if (this.stats) { - this.objectMode = true; - } - } - _getValue(option, value) { - return option === undefined ? value : option; - } - _getFileSystemMethods(methods = {}) { - return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); - } -} -exports.default = Settings; -}(settings)); - -const taskManager = tasks; -const async_1 = async$6; -const stream_1 = stream$3; -const sync_1 = sync$5; -const settings_1 = settings; -const utils = utils$k; -async function FastGlob(source, options) { - assertPatternsInput$1(source); - const works = getWorks(source, async_1.default, options); - const result = await Promise.all(works); - return utils.array.flatten(result); -} -// https://github.com/typescript-eslint/typescript-eslint/issues/60 -// eslint-disable-next-line no-redeclare -(function (FastGlob) { - function sync(source, options) { - assertPatternsInput$1(source); - const works = getWorks(source, sync_1.default, options); - return utils.array.flatten(works); - } - FastGlob.sync = sync; - function stream(source, options) { - assertPatternsInput$1(source); - const works = getWorks(source, stream_1.default, options); - /** - * The stream returned by the provider cannot work with an asynchronous iterator. - * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. - * This affects performance (+25%). I don't see best solution right now. - */ - return utils.stream.merge(works); - } - FastGlob.stream = stream; - function generateTasks(source, options) { - assertPatternsInput$1(source); - const patterns = [].concat(source); - const settings = new settings_1.default(options); - return taskManager.generate(patterns, settings); - } - FastGlob.generateTasks = generateTasks; - function isDynamicPattern(source, options) { - assertPatternsInput$1(source); - const settings = new settings_1.default(options); - return utils.pattern.isDynamicPattern(source, settings); - } - FastGlob.isDynamicPattern = isDynamicPattern; - function escapePath(source) { - assertPatternsInput$1(source); - return utils.path.escape(source); - } - FastGlob.escapePath = escapePath; -})(FastGlob || (FastGlob = {})); -function getWorks(source, _Provider, options) { - const patterns = [].concat(source); - const settings = new settings_1.default(options); - const tasks = taskManager.generate(patterns, settings); - const provider = new _Provider(settings); - return tasks.map(provider.read, provider); -} -function assertPatternsInput$1(input) { - const source = [].concat(input); - const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); - if (!isValidSource) { - throw new TypeError('Patterns must be a string (non empty) or an array of strings'); - } -} -var out = FastGlob; - -var dist$2 = {}; - -(function (exports) { -Object.defineProperty(exports, "__esModule", { value: true }); -exports.lilconfigSync = exports.lilconfig = exports.defaultLoaders = void 0; -const path = path__default; -const fs = fs__default; -const os = require$$0__default$1; -const fsReadFileAsync = fs.promises.readFile; -function getDefaultSearchPlaces(name) { - return [ - 'package.json', - `.${name}rc.json`, - `.${name}rc.js`, - `${name}.config.js`, - `.${name}rc.cjs`, - `${name}.config.cjs`, - ]; -} -function getSearchPaths(startDir, stopDir) { - return startDir - .split(path.sep) - .reduceRight((acc, _, ind, arr) => { - const currentPath = arr.slice(0, ind + 1).join(path.sep); - if (!acc.passedStopDir) - acc.searchPlaces.push(currentPath || path.sep); - if (currentPath === stopDir) - acc.passedStopDir = true; - return acc; - }, { searchPlaces: [], passedStopDir: false }).searchPlaces; -} -exports.defaultLoaders = Object.freeze({ - '.js': eval('require'), - '.json': eval('require'), - '.cjs': eval('require'), - noExt(_, content) { - return JSON.parse(content); - }, -}); -function getExtDesc(ext) { - return ext === 'noExt' ? 'files without extensions' : `extension "${ext}"`; -} -function getOptions(name, options = {}) { - const conf = { - stopDir: os.homedir(), - searchPlaces: getDefaultSearchPlaces(name), - ignoreEmptySearchPlaces: true, - transform: (x) => x, - packageProp: [name], - ...options, - loaders: { ...exports.defaultLoaders, ...options.loaders }, - }; - conf.searchPlaces.forEach(place => { - const key = path.extname(place) || 'noExt'; - const loader = conf.loaders[key]; - if (!loader) { - throw new Error(`No loader specified for ${getExtDesc(key)}, so searchPlaces item "${place}" is invalid`); - } - if (typeof loader !== 'function') { - throw new Error(`loader for ${getExtDesc(key)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`); - } - }); - return conf; -} -function getPackageProp(props, obj) { - if (typeof props === 'string' && props in obj) - return obj[props]; - return ((Array.isArray(props) ? props : props.split('.')).reduce((acc, prop) => (acc === undefined ? acc : acc[prop]), obj) || null); -} -function getSearchItems(searchPlaces, searchPaths) { - return searchPaths.reduce((acc, searchPath) => { - searchPlaces.forEach(fileName => acc.push({ - fileName, - filepath: path.join(searchPath, fileName), - loaderKey: path.extname(fileName) || 'noExt', - })); - return acc; - }, []); -} -function validateFilePath(filepath) { - if (!filepath) - throw new Error('load must pass a non-empty string'); -} -function validateLoader(loader, ext) { - if (!loader) - throw new Error(`No loader specified for extension "${ext}"`); - if (typeof loader !== 'function') - throw new Error('loader is not a function'); -} -function lilconfig(name, options) { - const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options); - return { - async search(searchFrom = process.cwd()) { - const searchPaths = getSearchPaths(searchFrom, stopDir); - const result = { - config: null, - filepath: '', - }; - const searchItems = getSearchItems(searchPlaces, searchPaths); - for (const { fileName, filepath, loaderKey } of searchItems) { - try { - await fs.promises.access(filepath); - } - catch (_a) { - continue; - } - const content = String(await fsReadFileAsync(filepath)); - const loader = loaders[loaderKey]; - if (fileName === 'package.json') { - const pkg = loader(filepath, content); - const maybeConfig = getPackageProp(packageProp, pkg); - if (maybeConfig != null) { - result.config = maybeConfig; - result.filepath = filepath; - break; - } - continue; - } - const isEmpty = content.trim() === ''; - if (isEmpty && ignoreEmptySearchPlaces) - continue; - if (isEmpty) { - result.isEmpty = true; - result.config = undefined; - } - else { - validateLoader(loader, loaderKey); - result.config = loader(filepath, content); - } - result.filepath = filepath; - break; - } - if (result.filepath === '' && result.config === null) - return transform(null); - return transform(result); - }, - async load(filepath) { - validateFilePath(filepath); - const { base, ext } = path.parse(filepath); - const loaderKey = ext || 'noExt'; - const loader = loaders[loaderKey]; - validateLoader(loader, loaderKey); - const content = String(await fsReadFileAsync(filepath)); - if (base === 'package.json') { - const pkg = await loader(filepath, content); - return transform({ - config: getPackageProp(packageProp, pkg), - filepath, - }); - } - const result = { - config: null, - filepath, - }; - const isEmpty = content.trim() === ''; - if (isEmpty && ignoreEmptySearchPlaces) - return transform({ - config: undefined, - filepath, - isEmpty: true, - }); - result.config = isEmpty - ? undefined - : await loader(filepath, content); - return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result); - }, - }; -} -exports.lilconfig = lilconfig; -function lilconfigSync(name, options) { - const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options); - return { - search(searchFrom = process.cwd()) { - const searchPaths = getSearchPaths(searchFrom, stopDir); - const result = { - config: null, - filepath: '', - }; - const searchItems = getSearchItems(searchPlaces, searchPaths); - for (const { fileName, filepath, loaderKey } of searchItems) { - try { - fs.accessSync(filepath); - } - catch (_a) { - continue; - } - const loader = loaders[loaderKey]; - const content = String(fs.readFileSync(filepath)); - if (fileName === 'package.json') { - const pkg = loader(filepath, content); - const maybeConfig = getPackageProp(packageProp, pkg); - if (maybeConfig != null) { - result.config = maybeConfig; - result.filepath = filepath; - break; - } - continue; - } - const isEmpty = content.trim() === ''; - if (isEmpty && ignoreEmptySearchPlaces) - continue; - if (isEmpty) { - result.isEmpty = true; - result.config = undefined; - } - else { - validateLoader(loader, loaderKey); - result.config = loader(filepath, content); - } - result.filepath = filepath; - break; - } - if (result.filepath === '' && result.config === null) - return transform(null); - return transform(result); - }, - load(filepath) { - validateFilePath(filepath); - const { base, ext } = path.parse(filepath); - const loaderKey = ext || 'noExt'; - const loader = loaders[loaderKey]; - validateLoader(loader, loaderKey); - const content = String(fs.readFileSync(filepath)); - if (base === 'package.json') { - const pkg = loader(filepath, content); - return transform({ - config: getPackageProp(packageProp, pkg), - filepath, - }); - } - const result = { - config: null, - filepath, - }; - const isEmpty = content.trim() === ''; - if (isEmpty && ignoreEmptySearchPlaces) - return transform({ - filepath, - config: undefined, - isEmpty: true, - }); - result.config = isEmpty ? undefined : loader(filepath, content); - return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result); - }, - }; -} -exports.lilconfigSync = lilconfigSync; -}(dist$2)); - -var dist$1 = {}; - -var parseCst$1 = {}; - -var PlainValueEc8e588e = {}; - -const Char = { - ANCHOR: '&', - COMMENT: '#', - TAG: '!', - DIRECTIVES_END: '-', - DOCUMENT_END: '.' -}; -const Type = { - ALIAS: 'ALIAS', - BLANK_LINE: 'BLANK_LINE', - BLOCK_FOLDED: 'BLOCK_FOLDED', - BLOCK_LITERAL: 'BLOCK_LITERAL', - COMMENT: 'COMMENT', - DIRECTIVE: 'DIRECTIVE', - DOCUMENT: 'DOCUMENT', - FLOW_MAP: 'FLOW_MAP', - FLOW_SEQ: 'FLOW_SEQ', - MAP: 'MAP', - MAP_KEY: 'MAP_KEY', - MAP_VALUE: 'MAP_VALUE', - PLAIN: 'PLAIN', - QUOTE_DOUBLE: 'QUOTE_DOUBLE', - QUOTE_SINGLE: 'QUOTE_SINGLE', - SEQ: 'SEQ', - SEQ_ITEM: 'SEQ_ITEM' -}; -const defaultTagPrefix = 'tag:yaml.org,2002:'; -const defaultTags = { - MAP: 'tag:yaml.org,2002:map', - SEQ: 'tag:yaml.org,2002:seq', - STR: 'tag:yaml.org,2002:str' -}; - -function findLineStarts(src) { - const ls = [0]; - let offset = src.indexOf('\n'); - - while (offset !== -1) { - offset += 1; - ls.push(offset); - offset = src.indexOf('\n', offset); - } - - return ls; -} - -function getSrcInfo(cst) { - let lineStarts, src; - - if (typeof cst === 'string') { - lineStarts = findLineStarts(cst); - src = cst; - } else { - if (Array.isArray(cst)) cst = cst[0]; - - if (cst && cst.context) { - if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src); - lineStarts = cst.lineStarts; - src = cst.context.src; - } - } - - return { - lineStarts, - src - }; -} -/** - * @typedef {Object} LinePos - One-indexed position in the source - * @property {number} line - * @property {number} col - */ - -/** - * Determine the line/col position matching a character offset. - * - * Accepts a source string or a CST document as the second parameter. With - * the latter, starting indices for lines are cached in the document as - * `lineStarts: number[]`. - * - * Returns a one-indexed `{ line, col }` location if found, or - * `undefined` otherwise. - * - * @param {number} offset - * @param {string|Document|Document[]} cst - * @returns {?LinePos} - */ - - -function getLinePos(offset, cst) { - if (typeof offset !== 'number' || offset < 0) return null; - const { - lineStarts, - src - } = getSrcInfo(cst); - if (!lineStarts || !src || offset > src.length) return null; - - for (let i = 0; i < lineStarts.length; ++i) { - const start = lineStarts[i]; - - if (offset < start) { - return { - line: i, - col: offset - lineStarts[i - 1] + 1 - }; - } - - if (offset === start) return { - line: i + 1, - col: 1 - }; - } - - const line = lineStarts.length; - return { - line, - col: offset - lineStarts[line - 1] + 1 - }; -} -/** - * Get a specified line from the source. - * - * Accepts a source string or a CST document as the second parameter. With - * the latter, starting indices for lines are cached in the document as - * `lineStarts: number[]`. - * - * Returns the line as a string if found, or `null` otherwise. - * - * @param {number} line One-indexed line number - * @param {string|Document|Document[]} cst - * @returns {?string} - */ - -function getLine(line, cst) { - const { - lineStarts, - src - } = getSrcInfo(cst); - if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null; - const start = lineStarts[line - 1]; - let end = lineStarts[line]; // undefined for last line; that's ok for slice() - - while (end && end > start && src[end - 1] === '\n') --end; - - return src.slice(start, end); -} -/** - * Pretty-print the starting line from the source indicated by the range `pos` - * - * Trims output to `maxWidth` chars while keeping the starting column visible, - * using `…` at either end to indicate dropped characters. - * - * Returns a two-line string (or `null`) with `\n` as separator; the second line - * will hold appropriately indented `^` marks indicating the column range. - * - * @param {Object} pos - * @param {LinePos} pos.start - * @param {LinePos} [pos.end] - * @param {string|Document|Document[]*} cst - * @param {number} [maxWidth=80] - * @returns {?string} - */ - -function getPrettyContext({ - start, - end -}, cst, maxWidth = 80) { - let src = getLine(start.line, cst); - if (!src) return null; - let { - col - } = start; - - if (src.length > maxWidth) { - if (col <= maxWidth - 10) { - src = src.substr(0, maxWidth - 1) + '…'; - } else { - const halfWidth = Math.round(maxWidth / 2); - if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…'; - col -= src.length - maxWidth; - src = '…' + src.substr(1 - maxWidth); - } - } - - let errLen = 1; - let errEnd = ''; - - if (end) { - if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) { - errLen = end.col - start.col; - } else { - errLen = Math.min(src.length + 1, maxWidth) - col; - errEnd = '…'; - } - } - - const offset = col > 1 ? ' '.repeat(col - 1) : ''; - const err = '^'.repeat(errLen); - return `${src}\n${offset}${err}${errEnd}`; -} - -class Range { - static copy(orig) { - return new Range(orig.start, orig.end); - } - - constructor(start, end) { - this.start = start; - this.end = end || start; - } - - isEmpty() { - return typeof this.start !== 'number' || !this.end || this.end <= this.start; - } - /** - * Set `origStart` and `origEnd` to point to the original source range for - * this node, which may differ due to dropped CR characters. - * - * @param {number[]} cr - Positions of dropped CR characters - * @param {number} offset - Starting index of `cr` from the last call - * @returns {number} - The next offset, matching the one found for `origStart` - */ - - - setOrigRange(cr, offset) { - const { - start, - end - } = this; - - if (cr.length === 0 || end <= cr[0]) { - this.origStart = start; - this.origEnd = end; - return offset; - } - - let i = offset; - - while (i < cr.length) { - if (cr[i] > start) break;else ++i; - } - - this.origStart = start + i; - const nextOffset = i; - - while (i < cr.length) { - // if end was at \n, it should now be at \r - if (cr[i] >= end) break;else ++i; - } - - this.origEnd = end + i; - return nextOffset; - } - -} - -/** Root class of all nodes */ - -class Node$2 { - static addStringTerminator(src, offset, str) { - if (str[str.length - 1] === '\n') return str; - const next = Node$2.endOfWhiteSpace(src, offset); - return next >= src.length || src[next] === '\n' ? str + '\n' : str; - } // ^(---|...) - - - static atDocumentBoundary(src, offset, sep) { - const ch0 = src[offset]; - if (!ch0) return true; - const prev = src[offset - 1]; - if (prev && prev !== '\n') return false; - - if (sep) { - if (ch0 !== sep) return false; - } else { - if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false; - } - - const ch1 = src[offset + 1]; - const ch2 = src[offset + 2]; - if (ch1 !== ch0 || ch2 !== ch0) return false; - const ch3 = src[offset + 3]; - return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' '; - } - - static endOfIdentifier(src, offset) { - let ch = src[offset]; - const isVerbatim = ch === '<'; - const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ',']; - - while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1]; - - if (isVerbatim && ch === '>') offset += 1; - return offset; - } - - static endOfIndent(src, offset) { - let ch = src[offset]; - - while (ch === ' ') ch = src[offset += 1]; - - return offset; - } - - static endOfLine(src, offset) { - let ch = src[offset]; - - while (ch && ch !== '\n') ch = src[offset += 1]; - - return offset; - } - - static endOfWhiteSpace(src, offset) { - let ch = src[offset]; - - while (ch === '\t' || ch === ' ') ch = src[offset += 1]; - - return offset; - } - - static startOfLine(src, offset) { - let ch = src[offset - 1]; - if (ch === '\n') return offset; - - while (ch && ch !== '\n') ch = src[offset -= 1]; - - return offset + 1; - } - /** - * End of indentation, or null if the line's indent level is not more - * than `indent` - * - * @param {string} src - * @param {number} indent - * @param {number} lineStart - * @returns {?number} - */ - - - static endOfBlockIndent(src, indent, lineStart) { - const inEnd = Node$2.endOfIndent(src, lineStart); - - if (inEnd > lineStart + indent) { - return inEnd; - } else { - const wsEnd = Node$2.endOfWhiteSpace(src, inEnd); - const ch = src[wsEnd]; - if (!ch || ch === '\n') return wsEnd; - } - - return null; - } - - static atBlank(src, offset, endAsBlank) { - const ch = src[offset]; - return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch; - } - - static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { - if (!ch || indentDiff < 0) return false; - if (indentDiff > 0) return true; - return indicatorAsIndent && ch === '-'; - } // should be at line or string end, or at next non-whitespace char - - - static normalizeOffset(src, offset) { - const ch = src[offset]; - return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node$2.endOfWhiteSpace(src, offset); - } // fold single newline into space, multiple newlines to N - 1 newlines - // presumes src[offset] === '\n' - - - static foldNewline(src, offset, indent) { - let inCount = 0; - let error = false; - let fold = ''; - let ch = src[offset + 1]; - - while (ch === ' ' || ch === '\t' || ch === '\n') { - switch (ch) { - case '\n': - inCount = 0; - offset += 1; - fold += '\n'; - break; - - case '\t': - if (inCount <= indent) error = true; - offset = Node$2.endOfWhiteSpace(src, offset + 2) - 1; - break; - - case ' ': - inCount += 1; - offset += 1; - break; - } - - ch = src[offset + 1]; - } - - if (!fold) fold = ' '; - if (ch && inCount <= indent) error = true; - return { - fold, - offset, - error - }; - } - - constructor(type, props, context) { - Object.defineProperty(this, 'context', { - value: context || null, - writable: true - }); - this.error = null; - this.range = null; - this.valueRange = null; - this.props = props || []; - this.type = type; - this.value = null; - } - - getPropValue(idx, key, skipKey) { - if (!this.context) return null; - const { - src - } = this.context; - const prop = this.props[idx]; - return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; - } - - get anchor() { - for (let i = 0; i < this.props.length; ++i) { - const anchor = this.getPropValue(i, Char.ANCHOR, true); - if (anchor != null) return anchor; - } - - return null; - } - - get comment() { - const comments = []; - - for (let i = 0; i < this.props.length; ++i) { - const comment = this.getPropValue(i, Char.COMMENT, true); - if (comment != null) comments.push(comment); - } - - return comments.length > 0 ? comments.join('\n') : null; - } - - commentHasRequiredWhitespace(start) { - const { - src - } = this.context; - if (this.header && start === this.header.end) return false; - if (!this.valueRange) return false; - const { - end - } = this.valueRange; - return start !== end || Node$2.atBlank(src, end - 1); - } - - get hasComment() { - if (this.context) { - const { - src - } = this.context; - - for (let i = 0; i < this.props.length; ++i) { - if (src[this.props[i].start] === Char.COMMENT) return true; - } - } - - return false; - } - - get hasProps() { - if (this.context) { - const { - src - } = this.context; - - for (let i = 0; i < this.props.length; ++i) { - if (src[this.props[i].start] !== Char.COMMENT) return true; - } - } - - return false; - } - - get includesTrailingLines() { - return false; - } - - get jsonLike() { - const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; - return jsonLikeTypes.indexOf(this.type) !== -1; - } - - get rangeAsLinePos() { - if (!this.range || !this.context) return undefined; - const start = getLinePos(this.range.start, this.context.root); - if (!start) return undefined; - const end = getLinePos(this.range.end, this.context.root); - return { - start, - end - }; - } - - get rawValue() { - if (!this.valueRange || !this.context) return null; - const { - start, - end - } = this.valueRange; - return this.context.src.slice(start, end); - } - - get tag() { - for (let i = 0; i < this.props.length; ++i) { - const tag = this.getPropValue(i, Char.TAG, false); - - if (tag != null) { - if (tag[1] === '<') { - return { - verbatim: tag.slice(2, -1) - }; - } else { - // eslint-disable-next-line no-unused-vars - const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/); - return { - handle, - suffix - }; - } - } - } - - return null; - } - - get valueRangeContainsNewline() { - if (!this.valueRange || !this.context) return false; - const { - start, - end - } = this.valueRange; - const { - src - } = this.context; - - for (let i = start; i < end; ++i) { - if (src[i] === '\n') return true; - } - - return false; - } - - parseComment(start) { - const { - src - } = this.context; - - if (src[start] === Char.COMMENT) { - const end = Node$2.endOfLine(src, start + 1); - const commentRange = new Range(start, end); - this.props.push(commentRange); - return end; - } - - return start; - } - /** - * Populates the `origStart` and `origEnd` values of all ranges for this - * node. Extended by child classes to handle descendant nodes. - * - * @param {number[]} cr - Positions of dropped CR characters - * @param {number} offset - Starting index of `cr` from the last call - * @returns {number} - The next offset, matching the one found for `origStart` - */ - - - setOrigRanges(cr, offset) { - if (this.range) offset = this.range.setOrigRange(cr, offset); - if (this.valueRange) this.valueRange.setOrigRange(cr, offset); - this.props.forEach(prop => prop.setOrigRange(cr, offset)); - return offset; - } - - toString() { - const { - context: { - src - }, - range, - value - } = this; - if (value != null) return value; - const str = src.slice(range.start, range.end); - return Node$2.addStringTerminator(src, range.end, str); - } - -} - -class YAMLError extends Error { - constructor(name, source, message) { - if (!message || !(source instanceof Node$2)) throw new Error(`Invalid arguments for new ${name}`); - super(); - this.name = name; - this.message = message; - this.source = source; - } - - makePretty() { - if (!this.source) return; - this.nodeType = this.source.type; - const cst = this.source.context && this.source.context.root; - - if (typeof this.offset === 'number') { - this.range = new Range(this.offset, this.offset + 1); - const start = cst && getLinePos(this.offset, cst); - - if (start) { - const end = { - line: start.line, - col: start.col + 1 - }; - this.linePos = { - start, - end - }; - } - - delete this.offset; - } else { - this.range = this.source.range; - this.linePos = this.source.rangeAsLinePos; - } - - if (this.linePos) { - const { - line, - col - } = this.linePos.start; - this.message += ` at line ${line}, column ${col}`; - const ctx = cst && getPrettyContext(this.linePos, cst); - if (ctx) this.message += `:\n\n${ctx}\n`; - } - - delete this.source; - } - -} -class YAMLReferenceError extends YAMLError { - constructor(source, message) { - super('YAMLReferenceError', source, message); - } - -} -class YAMLSemanticError extends YAMLError { - constructor(source, message) { - super('YAMLSemanticError', source, message); - } - -} -class YAMLSyntaxError extends YAMLError { - constructor(source, message) { - super('YAMLSyntaxError', source, message); - } - -} -class YAMLWarning extends YAMLError { - constructor(source, message) { - super('YAMLWarning', source, message); - } - -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -class PlainValue$6 extends Node$2 { - static endOfLine(src, start, inFlow) { - let ch = src[start]; - let offset = start; - - while (ch && ch !== '\n') { - if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break; - const next = src[offset + 1]; - if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break; - if ((ch === ' ' || ch === '\t') && next === '#') break; - offset += 1; - ch = next; - } - - return offset; - } - - get strValue() { - if (!this.valueRange || !this.context) return null; - let { - start, - end - } = this.valueRange; - const { - src - } = this.context; - let ch = src[end - 1]; - - while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1]; - - let str = ''; - - for (let i = start; i < end; ++i) { - const ch = src[i]; - - if (ch === '\n') { - const { - fold, - offset - } = Node$2.foldNewline(src, i, -1); - str += fold; - i = offset; - } else if (ch === ' ' || ch === '\t') { - // trim trailing whitespace - const wsStart = i; - let next = src[i + 1]; - - while (i < end && (next === ' ' || next === '\t')) { - i += 1; - next = src[i + 1]; - } - - if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; - } else { - str += ch; - } - } - - const ch0 = src[start]; - - switch (ch0) { - case '\t': - { - const msg = 'Plain value cannot start with a tab character'; - const errors = [new YAMLSemanticError(this, msg)]; - return { - errors, - str - }; - } - - case '@': - case '`': - { - const msg = `Plain value cannot start with reserved character ${ch0}`; - const errors = [new YAMLSemanticError(this, msg)]; - return { - errors, - str - }; - } - - default: - return str; - } - } - - parseBlockValue(start) { - const { - indent, - inFlow, - src - } = this.context; - let offset = start; - let valueEnd = start; - - for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { - if (Node$2.atDocumentBoundary(src, offset + 1)) break; - const end = Node$2.endOfBlockIndent(src, indent, offset + 1); - if (end === null || src[end] === '#') break; - - if (src[end] === '\n') { - offset = end; - } else { - valueEnd = PlainValue$6.endOfLine(src, end, inFlow); - offset = valueEnd; - } - } - - if (this.valueRange.isEmpty()) this.valueRange.start = start; - this.valueRange.end = valueEnd; - return valueEnd; - } - /** - * Parses a plain value from the source - * - * Accepted forms are: - * ``` - * #comment - * - * first line - * - * first line #comment - * - * first line - * block - * lines - * - * #comment - * block - * lines - * ``` - * where block lines are empty or have an indent level greater than `indent`. - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar, may be `\n` - */ - - - parse(context, start) { - this.context = context; - const { - inFlow, - src - } = context; - let offset = start; - const ch = src[offset]; - - if (ch && ch !== '#' && ch !== '\n') { - offset = PlainValue$6.endOfLine(src, start, inFlow); - } - - this.valueRange = new Range(start, offset); - offset = Node$2.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - - if (!this.hasComment || this.valueRange.isEmpty()) { - offset = this.parseBlockValue(offset); - } - - return offset; - } - -} - -PlainValueEc8e588e.Char = Char; -PlainValueEc8e588e.Node = Node$2; -PlainValueEc8e588e.PlainValue = PlainValue$6; -PlainValueEc8e588e.Range = Range; -PlainValueEc8e588e.Type = Type; -PlainValueEc8e588e.YAMLError = YAMLError; -PlainValueEc8e588e.YAMLReferenceError = YAMLReferenceError; -PlainValueEc8e588e.YAMLSemanticError = YAMLSemanticError; -PlainValueEc8e588e.YAMLSyntaxError = YAMLSyntaxError; -PlainValueEc8e588e.YAMLWarning = YAMLWarning; -PlainValueEc8e588e._defineProperty = _defineProperty; -PlainValueEc8e588e.defaultTagPrefix = defaultTagPrefix; -PlainValueEc8e588e.defaultTags = defaultTags; - -var PlainValue$5 = PlainValueEc8e588e; - -class BlankLine extends PlainValue$5.Node { - constructor() { - super(PlainValue$5.Type.BLANK_LINE); - } - /* istanbul ignore next */ - - - get includesTrailingLines() { - // This is never called from anywhere, but if it were, - // this is the value it should return. - return true; - } - /** - * Parses a blank line from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first \n character - * @returns {number} - Index of the character after this - */ - - - parse(context, start) { - this.context = context; - this.range = new PlainValue$5.Range(start, start + 1); - return start + 1; - } - -} - -class CollectionItem extends PlainValue$5.Node { - constructor(type, props) { - super(type, props); - this.node = null; - } - - get includesTrailingLines() { - return !!this.node && this.node.includesTrailingLines; - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - - - parse(context, start) { - this.context = context; - const { - parseNode, - src - } = context; - let { - atLineStart, - lineStart - } = context; - if (!atLineStart && this.type === PlainValue$5.Type.SEQ_ITEM) this.error = new PlainValue$5.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line'); - const indent = atLineStart ? start - lineStart : context.indent; - let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1); - let ch = src[offset]; - const inlineComment = ch === '#'; - const comments = []; - let blankLine = null; - - while (ch === '\n' || ch === '#') { - if (ch === '#') { - const end = PlainValue$5.Node.endOfLine(src, offset + 1); - comments.push(new PlainValue$5.Range(offset, end)); - offset = end; - } else { - atLineStart = true; - lineStart = offset + 1; - const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); - - if (src[wsEnd] === '\n' && comments.length === 0) { - blankLine = new BlankLine(); - lineStart = blankLine.parse({ - src - }, lineStart); - } - - offset = PlainValue$5.Node.endOfIndent(src, lineStart); - } - - ch = src[offset]; - } - - if (PlainValue$5.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValue$5.Type.SEQ_ITEM)) { - this.node = parseNode({ - atLineStart, - inCollection: false, - indent, - lineStart, - parent: this - }, offset); - } else if (ch && lineStart > start + 1) { - offset = lineStart - 1; - } - - if (this.node) { - if (blankLine) { - // Only blank lines preceding non-empty nodes are captured. Note that - // this means that collection item range start indices do not always - // increase monotonically. -- eemeli/yaml#126 - const items = context.parent.items || context.parent.contents; - if (items) items.push(blankLine); - } - - if (comments.length) Array.prototype.push.apply(this.props, comments); - offset = this.node.range.end; - } else { - if (inlineComment) { - const c = comments[0]; - this.props.push(c); - offset = c.end; - } else { - offset = PlainValue$5.Node.endOfLine(src, start + 1); - } - } - - const end = this.node ? this.node.valueRange.end : offset; - this.valueRange = new PlainValue$5.Range(start, end); - return offset; - } - - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - return this.node ? this.node.setOrigRanges(cr, offset) : offset; - } - - toString() { - const { - context: { - src - }, - node, - range, - value - } = this; - if (value != null) return value; - const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end); - return PlainValue$5.Node.addStringTerminator(src, range.end, str); - } - -} - -class Comment extends PlainValue$5.Node { - constructor() { - super(PlainValue$5.Type.COMMENT); - } - /** - * Parses a comment line from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - - - parse(context, start) { - this.context = context; - const offset = this.parseComment(start); - this.range = new PlainValue$5.Range(start, offset); - return offset; - } - -} - -function grabCollectionEndComments(node) { - let cnode = node; - - while (cnode instanceof CollectionItem) cnode = cnode.node; - - if (!(cnode instanceof Collection$1)) return null; - const len = cnode.items.length; - let ci = -1; - - for (let i = len - 1; i >= 0; --i) { - const n = cnode.items[i]; - - if (n.type === PlainValue$5.Type.COMMENT) { - // Keep sufficiently indented comments with preceding node - const { - indent, - lineStart - } = n.context; - if (indent > 0 && n.range.start >= lineStart + indent) break; - ci = i; - } else if (n.type === PlainValue$5.Type.BLANK_LINE) ci = i;else break; - } - - if (ci === -1) return null; - const ca = cnode.items.splice(ci, len - ci); - const prevEnd = ca[0].range.start; - - while (true) { - cnode.range.end = prevEnd; - if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd; - if (cnode === node) break; - cnode = cnode.context.parent; - } - - return ca; -} -class Collection$1 extends PlainValue$5.Node { - static nextContentHasIndent(src, offset, indent) { - const lineStart = PlainValue$5.Node.endOfLine(src, offset) + 1; - offset = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); - const ch = src[offset]; - if (!ch) return false; - if (offset >= lineStart + indent) return true; - if (ch !== '#' && ch !== '\n') return false; - return Collection$1.nextContentHasIndent(src, offset, indent); - } - - constructor(firstItem) { - super(firstItem.type === PlainValue$5.Type.SEQ_ITEM ? PlainValue$5.Type.SEQ : PlainValue$5.Type.MAP); - - for (let i = firstItem.props.length - 1; i >= 0; --i) { - if (firstItem.props[i].start < firstItem.context.lineStart) { - // props on previous line are assumed by the collection - this.props = firstItem.props.slice(0, i + 1); - firstItem.props = firstItem.props.slice(i + 1); - const itemRange = firstItem.props[0] || firstItem.valueRange; - firstItem.range.start = itemRange.start; - break; - } - } - - this.items = [firstItem]; - const ec = grabCollectionEndComments(firstItem); - if (ec) Array.prototype.push.apply(this.items, ec); - } - - get includesTrailingLines() { - return this.items.length > 0; - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - - - parse(context, start) { - this.context = context; - const { - parseNode, - src - } = context; // It's easier to recalculate lineStart here rather than tracking down the - // last context from which to read it -- eemeli/yaml#2 - - let lineStart = PlainValue$5.Node.startOfLine(src, start); - const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling - // -- eemeli/yaml#17 - - firstItem.context.parent = this; - this.valueRange = PlainValue$5.Range.copy(firstItem.valueRange); - const indent = firstItem.range.start - firstItem.context.lineStart; - let offset = start; - offset = PlainValue$5.Node.normalizeOffset(src, offset); - let ch = src[offset]; - let atLineStart = PlainValue$5.Node.endOfWhiteSpace(src, lineStart) === offset; - let prevIncludesTrailingLines = false; - - while (ch) { - while (ch === '\n' || ch === '#') { - if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) { - const blankLine = new BlankLine(); - offset = blankLine.parse({ - src - }, offset); - this.valueRange.end = offset; - - if (offset >= src.length) { - ch = null; - break; - } - - this.items.push(blankLine); - offset -= 1; // blankLine.parse() consumes terminal newline - } else if (ch === '#') { - if (offset < lineStart + indent && !Collection$1.nextContentHasIndent(src, offset, indent)) { - return offset; - } - - const comment = new Comment(); - offset = comment.parse({ - indent, - lineStart, - src - }, offset); - this.items.push(comment); - this.valueRange.end = offset; - - if (offset >= src.length) { - ch = null; - break; - } - } - - lineStart = offset + 1; - offset = PlainValue$5.Node.endOfIndent(src, lineStart); - - if (PlainValue$5.Node.atBlank(src, offset)) { - const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, offset); - const next = src[wsEnd]; - - if (!next || next === '\n' || next === '#') { - offset = wsEnd; - } - } - - ch = src[offset]; - atLineStart = true; - } - - if (!ch) { - break; - } - - if (offset !== lineStart + indent && (atLineStart || ch !== ':')) { - if (offset < lineStart + indent) { - if (lineStart > start) offset = lineStart; - break; - } else if (!this.error) { - const msg = 'All collection items must start at the same column'; - this.error = new PlainValue$5.YAMLSyntaxError(this, msg); - } - } - - if (firstItem.type === PlainValue$5.Type.SEQ_ITEM) { - if (ch !== '-') { - if (lineStart > start) offset = lineStart; - break; - } - } else if (ch === '-' && !this.error) { - // map key may start with -, as long as it's followed by a non-whitespace char - const next = src[offset + 1]; - - if (!next || next === '\n' || next === '\t' || next === ' ') { - const msg = 'A collection cannot be both a mapping and a sequence'; - this.error = new PlainValue$5.YAMLSyntaxError(this, msg); - } - } - - const node = parseNode({ - atLineStart, - inCollection: true, - indent, - lineStart, - parent: this - }, offset); - if (!node) return offset; // at next document start - - this.items.push(node); - this.valueRange.end = node.valueRange.end; - offset = PlainValue$5.Node.normalizeOffset(src, node.range.end); - ch = src[offset]; - atLineStart = false; - prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range - // has advanced to check the current line's indentation level - // -- eemeli/yaml#10 & eemeli/yaml#38 - - if (ch) { - let ls = offset - 1; - let prev = src[ls]; - - while (prev === ' ' || prev === '\t') prev = src[--ls]; - - if (prev === '\n') { - lineStart = ls + 1; - atLineStart = true; - } - } - - const ec = grabCollectionEndComments(node); - if (ec) Array.prototype.push.apply(this.items, ec); - } - - return offset; - } - - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - this.items.forEach(node => { - offset = node.setOrigRanges(cr, offset); - }); - return offset; - } - - toString() { - const { - context: { - src - }, - items, - range, - value - } = this; - if (value != null) return value; - let str = src.slice(range.start, items[0].range.start) + String(items[0]); - - for (let i = 1; i < items.length; ++i) { - const item = items[i]; - const { - atLineStart, - indent - } = item.context; - if (atLineStart) for (let i = 0; i < indent; ++i) str += ' '; - str += String(item); - } - - return PlainValue$5.Node.addStringTerminator(src, range.end, str); - } - -} - -class Directive extends PlainValue$5.Node { - constructor() { - super(PlainValue$5.Type.DIRECTIVE); - this.name = null; - } - - get parameters() { - const raw = this.rawValue; - return raw ? raw.trim().split(/[ \t]+/) : []; - } - - parseName(start) { - const { - src - } = this.context; - let offset = start; - let ch = src[offset]; - - while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1]; - - this.name = src.slice(start, offset); - return offset; - } - - parseParameters(start) { - const { - src - } = this.context; - let offset = start; - let ch = src[offset]; - - while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1]; - - this.valueRange = new PlainValue$5.Range(start, offset); - return offset; - } - - parse(context, start) { - this.context = context; - let offset = this.parseName(start + 1); - offset = this.parseParameters(offset); - offset = this.parseComment(offset); - this.range = new PlainValue$5.Range(start, offset); - return offset; - } - -} - -class Document$3 extends PlainValue$5.Node { - static startCommentOrEndBlankLine(src, start) { - const offset = PlainValue$5.Node.endOfWhiteSpace(src, start); - const ch = src[offset]; - return ch === '#' || ch === '\n' ? offset : start; - } - - constructor() { - super(PlainValue$5.Type.DOCUMENT); - this.directives = null; - this.contents = null; - this.directivesEndMarker = null; - this.documentEndMarker = null; - } - - parseDirectives(start) { - const { - src - } = this.context; - this.directives = []; - let atLineStart = true; - let hasDirectives = false; - let offset = start; - - while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DIRECTIVES_END)) { - offset = Document$3.startCommentOrEndBlankLine(src, offset); - - switch (src[offset]) { - case '\n': - if (atLineStart) { - const blankLine = new BlankLine(); - offset = blankLine.parse({ - src - }, offset); - - if (offset < src.length) { - this.directives.push(blankLine); - } - } else { - offset += 1; - atLineStart = true; - } - - break; - - case '#': - { - const comment = new Comment(); - offset = comment.parse({ - src - }, offset); - this.directives.push(comment); - atLineStart = false; - } - break; - - case '%': - { - const directive = new Directive(); - offset = directive.parse({ - parent: this, - src - }, offset); - this.directives.push(directive); - hasDirectives = true; - atLineStart = false; - } - break; - - default: - if (hasDirectives) { - this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line'); - } else if (this.directives.length > 0) { - this.contents = this.directives; - this.directives = []; - } - - return offset; - } - } - - if (src[offset]) { - this.directivesEndMarker = new PlainValue$5.Range(offset, offset + 3); - return offset + 3; - } - - if (hasDirectives) { - this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line'); - } else if (this.directives.length > 0) { - this.contents = this.directives; - this.directives = []; - } - - return offset; - } - - parseContents(start) { - const { - parseNode, - src - } = this.context; - if (!this.contents) this.contents = []; - let lineStart = start; - - while (src[lineStart - 1] === '-') lineStart -= 1; - - let offset = PlainValue$5.Node.endOfWhiteSpace(src, start); - let atLineStart = lineStart === start; - this.valueRange = new PlainValue$5.Range(offset); - - while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DOCUMENT_END)) { - switch (src[offset]) { - case '\n': - if (atLineStart) { - const blankLine = new BlankLine(); - offset = blankLine.parse({ - src - }, offset); - - if (offset < src.length) { - this.contents.push(blankLine); - } - } else { - offset += 1; - atLineStart = true; - } - - lineStart = offset; - break; - - case '#': - { - const comment = new Comment(); - offset = comment.parse({ - src - }, offset); - this.contents.push(comment); - atLineStart = false; - } - break; - - default: - { - const iEnd = PlainValue$5.Node.endOfIndent(src, offset); - const context = { - atLineStart, - indent: -1, - inFlow: false, - inCollection: false, - lineStart, - parent: this - }; - const node = parseNode(context, iEnd); - if (!node) return this.valueRange.end = iEnd; // at next document start - - this.contents.push(node); - offset = node.range.end; - atLineStart = false; - const ec = grabCollectionEndComments(node); - if (ec) Array.prototype.push.apply(this.contents, ec); - } - } - - offset = Document$3.startCommentOrEndBlankLine(src, offset); - } - - this.valueRange.end = offset; - - if (src[offset]) { - this.documentEndMarker = new PlainValue$5.Range(offset, offset + 3); - offset += 3; - - if (src[offset]) { - offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); - - if (src[offset] === '#') { - const comment = new Comment(); - offset = comment.parse({ - src - }, offset); - this.contents.push(comment); - } - - switch (src[offset]) { - case '\n': - offset += 1; - break; - - case undefined: - break; - - default: - this.error = new PlainValue$5.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix'); - } - } - } - - return offset; - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - - - parse(context, start) { - context.root = this; - this.context = context; - const { - src - } = context; - let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM - - offset = this.parseDirectives(offset); - offset = this.parseContents(offset); - return offset; - } - - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - this.directives.forEach(node => { - offset = node.setOrigRanges(cr, offset); - }); - if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset); - this.contents.forEach(node => { - offset = node.setOrigRanges(cr, offset); - }); - if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset); - return offset; - } - - toString() { - const { - contents, - directives, - value - } = this; - if (value != null) return value; - let str = directives.join(''); - - if (contents.length > 0) { - if (directives.length > 0 || contents[0].type === PlainValue$5.Type.COMMENT) str += '---\n'; - str += contents.join(''); - } - - if (str[str.length - 1] !== '\n') str += '\n'; - return str; - } - -} - -class Alias$1 extends PlainValue$5.Node { - /** - * Parses an *alias from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - parse(context, start) { - this.context = context; - const { - src - } = context; - let offset = PlainValue$5.Node.endOfIdentifier(src, start + 1); - this.valueRange = new PlainValue$5.Range(start + 1, offset); - offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - return offset; - } - -} - -const Chomp = { - CLIP: 'CLIP', - KEEP: 'KEEP', - STRIP: 'STRIP' -}; -class BlockValue extends PlainValue$5.Node { - constructor(type, props) { - super(type, props); - this.blockIndent = null; - this.chomping = Chomp.CLIP; - this.header = null; - } - - get includesTrailingLines() { - return this.chomping === Chomp.KEEP; - } - - get strValue() { - if (!this.valueRange || !this.context) return null; - let { - start, - end - } = this.valueRange; - const { - indent, - src - } = this.context; - if (this.valueRange.isEmpty()) return ''; - let lastNewLine = null; - let ch = src[end - 1]; - - while (ch === '\n' || ch === '\t' || ch === ' ') { - end -= 1; - - if (end <= start) { - if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens - } - - if (ch === '\n') lastNewLine = end; - ch = src[end - 1]; - } - - let keepStart = end + 1; - - if (lastNewLine) { - if (this.chomping === Chomp.KEEP) { - keepStart = lastNewLine; - end = this.valueRange.end; - } else { - end = lastNewLine; - } - } - - const bi = indent + this.blockIndent; - const folded = this.type === PlainValue$5.Type.BLOCK_FOLDED; - let atStart = true; - let str = ''; - let sep = ''; - let prevMoreIndented = false; - - for (let i = start; i < end; ++i) { - for (let j = 0; j < bi; ++j) { - if (src[i] !== ' ') break; - i += 1; - } - - const ch = src[i]; - - if (ch === '\n') { - if (sep === '\n') str += '\n';else sep = '\n'; - } else { - const lineEnd = PlainValue$5.Node.endOfLine(src, i); - const line = src.slice(i, lineEnd); - i = lineEnd; - - if (folded && (ch === ' ' || ch === '\t') && i < keepStart) { - if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n'; - str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '') - - sep = lineEnd < end && src[lineEnd] || ''; - prevMoreIndented = true; - } else { - str += sep + line; - sep = folded && i < keepStart ? ' ' : '\n'; - prevMoreIndented = false; - } - - if (atStart && line !== '') atStart = false; - } - } - - return this.chomping === Chomp.STRIP ? str : str + '\n'; - } - - parseBlockHeader(start) { - const { - src - } = this.context; - let offset = start + 1; - let bi = ''; - - while (true) { - const ch = src[offset]; - - switch (ch) { - case '-': - this.chomping = Chomp.STRIP; - break; - - case '+': - this.chomping = Chomp.KEEP; - break; - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - bi += ch; - break; - - default: - this.blockIndent = Number(bi) || null; - this.header = new PlainValue$5.Range(start, offset); - return offset; - } - - offset += 1; - } - } - - parseBlockValue(start) { - const { - indent, - src - } = this.context; - const explicit = !!this.blockIndent; - let offset = start; - let valueEnd = start; - let minBlockIndent = 1; - - for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { - offset += 1; - if (PlainValue$5.Node.atDocumentBoundary(src, offset)) break; - const end = PlainValue$5.Node.endOfBlockIndent(src, indent, offset); // should not include tab? - - if (end === null) break; - const ch = src[end]; - const lineIndent = end - (offset + indent); - - if (!this.blockIndent) { - // no explicit block indent, none yet detected - if (src[end] !== '\n') { - // first line with non-whitespace content - if (lineIndent < minBlockIndent) { - const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; - this.error = new PlainValue$5.YAMLSemanticError(this, msg); - } - - this.blockIndent = lineIndent; - } else if (lineIndent > minBlockIndent) { - // empty line with more whitespace - minBlockIndent = lineIndent; - } - } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) { - if (src[end] === '#') break; - - if (!this.error) { - const src = explicit ? 'explicit indentation indicator' : 'first line'; - const msg = `Block scalars must not be less indented than their ${src}`; - this.error = new PlainValue$5.YAMLSemanticError(this, msg); - } - } - - if (src[end] === '\n') { - offset = end; - } else { - offset = valueEnd = PlainValue$5.Node.endOfLine(src, end); - } - } - - if (this.chomping !== Chomp.KEEP) { - offset = src[valueEnd] ? valueEnd + 1 : valueEnd; - } - - this.valueRange = new PlainValue$5.Range(start + 1, offset); - return offset; - } - /** - * Parses a block value from the source - * - * Accepted forms are: - * ``` - * BS - * block - * lines - * - * BS #comment - * block - * lines - * ``` - * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines - * are empty or have an indent level greater than `indent`. - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this block - */ - - - parse(context, start) { - this.context = context; - const { - src - } = context; - let offset = this.parseBlockHeader(start); - offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - offset = this.parseBlockValue(offset); - return offset; - } - - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - return this.header ? this.header.setOrigRange(cr, offset) : offset; - } - -} - -class FlowCollection extends PlainValue$5.Node { - constructor(type, props) { - super(type, props); - this.items = null; - } - - prevNodeIsJsonLike(idx = this.items.length) { - const node = this.items[idx - 1]; - return !!node && (node.jsonLike || node.type === PlainValue$5.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1)); - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - - - parse(context, start) { - this.context = context; - const { - parseNode, - src - } = context; - let { - indent, - lineStart - } = context; - let char = src[start]; // { or [ - - this.items = [{ - char, - offset: start - }]; - let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1); - char = src[offset]; - - while (char && char !== ']' && char !== '}') { - switch (char) { - case '\n': - { - lineStart = offset + 1; - const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); - - if (src[wsEnd] === '\n') { - const blankLine = new BlankLine(); - lineStart = blankLine.parse({ - src - }, lineStart); - this.items.push(blankLine); - } - - offset = PlainValue$5.Node.endOfIndent(src, lineStart); - - if (offset <= lineStart + indent) { - char = src[offset]; - - if (offset < lineStart + indent || char !== ']' && char !== '}') { - const msg = 'Insufficient indentation in flow collection'; - this.error = new PlainValue$5.YAMLSemanticError(this, msg); - } - } - } - break; - - case ',': - { - this.items.push({ - char, - offset - }); - offset += 1; - } - break; - - case '#': - { - const comment = new Comment(); - offset = comment.parse({ - src - }, offset); - this.items.push(comment); - } - break; - - case '?': - case ':': - { - const next = src[offset + 1]; - - if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace - char === ':' && this.prevNodeIsJsonLike()) { - this.items.push({ - char, - offset - }); - offset += 1; - break; - } - } - // fallthrough - - default: - { - const node = parseNode({ - atLineStart: false, - inCollection: false, - inFlow: true, - indent: -1, - lineStart, - parent: this - }, offset); - - if (!node) { - // at next document start - this.valueRange = new PlainValue$5.Range(start, offset); - return offset; - } - - this.items.push(node); - offset = PlainValue$5.Node.normalizeOffset(src, node.range.end); - } - } - - offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); - char = src[offset]; - } - - this.valueRange = new PlainValue$5.Range(start, offset + 1); - - if (char) { - this.items.push({ - char, - offset - }); - offset = PlainValue$5.Node.endOfWhiteSpace(src, offset + 1); - offset = this.parseComment(offset); - } - - return offset; - } - - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - this.items.forEach(node => { - if (node instanceof PlainValue$5.Node) { - offset = node.setOrigRanges(cr, offset); - } else if (cr.length === 0) { - node.origOffset = node.offset; - } else { - let i = offset; - - while (i < cr.length) { - if (cr[i] > node.offset) break;else ++i; - } - - node.origOffset = node.offset + i; - offset = i; - } - }); - return offset; - } - - toString() { - const { - context: { - src - }, - items, - range, - value - } = this; - if (value != null) return value; - const nodes = items.filter(item => item instanceof PlainValue$5.Node); - let str = ''; - let prevEnd = range.start; - nodes.forEach(node => { - const prefix = src.slice(prevEnd, node.range.start); - prevEnd = node.range.end; - str += prefix + String(node); - - if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') { - // Comment range does not include the terminal newline, but its - // stringified value does. Without this fix, newlines at comment ends - // get duplicated. - prevEnd += 1; - } - }); - str += src.slice(prevEnd, range.end); - return PlainValue$5.Node.addStringTerminator(src, range.end, str); - } - -} - -class QuoteDouble extends PlainValue$5.Node { - static endOfQuote(src, offset) { - let ch = src[offset]; - - while (ch && ch !== '"') { - offset += ch === '\\' ? 2 : 1; - ch = src[offset]; - } - - return offset + 1; - } - /** - * @returns {string | { str: string, errors: YAMLSyntaxError[] }} - */ - - - get strValue() { - if (!this.valueRange || !this.context) return null; - const errors = []; - const { - start, - end - } = this.valueRange; - const { - indent, - src - } = this.context; - if (src[end - 1] !== '"') errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by - // escaped backslashes; also, this should be faster. - - let str = ''; - - for (let i = start + 1; i < end - 1; ++i) { - const ch = src[i]; - - if (ch === '\n') { - if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); - const { - fold, - offset, - error - } = PlainValue$5.Node.foldNewline(src, i, indent); - str += fold; - i = offset; - if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented')); - } else if (ch === '\\') { - i += 1; - - switch (src[i]) { - case '0': - str += '\0'; - break; - // null character - - case 'a': - str += '\x07'; - break; - // bell character - - case 'b': - str += '\b'; - break; - // backspace - - case 'e': - str += '\x1b'; - break; - // escape character - - case 'f': - str += '\f'; - break; - // form feed - - case 'n': - str += '\n'; - break; - // line feed - - case 'r': - str += '\r'; - break; - // carriage return - - case 't': - str += '\t'; - break; - // horizontal tab - - case 'v': - str += '\v'; - break; - // vertical tab - - case 'N': - str += '\u0085'; - break; - // Unicode next line - - case '_': - str += '\u00a0'; - break; - // Unicode non-breaking space - - case 'L': - str += '\u2028'; - break; - // Unicode line separator - - case 'P': - str += '\u2029'; - break; - // Unicode paragraph separator - - case ' ': - str += ' '; - break; - - case '"': - str += '"'; - break; - - case '/': - str += '/'; - break; - - case '\\': - str += '\\'; - break; - - case '\t': - str += '\t'; - break; - - case 'x': - str += this.parseCharCode(i + 1, 2, errors); - i += 2; - break; - - case 'u': - str += this.parseCharCode(i + 1, 4, errors); - i += 4; - break; - - case 'U': - str += this.parseCharCode(i + 1, 8, errors); - i += 8; - break; - - case '\n': - // skip escaped newlines, but still trim the following line - while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1; - - break; - - default: - errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`)); - str += '\\' + src[i]; - } - } else if (ch === ' ' || ch === '\t') { - // trim trailing whitespace - const wsStart = i; - let next = src[i + 1]; - - while (next === ' ' || next === '\t') { - i += 1; - next = src[i + 1]; - } - - if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; - } else { - str += ch; - } - } - - return errors.length > 0 ? { - errors, - str - } : str; - } - - parseCharCode(offset, length, errors) { - const { - src - } = this.context; - const cc = src.substr(offset, length); - const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); - const code = ok ? parseInt(cc, 16) : NaN; - - if (isNaN(code)) { - errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`)); - return src.substr(offset - 2, length + 2); - } - - return String.fromCodePoint(code); - } - /** - * Parses a "double quoted" value from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - - - parse(context, start) { - this.context = context; - const { - src - } = context; - let offset = QuoteDouble.endOfQuote(src, start + 1); - this.valueRange = new PlainValue$5.Range(start, offset); - offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - return offset; - } - -} - -class QuoteSingle extends PlainValue$5.Node { - static endOfQuote(src, offset) { - let ch = src[offset]; - - while (ch) { - if (ch === "'") { - if (src[offset + 1] !== "'") break; - ch = src[offset += 2]; - } else { - ch = src[offset += 1]; - } - } - - return offset + 1; - } - /** - * @returns {string | { str: string, errors: YAMLSyntaxError[] }} - */ - - - get strValue() { - if (!this.valueRange || !this.context) return null; - const errors = []; - const { - start, - end - } = this.valueRange; - const { - indent, - src - } = this.context; - if (src[end - 1] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, "Missing closing 'quote")); - let str = ''; - - for (let i = start + 1; i < end - 1; ++i) { - const ch = src[i]; - - if (ch === '\n') { - if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); - const { - fold, - offset, - error - } = PlainValue$5.Node.foldNewline(src, i, indent); - str += fold; - i = offset; - if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented')); - } else if (ch === "'") { - str += ch; - i += 1; - if (src[i] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.')); - } else if (ch === ' ' || ch === '\t') { - // trim trailing whitespace - const wsStart = i; - let next = src[i + 1]; - - while (next === ' ' || next === '\t') { - i += 1; - next = src[i + 1]; - } - - if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; - } else { - str += ch; - } - } - - return errors.length > 0 ? { - errors, - str - } : str; - } - /** - * Parses a 'single quoted' value from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - - - parse(context, start) { - this.context = context; - const { - src - } = context; - let offset = QuoteSingle.endOfQuote(src, start + 1); - this.valueRange = new PlainValue$5.Range(start, offset); - offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - return offset; - } - -} - -function createNewNode(type, props) { - switch (type) { - case PlainValue$5.Type.ALIAS: - return new Alias$1(type, props); - - case PlainValue$5.Type.BLOCK_FOLDED: - case PlainValue$5.Type.BLOCK_LITERAL: - return new BlockValue(type, props); - - case PlainValue$5.Type.FLOW_MAP: - case PlainValue$5.Type.FLOW_SEQ: - return new FlowCollection(type, props); - - case PlainValue$5.Type.MAP_KEY: - case PlainValue$5.Type.MAP_VALUE: - case PlainValue$5.Type.SEQ_ITEM: - return new CollectionItem(type, props); - - case PlainValue$5.Type.COMMENT: - case PlainValue$5.Type.PLAIN: - return new PlainValue$5.PlainValue(type, props); - - case PlainValue$5.Type.QUOTE_DOUBLE: - return new QuoteDouble(type, props); - - case PlainValue$5.Type.QUOTE_SINGLE: - return new QuoteSingle(type, props); - - /* istanbul ignore next */ - - default: - return null; - // should never happen - } -} -/** - * @param {boolean} atLineStart - Node starts at beginning of line - * @param {boolean} inFlow - true if currently in a flow context - * @param {boolean} inCollection - true if currently in a collection context - * @param {number} indent - Current level of indentation - * @param {number} lineStart - Start of the current line - * @param {Node} parent - The parent of the node - * @param {string} src - Source of the YAML document - */ - - -class ParseContext { - static parseType(src, offset, inFlow) { - switch (src[offset]) { - case '*': - return PlainValue$5.Type.ALIAS; - - case '>': - return PlainValue$5.Type.BLOCK_FOLDED; - - case '|': - return PlainValue$5.Type.BLOCK_LITERAL; - - case '{': - return PlainValue$5.Type.FLOW_MAP; - - case '[': - return PlainValue$5.Type.FLOW_SEQ; - - case '?': - return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_KEY : PlainValue$5.Type.PLAIN; - - case ':': - return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_VALUE : PlainValue$5.Type.PLAIN; - - case '-': - return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.SEQ_ITEM : PlainValue$5.Type.PLAIN; - - case '"': - return PlainValue$5.Type.QUOTE_DOUBLE; - - case "'": - return PlainValue$5.Type.QUOTE_SINGLE; - - default: - return PlainValue$5.Type.PLAIN; - } - } - - constructor(orig = {}, { - atLineStart, - inCollection, - inFlow, - indent, - lineStart, - parent - } = {}) { - PlainValue$5._defineProperty(this, "parseNode", (overlay, start) => { - if (PlainValue$5.Node.atDocumentBoundary(this.src, start)) return null; - const context = new ParseContext(this, overlay); - const { - props, - type, - valueStart - } = context.parseProps(start); - const node = createNewNode(type, props); - let offset = node.parse(context, valueStart); - node.range = new PlainValue$5.Range(start, offset); - /* istanbul ignore if */ - - if (offset <= start) { - // This should never happen, but if it does, let's make sure to at least - // step one character forward to avoid a busy loop. - node.error = new Error(`Node#parse consumed no characters`); - node.error.parseEnd = offset; - node.error.source = node; - node.range.end = start + 1; - } - - if (context.nodeStartsCollection(node)) { - if (!node.error && !context.atLineStart && context.parent.type === PlainValue$5.Type.DOCUMENT) { - node.error = new PlainValue$5.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)'); - } - - const collection = new Collection$1(node); - offset = collection.parse(new ParseContext(context), offset); - collection.range = new PlainValue$5.Range(start, offset); - return collection; - } - - return node; - }); - - this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false; - this.inCollection = inCollection != null ? inCollection : orig.inCollection || false; - this.inFlow = inFlow != null ? inFlow : orig.inFlow || false; - this.indent = indent != null ? indent : orig.indent; - this.lineStart = lineStart != null ? lineStart : orig.lineStart; - this.parent = parent != null ? parent : orig.parent || {}; - this.root = orig.root; - this.src = orig.src; - } - - nodeStartsCollection(node) { - const { - inCollection, - inFlow, - src - } = this; - if (inCollection || inFlow) return false; - if (node instanceof CollectionItem) return true; // check for implicit key - - let offset = node.range.end; - if (src[offset] === '\n' || src[offset - 1] === '\n') return false; - offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); - return src[offset] === ':'; - } // Anchor and tag are before type, which determines the node implementation - // class; hence this intermediate step. - - - parseProps(offset) { - const { - inFlow, - parent, - src - } = this; - const props = []; - let lineHasProps = false; - offset = this.atLineStart ? PlainValue$5.Node.endOfIndent(src, offset) : PlainValue$5.Node.endOfWhiteSpace(src, offset); - let ch = src[offset]; - - while (ch === PlainValue$5.Char.ANCHOR || ch === PlainValue$5.Char.COMMENT || ch === PlainValue$5.Char.TAG || ch === '\n') { - if (ch === '\n') { - let inEnd = offset; - let lineStart; - - do { - lineStart = inEnd + 1; - inEnd = PlainValue$5.Node.endOfIndent(src, lineStart); - } while (src[inEnd] === '\n'); - - const indentDiff = inEnd - (lineStart + this.indent); - const noIndicatorAsIndent = parent.type === PlainValue$5.Type.SEQ_ITEM && parent.context.atLineStart; - if (src[inEnd] !== '#' && !PlainValue$5.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break; - this.atLineStart = true; - this.lineStart = lineStart; - lineHasProps = false; - offset = inEnd; - } else if (ch === PlainValue$5.Char.COMMENT) { - const end = PlainValue$5.Node.endOfLine(src, offset + 1); - props.push(new PlainValue$5.Range(offset, end)); - offset = end; - } else { - let end = PlainValue$5.Node.endOfIdentifier(src, offset + 1); - - if (ch === PlainValue$5.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) { - // Let's presume we're dealing with a YAML 1.0 domain tag here, rather - // than an empty but 'foo.bar' private-tagged node in a flow collection - // followed without whitespace by a plain string starting with a year - // or date divided by something. - end = PlainValue$5.Node.endOfIdentifier(src, end + 5); - } - - props.push(new PlainValue$5.Range(offset, end)); - lineHasProps = true; - offset = PlainValue$5.Node.endOfWhiteSpace(src, end); - } - - ch = src[offset]; - } // '- &a : b' has an anchor on an empty node - - - if (lineHasProps && ch === ':' && PlainValue$5.Node.atBlank(src, offset + 1, true)) offset -= 1; - const type = ParseContext.parseType(src, offset, inFlow); - return { - props, - type, - valueStart: offset - }; - } - /** - * Parses a node from the source - * @param {ParseContext} overlay - * @param {number} start - Index of first non-whitespace character for the node - * @returns {?Node} - null if at a document boundary - */ - - -} - -// Published as 'yaml/parse-cst' -function parse$h(src) { - const cr = []; - - if (src.indexOf('\r') !== -1) { - src = src.replace(/\r\n?/g, (match, offset) => { - if (match.length > 1) cr.push(offset); - return '\n'; - }); - } - - const documents = []; - let offset = 0; - - do { - const doc = new Document$3(); - const context = new ParseContext({ - src - }); - offset = doc.parse(context, offset); - documents.push(doc); - } while (offset < src.length); - - documents.setOrigRanges = () => { - if (cr.length === 0) return false; - - for (let i = 1; i < cr.length; ++i) cr[i] -= i; - - let crOffset = 0; - - for (let i = 0; i < documents.length; ++i) { - crOffset = documents[i].setOrigRanges(cr, crOffset); - } - - cr.splice(0, cr.length); - return true; - }; - - documents.toString = () => documents.join('...\n'); - - return documents; -} - -parseCst$1.parse = parse$h; - -var Document9b4560a1 = {}; - -var resolveSeqD03cb037 = {}; - -var PlainValue$4 = PlainValueEc8e588e; - -function addCommentBefore(str, indent, comment) { - if (!comment) return str; - const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`); - return `#${cc}\n${indent}${str}`; -} -function addComment(str, indent, comment) { - return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`); -} - -class Node$1 {} - -function toJSON(value, arg, ctx) { - if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx)); - - if (value && typeof value.toJSON === 'function') { - const anchor = ctx && ctx.anchors && ctx.anchors.get(value); - if (anchor) ctx.onCreate = res => { - anchor.res = res; - delete ctx.onCreate; - }; - const res = value.toJSON(arg, ctx); - if (anchor && ctx.onCreate) ctx.onCreate(res); - return res; - } - - if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value); - return value; -} - -class Scalar extends Node$1 { - constructor(value) { - super(); - this.value = value; - } - - toJSON(arg, ctx) { - return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx); - } - - toString() { - return String(this.value); - } - -} - -function collectionFromPath(schema, path, value) { - let v = value; - - for (let i = path.length - 1; i >= 0; --i) { - const k = path[i]; - - if (Number.isInteger(k) && k >= 0) { - const a = []; - a[k] = v; - v = a; - } else { - const o = {}; - Object.defineProperty(o, k, { - value: v, - writable: true, - enumerable: true, - configurable: true - }); - v = o; - } - } - - return schema.createNode(v, false); -} // null, undefined, or an empty non-string iterable (e.g. []) - - -const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done; -class Collection extends Node$1 { - constructor(schema) { - super(); - - PlainValue$4._defineProperty(this, "items", []); - - this.schema = schema; - } - - addIn(path, value) { - if (isEmptyPath(path)) this.add(value);else { - const [key, ...rest] = path; - const node = this.get(key, true); - if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); - } - } - - deleteIn([key, ...rest]) { - if (rest.length === 0) return this.delete(key); - const node = this.get(key, true); - if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); - } - - getIn([key, ...rest], keepScalar) { - const node = this.get(key, true); - if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined; - } - - hasAllNullValues() { - return this.items.every(node => { - if (!node || node.type !== 'PAIR') return false; - const n = node.value; - return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag; - }); - } - - hasIn([key, ...rest]) { - if (rest.length === 0) return this.has(key); - const node = this.get(key, true); - return node instanceof Collection ? node.hasIn(rest) : false; - } - - setIn([key, ...rest], value) { - if (rest.length === 0) { - this.set(key, value); - } else { - const node = this.get(key, true); - if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); - } - } // overridden in implementations - - /* istanbul ignore next */ - - - toJSON() { - return null; - } - - toString(ctx, { - blockItem, - flowChars, - isMap, - itemIndent - }, onComment, onChompKeep) { - const { - indent, - indentStep, - stringify - } = ctx; - const inFlow = this.type === PlainValue$4.Type.FLOW_MAP || this.type === PlainValue$4.Type.FLOW_SEQ || ctx.inFlow; - if (inFlow) itemIndent += indentStep; - const allNullValues = isMap && this.hasAllNullValues(); - ctx = Object.assign({}, ctx, { - allNullValues, - indent: itemIndent, - inFlow, - type: null - }); - let chompKeep = false; - let hasItemWithNewLine = false; - const nodes = this.items.reduce((nodes, item, i) => { - let comment; - - if (item) { - if (!chompKeep && item.spaceBefore) nodes.push({ - type: 'comment', - str: '' - }); - if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => { - nodes.push({ - type: 'comment', - str: `#${line}` - }); - }); - if (item.comment) comment = item.comment; - if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true; - } - - chompKeep = false; - let str = stringify(item, ctx, () => comment = null, () => chompKeep = true); - if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true; - if (inFlow && i < this.items.length - 1) str += ','; - str = addComment(str, itemIndent, comment); - if (chompKeep && (comment || inFlow)) chompKeep = false; - nodes.push({ - type: 'item', - str - }); - return nodes; - }, []); - let str; - - if (nodes.length === 0) { - str = flowChars.start + flowChars.end; - } else if (inFlow) { - const { - start, - end - } = flowChars; - const strings = nodes.map(n => n.str); - - if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) { - str = start; - - for (const s of strings) { - str += s ? `\n${indentStep}${indent}${s}` : '\n'; - } - - str += `\n${indent}${end}`; - } else { - str = `${start} ${strings.join(' ')} ${end}`; - } - } else { - const strings = nodes.map(blockItem); - str = strings.shift(); - - for (const s of strings) str += s ? `\n${indent}${s}` : '\n'; - } - - if (this.comment) { - str += '\n' + this.comment.replace(/^/gm, `${indent}#`); - if (onComment) onComment(); - } else if (chompKeep && onChompKeep) onChompKeep(); - - return str; - } - -} - -PlainValue$4._defineProperty(Collection, "maxFlowStringSingleLineLength", 60); - -function asItemIndex(key) { - let idx = key instanceof Scalar ? key.value : key; - if (idx && typeof idx === 'string') idx = Number(idx); - return Number.isInteger(idx) && idx >= 0 ? idx : null; -} - -class YAMLSeq extends Collection { - add(value) { - this.items.push(value); - } - - delete(key) { - const idx = asItemIndex(key); - if (typeof idx !== 'number') return false; - const del = this.items.splice(idx, 1); - return del.length > 0; - } - - get(key, keepScalar) { - const idx = asItemIndex(key); - if (typeof idx !== 'number') return undefined; - const it = this.items[idx]; - return !keepScalar && it instanceof Scalar ? it.value : it; - } - - has(key) { - const idx = asItemIndex(key); - return typeof idx === 'number' && idx < this.items.length; - } - - set(key, value) { - const idx = asItemIndex(key); - if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`); - this.items[idx] = value; - } - - toJSON(_, ctx) { - const seq = []; - if (ctx && ctx.onCreate) ctx.onCreate(seq); - let i = 0; - - for (const item of this.items) seq.push(toJSON(item, String(i++), ctx)); - - return seq; - } - - toString(ctx, onComment, onChompKeep) { - if (!ctx) return JSON.stringify(this); - return super.toString(ctx, { - blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`, - flowChars: { - start: '[', - end: ']' - }, - isMap: false, - itemIndent: (ctx.indent || '') + ' ' - }, onComment, onChompKeep); - } - -} - -const stringifyKey = (key, jsKey, ctx) => { - if (jsKey === null) return ''; - if (typeof jsKey !== 'object') return String(jsKey); - if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({ - anchors: Object.create(null), - doc: ctx.doc, - indent: '', - indentStep: ctx.indentStep, - inFlow: true, - inStringifyKey: true, - stringify: ctx.stringify - }); - return JSON.stringify(jsKey); -}; - -class Pair extends Node$1 { - constructor(key, value = null) { - super(); - this.key = key; - this.value = value; - this.type = Pair.Type.PAIR; - } - - get commentBefore() { - return this.key instanceof Node$1 ? this.key.commentBefore : undefined; - } - - set commentBefore(cb) { - if (this.key == null) this.key = new Scalar(null); - if (this.key instanceof Node$1) this.key.commentBefore = cb;else { - const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.'; - throw new Error(msg); - } - } - - addToJSMap(ctx, map) { - const key = toJSON(this.key, '', ctx); - - if (map instanceof Map) { - const value = toJSON(this.value, key, ctx); - map.set(key, value); - } else if (map instanceof Set) { - map.add(key); - } else { - const stringKey = stringifyKey(this.key, key, ctx); - const value = toJSON(this.value, stringKey, ctx); - if (stringKey in map) Object.defineProperty(map, stringKey, { - value, - writable: true, - enumerable: true, - configurable: true - });else map[stringKey] = value; - } - - return map; - } - - toJSON(_, ctx) { - const pair = ctx && ctx.mapAsMap ? new Map() : {}; - return this.addToJSMap(ctx, pair); - } - - toString(ctx, onComment, onChompKeep) { - if (!ctx || !ctx.doc) return JSON.stringify(this); - const { - indent: indentSize, - indentSeq, - simpleKeys - } = ctx.doc.options; - let { - key, - value - } = this; - let keyComment = key instanceof Node$1 && key.comment; - - if (simpleKeys) { - if (keyComment) { - throw new Error('With simple keys, key nodes cannot have comments'); - } - - if (key instanceof Collection) { - const msg = 'With simple keys, collection cannot be used as a key value'; - throw new Error(msg); - } - } - - let explicitKey = !simpleKeys && (!key || keyComment || (key instanceof Node$1 ? key instanceof Collection || key.type === PlainValue$4.Type.BLOCK_FOLDED || key.type === PlainValue$4.Type.BLOCK_LITERAL : typeof key === 'object')); - const { - doc, - indent, - indentStep, - stringify - } = ctx; - ctx = Object.assign({}, ctx, { - implicitKey: !explicitKey, - indent: indent + indentStep - }); - let chompKeep = false; - let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true); - str = addComment(str, ctx.indent, keyComment); - - if (!explicitKey && str.length > 1024) { - if (simpleKeys) throw new Error('With simple keys, single line scalar must not span more than 1024 characters'); - explicitKey = true; - } - - if (ctx.allNullValues && !simpleKeys) { - if (this.comment) { - str = addComment(str, ctx.indent, this.comment); - if (onComment) onComment(); - } else if (chompKeep && !keyComment && onChompKeep) onChompKeep(); - - return ctx.inFlow && !explicitKey ? str : `? ${str}`; - } - - str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`; - - if (this.comment) { - // expected (but not strictly required) to be a single-line comment - str = addComment(str, ctx.indent, this.comment); - if (onComment) onComment(); - } - - let vcb = ''; - let valueComment = null; - - if (value instanceof Node$1) { - if (value.spaceBefore) vcb = '\n'; - - if (value.commentBefore) { - const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`); - vcb += `\n${cs}`; - } - - valueComment = value.comment; - } else if (value && typeof value === 'object') { - value = doc.schema.createNode(value, true); - } - - ctx.implicitKey = false; - if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1; - chompKeep = false; - - if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue$4.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) { - // If indentSeq === false, consider '- ' as part of indentation where possible - ctx.indent = ctx.indent.substr(2); - } - - const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true); - let ws = ' '; - - if (vcb || this.comment) { - ws = `${vcb}\n${ctx.indent}`; - } else if (!explicitKey && value instanceof Collection) { - const flow = valueStr[0] === '[' || valueStr[0] === '{'; - if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`; - } else if (valueStr[0] === '\n') ws = ''; - - if (chompKeep && !valueComment && onChompKeep) onChompKeep(); - return addComment(str + ws + valueStr, ctx.indent, valueComment); - } - -} - -PlainValue$4._defineProperty(Pair, "Type", { - PAIR: 'PAIR', - MERGE_PAIR: 'MERGE_PAIR' -}); - -const getAliasCount = (node, anchors) => { - if (node instanceof Alias) { - const anchor = anchors.get(node.source); - return anchor.count * anchor.aliasCount; - } else if (node instanceof Collection) { - let count = 0; - - for (const item of node.items) { - const c = getAliasCount(item, anchors); - if (c > count) count = c; - } - - return count; - } else if (node instanceof Pair) { - const kc = getAliasCount(node.key, anchors); - const vc = getAliasCount(node.value, anchors); - return Math.max(kc, vc); - } - - return 1; -}; - -class Alias extends Node$1 { - static stringify({ - range, - source - }, { - anchors, - doc, - implicitKey, - inStringifyKey - }) { - let anchor = Object.keys(anchors).find(a => anchors[a] === source); - if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName(); - if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`; - const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node'; - throw new Error(`${msg} [${range}]`); - } - - constructor(source) { - super(); - this.source = source; - this.type = PlainValue$4.Type.ALIAS; - } - - set tag(t) { - throw new Error('Alias nodes cannot have tags'); - } - - toJSON(arg, ctx) { - if (!ctx) return toJSON(this.source, arg, ctx); - const { - anchors, - maxAliasCount - } = ctx; - const anchor = anchors.get(this.source); - /* istanbul ignore if */ - - if (!anchor || anchor.res === undefined) { - const msg = 'This should not happen: Alias anchor was not resolved?'; - if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); - } - - if (maxAliasCount >= 0) { - anchor.count += 1; - if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors); - - if (anchor.count * anchor.aliasCount > maxAliasCount) { - const msg = 'Excessive alias count indicates a resource exhaustion attack'; - if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); - } - } - - return anchor.res; - } // Only called when stringifying an alias mapping key while constructing - // Object output. - - - toString(ctx) { - return Alias.stringify(this, ctx); - } - -} - -PlainValue$4._defineProperty(Alias, "default", true); - -function findPair(items, key) { - const k = key instanceof Scalar ? key.value : key; - - for (const it of items) { - if (it instanceof Pair) { - if (it.key === key || it.key === k) return it; - if (it.key && it.key.value === k) return it; - } - } - - return undefined; -} -class YAMLMap extends Collection { - add(pair, overwrite) { - if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value); - const prev = findPair(this.items, pair.key); - const sortEntries = this.schema && this.schema.sortMapEntries; - - if (prev) { - if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`); - } else if (sortEntries) { - const i = this.items.findIndex(item => sortEntries(pair, item) < 0); - if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair); - } else { - this.items.push(pair); - } - } - - delete(key) { - const it = findPair(this.items, key); - if (!it) return false; - const del = this.items.splice(this.items.indexOf(it), 1); - return del.length > 0; - } - - get(key, keepScalar) { - const it = findPair(this.items, key); - const node = it && it.value; - return !keepScalar && node instanceof Scalar ? node.value : node; - } - - has(key) { - return !!findPair(this.items, key); - } - - set(key, value) { - this.add(new Pair(key, value), true); - } - /** - * @param {*} arg ignored - * @param {*} ctx Conversion context, originally set in Document#toJSON() - * @param {Class} Type If set, forces the returned collection type - * @returns {*} Instance of Type, Map, or Object - */ - - - toJSON(_, ctx, Type) { - const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {}; - if (ctx && ctx.onCreate) ctx.onCreate(map); - - for (const item of this.items) item.addToJSMap(ctx, map); - - return map; - } - - toString(ctx, onComment, onChompKeep) { - if (!ctx) return JSON.stringify(this); - - for (const item of this.items) { - if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); - } - - return super.toString(ctx, { - blockItem: n => n.str, - flowChars: { - start: '{', - end: '}' - }, - isMap: true, - itemIndent: ctx.indent || '' - }, onComment, onChompKeep); - } - -} - -const MERGE_KEY = '<<'; -class Merge extends Pair { - constructor(pair) { - if (pair instanceof Pair) { - let seq = pair.value; - - if (!(seq instanceof YAMLSeq)) { - seq = new YAMLSeq(); - seq.items.push(pair.value); - seq.range = pair.value.range; - } - - super(pair.key, seq); - this.range = pair.range; - } else { - super(new Scalar(MERGE_KEY), new YAMLSeq()); - } - - this.type = Pair.Type.MERGE_PAIR; - } // If the value associated with a merge key is a single mapping node, each of - // its key/value pairs is inserted into the current mapping, unless the key - // already exists in it. If the value associated with the merge key is a - // sequence, then this sequence is expected to contain mapping nodes and each - // of these nodes is merged in turn according to its order in the sequence. - // Keys in mapping nodes earlier in the sequence override keys specified in - // later mapping nodes. -- http://yaml.org/type/merge.html - - - addToJSMap(ctx, map) { - for (const { - source - } of this.value.items) { - if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps'); - const srcMap = source.toJSON(null, ctx, Map); - - for (const [key, value] of srcMap) { - if (map instanceof Map) { - if (!map.has(key)) map.set(key, value); - } else if (map instanceof Set) { - map.add(key); - } else if (!Object.prototype.hasOwnProperty.call(map, key)) { - Object.defineProperty(map, key, { - value, - writable: true, - enumerable: true, - configurable: true - }); - } - } - } - - return map; - } - - toString(ctx, onComment) { - const seq = this.value; - if (seq.items.length > 1) return super.toString(ctx, onComment); - this.value = seq.items[0]; - const str = super.toString(ctx, onComment); - this.value = seq; - return str; - } - -} - -const binaryOptions = { - defaultType: PlainValue$4.Type.BLOCK_LITERAL, - lineWidth: 76 -}; -const boolOptions = { - trueStr: 'true', - falseStr: 'false' -}; -const intOptions = { - asBigInt: false -}; -const nullOptions = { - nullStr: 'null' -}; -const strOptions = { - defaultType: PlainValue$4.Type.PLAIN, - doubleQuoted: { - jsonEncoding: false, - minMultiLineLength: 40 - }, - fold: { - lineWidth: 80, - minContentWidth: 20 - } -}; - -function resolveScalar(str, tags, scalarFallback) { - for (const { - format, - test, - resolve - } of tags) { - if (test) { - const match = str.match(test); - - if (match) { - let res = resolve.apply(null, match); - if (!(res instanceof Scalar)) res = new Scalar(res); - if (format) res.format = format; - return res; - } - } - } - - if (scalarFallback) str = scalarFallback(str); - return new Scalar(str); -} - -const FOLD_FLOW = 'flow'; -const FOLD_BLOCK = 'block'; -const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line -// returns index of last newline in more-indented block - -const consumeMoreIndentedLines = (text, i) => { - let ch = text[i + 1]; - - while (ch === ' ' || ch === '\t') { - do { - ch = text[i += 1]; - } while (ch && ch !== '\n'); - - ch = text[i + 1]; - } - - return i; -}; -/** - * Tries to keep input at up to `lineWidth` characters, splitting only on spaces - * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are - * terminated with `\n` and started with `indent`. - * - * @param {string} text - * @param {string} indent - * @param {string} [mode='flow'] `'block'` prevents more-indented lines - * from being folded; `'quoted'` allows for `\` escapes, including escaped - * newlines - * @param {Object} options - * @param {number} [options.indentAtStart] Accounts for leading contents on - * the first line, defaulting to `indent.length` - * @param {number} [options.lineWidth=80] - * @param {number} [options.minContentWidth=20] Allow highly indented lines to - * stretch the line width or indent content from the start - * @param {function} options.onFold Called once if the text is folded - * @param {function} options.onFold Called once if any line of text exceeds - * lineWidth characters - */ - - -function foldFlowLines(text, indent, mode, { - indentAtStart, - lineWidth = 80, - minContentWidth = 20, - onFold, - onOverflow -}) { - if (!lineWidth || lineWidth < 0) return text; - const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); - if (text.length <= endStep) return text; - const folds = []; - const escapedFolds = {}; - let end = lineWidth - indent.length; - - if (typeof indentAtStart === 'number') { - if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0);else end = lineWidth - indentAtStart; - } - - let split = undefined; - let prev = undefined; - let overflow = false; - let i = -1; - let escStart = -1; - let escEnd = -1; - - if (mode === FOLD_BLOCK) { - i = consumeMoreIndentedLines(text, i); - if (i !== -1) end = i + endStep; - } - - for (let ch; ch = text[i += 1];) { - if (mode === FOLD_QUOTED && ch === '\\') { - escStart = i; - - switch (text[i + 1]) { - case 'x': - i += 3; - break; - - case 'u': - i += 5; - break; - - case 'U': - i += 9; - break; - - default: - i += 1; - } - - escEnd = i; - } - - if (ch === '\n') { - if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i); - end = i + endStep; - split = undefined; - } else { - if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') { - // space surrounded by non-space can be replaced with newline + indent - const next = text[i + 1]; - if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i; - } - - if (i >= end) { - if (split) { - folds.push(split); - end = split + endStep; - split = undefined; - } else if (mode === FOLD_QUOTED) { - // white-space collected at end may stretch past lineWidth - while (prev === ' ' || prev === '\t') { - prev = ch; - ch = text[i += 1]; - overflow = true; - } // Account for newline escape, but don't break preceding escape - - - const j = i > escEnd + 1 ? i - 2 : escStart - 1; // Bail out if lineWidth & minContentWidth are shorter than an escape string - - if (escapedFolds[j]) return text; - folds.push(j); - escapedFolds[j] = true; - end = j + endStep; - split = undefined; - } else { - overflow = true; - } - } - } - - prev = ch; - } - - if (overflow && onOverflow) onOverflow(); - if (folds.length === 0) return text; - if (onFold) onFold(); - let res = text.slice(0, folds[0]); - - for (let i = 0; i < folds.length; ++i) { - const fold = folds[i]; - const end = folds[i + 1] || text.length; - if (fold === 0) res = `\n${indent}${text.slice(0, end)}`;else { - if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; - res += `\n${indent}${text.slice(fold + 1, end)}`; - } - } - - return res; -} - -const getFoldOptions = ({ - indentAtStart -}) => indentAtStart ? Object.assign({ - indentAtStart -}, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will -// presume that's starting a new document. - - -const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str); - -function lineLengthOverLimit(str, lineWidth, indentLength) { - if (!lineWidth || lineWidth < 0) return false; - const limit = lineWidth - indentLength; - const strLen = str.length; - if (strLen <= limit) return false; - - for (let i = 0, start = 0; i < strLen; ++i) { - if (str[i] === '\n') { - if (i - start > limit) return true; - start = i + 1; - if (strLen - start <= limit) return false; - } - } - - return true; -} - -function doubleQuotedString(value, ctx) { - const { - implicitKey - } = ctx; - const { - jsonEncoding, - minMultiLineLength - } = strOptions.doubleQuoted; - const json = JSON.stringify(value); - if (jsonEncoding) return json; - const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); - let str = ''; - let start = 0; - - for (let i = 0, ch = json[i]; ch; ch = json[++i]) { - if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { - // space before newline needs to be escaped to not be folded - str += json.slice(start, i) + '\\ '; - i += 1; - start = i; - ch = '\\'; - } - - if (ch === '\\') switch (json[i + 1]) { - case 'u': - { - str += json.slice(start, i); - const code = json.substr(i + 2, 4); - - switch (code) { - case '0000': - str += '\\0'; - break; - - case '0007': - str += '\\a'; - break; - - case '000b': - str += '\\v'; - break; - - case '001b': - str += '\\e'; - break; - - case '0085': - str += '\\N'; - break; - - case '00a0': - str += '\\_'; - break; - - case '2028': - str += '\\L'; - break; - - case '2029': - str += '\\P'; - break; - - default: - if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6); - } - - i += 5; - start = i + 1; - } - break; - - case 'n': - if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { - i += 1; - } else { - // folding will eat first newline - str += json.slice(start, i) + '\n\n'; - - while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') { - str += '\n'; - i += 2; - } - - str += indent; // space after newline needs to be escaped to not be folded - - if (json[i + 2] === ' ') str += '\\'; - i += 1; - start = i + 1; - } - - break; - - default: - i += 1; - } - } - - str = start ? str + json.slice(start) : json; - return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx)); -} - -function singleQuotedString(value, ctx) { - if (ctx.implicitKey) { - if (/\n/.test(value)) return doubleQuotedString(value, ctx); - } else { - // single quoted string can't have leading or trailing whitespace around newline - if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); - } - - const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); - const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; - return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx)); -} - -function blockString({ - comment, - type, - value -}, ctx, onComment, onChompKeep) { - // 1. Block can't end in whitespace unless the last line is non-empty. - // 2. Strings consisting of only whitespace are best rendered explicitly. - if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) { - return doubleQuotedString(value, ctx); - } - - const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : ''); - const indentSize = indent ? '2' : '1'; // root is at -1 - - const literal = type === PlainValue$4.Type.BLOCK_FOLDED ? false : type === PlainValue$4.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth, indent.length); - let header = literal ? '|' : '>'; - if (!value) return header + '\n'; - let wsStart = ''; - let wsEnd = ''; - value = value.replace(/[\n\t ]*$/, ws => { - const n = ws.indexOf('\n'); - - if (n === -1) { - header += '-'; // strip - } else if (value === ws || n !== ws.length - 1) { - header += '+'; // keep - - if (onChompKeep) onChompKeep(); - } - - wsEnd = ws.replace(/\n$/, ''); - return ''; - }).replace(/^[\n ]*/, ws => { - if (ws.indexOf(' ') !== -1) header += indentSize; - const m = ws.match(/ +$/); - - if (m) { - wsStart = ws.slice(0, -m[0].length); - return m[0]; - } else { - wsStart = ws; - return ''; - } - }); - if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`); - if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`); - - if (comment) { - header += ' #' + comment.replace(/ ?[\r\n]+/g, ' '); - if (onComment) onComment(); - } - - if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`; - - if (literal) { - value = value.replace(/\n+/g, `$&${indent}`); - return `${header}\n${indent}${wsStart}${value}${wsEnd}`; - } - - value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded - // ^ ind.line ^ empty ^ capture next empty lines only at end of indent - .replace(/\n+/g, `$&${indent}`); - const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold); - return `${header}\n${indent}${body}`; -} - -function plainString(item, ctx, onComment, onChompKeep) { - const { - comment, - type, - value - } = item; - const { - actualString, - implicitKey, - indent, - inFlow - } = ctx; - - if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) { - return doubleQuotedString(value, ctx); - } - - if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { - // not allowed: - // - empty string, '-' or '?' - // - start with an indicator character (except [?:-]) or /[?-] / - // - '\n ', ': ' or ' \n' anywhere - // - '#' not preceded by a non-space char - // - end with ' ' or ':' - return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); - } - - if (!implicitKey && !inFlow && type !== PlainValue$4.Type.PLAIN && value.indexOf('\n') !== -1) { - // Where allowed & type not set explicitly, prefer block style for multiline strings - return blockString(item, ctx, onComment, onChompKeep); - } - - if (indent === '' && containsDocumentMarker(value)) { - ctx.forceBlockIndent = true; - return blockString(item, ctx, onComment, onChompKeep); - } - - const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and - // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), - // and others in v1.1. - - if (actualString) { - const { - tags - } = ctx.doc.schema; - const resolved = resolveScalar(str, tags, tags.scalarFallback).value; - if (typeof resolved !== 'string') return doubleQuotedString(value, ctx); - } - - const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx)); - - if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { - if (onComment) onComment(); - return addCommentBefore(body, indent, comment); - } - - return body; -} - -function stringifyString(item, ctx, onComment, onChompKeep) { - const { - defaultType - } = strOptions; - const { - implicitKey, - inFlow - } = ctx; - let { - type, - value - } = item; - - if (typeof value !== 'string') { - value = String(value); - item = Object.assign({}, item, { - value - }); - } - - const _stringify = _type => { - switch (_type) { - case PlainValue$4.Type.BLOCK_FOLDED: - case PlainValue$4.Type.BLOCK_LITERAL: - return blockString(item, ctx, onComment, onChompKeep); - - case PlainValue$4.Type.QUOTE_DOUBLE: - return doubleQuotedString(value, ctx); - - case PlainValue$4.Type.QUOTE_SINGLE: - return singleQuotedString(value, ctx); - - case PlainValue$4.Type.PLAIN: - return plainString(item, ctx, onComment, onChompKeep); - - default: - return null; - } - }; - - if (type !== PlainValue$4.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) { - // force double quotes on control characters - type = PlainValue$4.Type.QUOTE_DOUBLE; - } else if ((implicitKey || inFlow) && (type === PlainValue$4.Type.BLOCK_FOLDED || type === PlainValue$4.Type.BLOCK_LITERAL)) { - // should not happen; blocks are not valid inside flow containers - type = PlainValue$4.Type.QUOTE_DOUBLE; - } - - let res = _stringify(type); - - if (res === null) { - res = _stringify(defaultType); - if (res === null) throw new Error(`Unsupported default string type ${defaultType}`); - } - - return res; -} - -function stringifyNumber({ - format, - minFractionDigits, - tag, - value -}) { - if (typeof value === 'bigint') return String(value); - if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf'; - let n = JSON.stringify(value); - - if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) { - let i = n.indexOf('.'); - - if (i < 0) { - i = n.length; - n += '.'; - } - - let d = minFractionDigits - (n.length - i - 1); - - while (d-- > 0) n += '0'; - } - - return n; -} - -function checkFlowCollectionEnd(errors, cst) { - let char, name; - - switch (cst.type) { - case PlainValue$4.Type.FLOW_MAP: - char = '}'; - name = 'flow map'; - break; - - case PlainValue$4.Type.FLOW_SEQ: - char = ']'; - name = 'flow sequence'; - break; - - default: - errors.push(new PlainValue$4.YAMLSemanticError(cst, 'Not a flow collection!?')); - return; - } - - let lastItem; - - for (let i = cst.items.length - 1; i >= 0; --i) { - const item = cst.items[i]; - - if (!item || item.type !== PlainValue$4.Type.COMMENT) { - lastItem = item; - break; - } - } - - if (lastItem && lastItem.char !== char) { - const msg = `Expected ${name} to end with ${char}`; - let err; - - if (typeof lastItem.offset === 'number') { - err = new PlainValue$4.YAMLSemanticError(cst, msg); - err.offset = lastItem.offset + 1; - } else { - err = new PlainValue$4.YAMLSemanticError(lastItem, msg); - if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start; - } - - errors.push(err); - } -} -function checkFlowCommentSpace(errors, comment) { - const prev = comment.context.src[comment.range.start - 1]; - - if (prev !== '\n' && prev !== '\t' && prev !== ' ') { - const msg = 'Comments must be separated from other tokens by white space characters'; - errors.push(new PlainValue$4.YAMLSemanticError(comment, msg)); - } -} -function getLongKeyError(source, key) { - const sk = String(key); - const k = sk.substr(0, 8) + '...' + sk.substr(-8); - return new PlainValue$4.YAMLSemanticError(source, `The "${k}" key is too long`); -} -function resolveComments(collection, comments) { - for (const { - afterKey, - before, - comment - } of comments) { - let item = collection.items[before]; - - if (!item) { - if (comment !== undefined) { - if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment; - } - } else { - if (afterKey && item.value) item = item.value; - - if (comment === undefined) { - if (afterKey || !item.commentBefore) item.spaceBefore = true; - } else { - if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment; - } - } - } -} - -// on error, will return { str: string, errors: Error[] } -function resolveString(doc, node) { - const res = node.strValue; - if (!res) return ''; - if (typeof res === 'string') return res; - res.errors.forEach(error => { - if (!error.source) error.source = node; - doc.errors.push(error); - }); - return res.str; -} - -function resolveTagHandle(doc, node) { - const { - handle, - suffix - } = node.tag; - let prefix = doc.tagPrefixes.find(p => p.handle === handle); - - if (!prefix) { - const dtp = doc.getDefaults().tagPrefixes; - if (dtp) prefix = dtp.find(p => p.handle === handle); - if (!prefix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`); - } - - if (!suffix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag has no suffix.`); - - if (handle === '!' && (doc.version || doc.options.version) === '1.0') { - if (suffix[0] === '^') { - doc.warnings.push(new PlainValue$4.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported')); - return suffix; - } - - if (/[:/]/.test(suffix)) { - // word/foo -> tag:word.yaml.org,2002:foo - const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i); - return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`; - } - } - - return prefix.prefix + decodeURIComponent(suffix); -} - -function resolveTagName(doc, node) { - const { - tag, - type - } = node; - let nonSpecific = false; - - if (tag) { - const { - handle, - suffix, - verbatim - } = tag; - - if (verbatim) { - if (verbatim !== '!' && verbatim !== '!!') return verbatim; - const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`; - doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); - } else if (handle === '!' && !suffix) { - nonSpecific = true; - } else { - try { - return resolveTagHandle(doc, node); - } catch (error) { - doc.errors.push(error); - } - } - } - - switch (type) { - case PlainValue$4.Type.BLOCK_FOLDED: - case PlainValue$4.Type.BLOCK_LITERAL: - case PlainValue$4.Type.QUOTE_DOUBLE: - case PlainValue$4.Type.QUOTE_SINGLE: - return PlainValue$4.defaultTags.STR; - - case PlainValue$4.Type.FLOW_MAP: - case PlainValue$4.Type.MAP: - return PlainValue$4.defaultTags.MAP; - - case PlainValue$4.Type.FLOW_SEQ: - case PlainValue$4.Type.SEQ: - return PlainValue$4.defaultTags.SEQ; - - case PlainValue$4.Type.PLAIN: - return nonSpecific ? PlainValue$4.defaultTags.STR : null; - - default: - return null; - } -} - -function resolveByTagName(doc, node, tagName) { - const { - tags - } = doc.schema; - const matchWithTest = []; - - for (const tag of tags) { - if (tag.tag === tagName) { - if (tag.test) matchWithTest.push(tag);else { - const res = tag.resolve(doc, node); - return res instanceof Collection ? res : new Scalar(res); - } - } - } - - const str = resolveString(doc, node); - if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback); - return null; -} - -function getFallbackTagName({ - type -}) { - switch (type) { - case PlainValue$4.Type.FLOW_MAP: - case PlainValue$4.Type.MAP: - return PlainValue$4.defaultTags.MAP; - - case PlainValue$4.Type.FLOW_SEQ: - case PlainValue$4.Type.SEQ: - return PlainValue$4.defaultTags.SEQ; - - default: - return PlainValue$4.defaultTags.STR; - } -} - -function resolveTag(doc, node, tagName) { - try { - const res = resolveByTagName(doc, node, tagName); - - if (res) { - if (tagName && node.tag) res.tag = tagName; - return res; - } - } catch (error) { - /* istanbul ignore if */ - if (!error.source) error.source = node; - doc.errors.push(error); - return null; - } - - try { - const fallback = getFallbackTagName(node); - if (!fallback) throw new Error(`The tag ${tagName} is unavailable`); - const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`; - doc.warnings.push(new PlainValue$4.YAMLWarning(node, msg)); - const res = resolveByTagName(doc, node, fallback); - res.tag = tagName; - return res; - } catch (error) { - const refError = new PlainValue$4.YAMLReferenceError(node, error.message); - refError.stack = error.stack; - doc.errors.push(refError); - return null; - } -} - -const isCollectionItem = node => { - if (!node) return false; - const { - type - } = node; - return type === PlainValue$4.Type.MAP_KEY || type === PlainValue$4.Type.MAP_VALUE || type === PlainValue$4.Type.SEQ_ITEM; -}; - -function resolveNodeProps(errors, node) { - const comments = { - before: [], - after: [] - }; - let hasAnchor = false; - let hasTag = false; - const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props; - - for (const { - start, - end - } of props) { - switch (node.context.src[start]) { - case PlainValue$4.Char.COMMENT: - { - if (!node.commentHasRequiredWhitespace(start)) { - const msg = 'Comments must be separated from other tokens by white space characters'; - errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); - } - - const { - header, - valueRange - } = node; - const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before; - cc.push(node.context.src.slice(start + 1, end)); - break; - } - // Actual anchor & tag resolution is handled by schema, here we just complain - - case PlainValue$4.Char.ANCHOR: - if (hasAnchor) { - const msg = 'A node can have at most one anchor'; - errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); - } - - hasAnchor = true; - break; - - case PlainValue$4.Char.TAG: - if (hasTag) { - const msg = 'A node can have at most one tag'; - errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); - } - - hasTag = true; - break; - } - } - - return { - comments, - hasAnchor, - hasTag - }; -} - -function resolveNodeValue(doc, node) { - const { - anchors, - errors, - schema - } = doc; - - if (node.type === PlainValue$4.Type.ALIAS) { - const name = node.rawValue; - const src = anchors.getNode(name); - - if (!src) { - const msg = `Aliased anchor not found: ${name}`; - errors.push(new PlainValue$4.YAMLReferenceError(node, msg)); - return null; - } // Lazy resolution for circular references - - - const res = new Alias(src); - - anchors._cstAliases.push(res); - - return res; - } - - const tagName = resolveTagName(doc, node); - if (tagName) return resolveTag(doc, node, tagName); - - if (node.type !== PlainValue$4.Type.PLAIN) { - const msg = `Failed to resolve ${node.type} node here`; - errors.push(new PlainValue$4.YAMLSyntaxError(node, msg)); - return null; - } - - try { - const str = resolveString(doc, node); - return resolveScalar(str, schema.tags, schema.tags.scalarFallback); - } catch (error) { - if (!error.source) error.source = node; - errors.push(error); - return null; - } -} // sets node.resolved on success - - -function resolveNode(doc, node) { - if (!node) return null; - if (node.error) doc.errors.push(node.error); - const { - comments, - hasAnchor, - hasTag - } = resolveNodeProps(doc.errors, node); - - if (hasAnchor) { - const { - anchors - } = doc; - const name = node.anchor; - const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor - // name have already been resolved, so it may safely be renamed. - - if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as - // anchors need to be available during resolution to allow for - // circular references. - - anchors.map[name] = node; - } - - if (node.type === PlainValue$4.Type.ALIAS && (hasAnchor || hasTag)) { - const msg = 'An alias node must not specify any properties'; - doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); - } - - const res = resolveNodeValue(doc, node); - - if (res) { - res.range = [node.range.start, node.range.end]; - if (doc.options.keepCstNodes) res.cstNode = node; - if (doc.options.keepNodeTypes) res.type = node.type; - const cb = comments.before.join('\n'); - - if (cb) { - res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb; - } - - const ca = comments.after.join('\n'); - if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca; - } - - return node.resolved = res; -} - -function resolveMap(doc, cst) { - if (cst.type !== PlainValue$4.Type.MAP && cst.type !== PlainValue$4.Type.FLOW_MAP) { - const msg = `A ${cst.type} node cannot be resolved as a mapping`; - doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg)); - return null; - } - - const { - comments, - items - } = cst.type === PlainValue$4.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst); - const map = new YAMLMap(); - map.items = items; - resolveComments(map, comments); - let hasCollectionKey = false; - - for (let i = 0; i < items.length; ++i) { - const { - key: iKey - } = items[i]; - if (iKey instanceof Collection) hasCollectionKey = true; - - if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) { - items[i] = new Merge(items[i]); - const sources = items[i].value.items; - let error = null; - sources.some(node => { - if (node instanceof Alias) { - // During parsing, alias sources are CST nodes; to account for - // circular references their resolved values can't be used here. - const { - type - } = node.source; - if (type === PlainValue$4.Type.MAP || type === PlainValue$4.Type.FLOW_MAP) return false; - return error = 'Merge nodes aliases can only point to maps'; - } - - return error = 'Merge nodes can only have Alias nodes as values'; - }); - if (error) doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, error)); - } else { - for (let j = i + 1; j < items.length; ++j) { - const { - key: jKey - } = items[j]; - - if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) { - const msg = `Map keys must be unique; "${iKey}" is repeated`; - doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, msg)); - break; - } - } - } - } - - if (hasCollectionKey && !doc.options.mapAsMap) { - const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; - doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn)); - } - - cst.resolved = map; - return map; -} - -const valueHasPairComment = ({ - context: { - lineStart, - node, - src - }, - props -}) => { - if (props.length === 0) return false; - const { - start - } = props[0]; - if (node && start > node.valueRange.start) return false; - if (src[start] !== PlainValue$4.Char.COMMENT) return false; - - for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false; - - return true; -}; - -function resolvePairComment(item, pair) { - if (!valueHasPairComment(item)) return; - const comment = item.getPropValue(0, PlainValue$4.Char.COMMENT, true); - let found = false; - const cb = pair.value.commentBefore; - - if (cb && cb.startsWith(comment)) { - pair.value.commentBefore = cb.substr(comment.length + 1); - found = true; - } else { - const cc = pair.value.comment; - - if (!item.node && cc && cc.startsWith(comment)) { - pair.value.comment = cc.substr(comment.length + 1); - found = true; - } - } - - if (found) pair.comment = comment; -} - -function resolveBlockMapItems(doc, cst) { - const comments = []; - const items = []; - let key = undefined; - let keyStart = null; - - for (let i = 0; i < cst.items.length; ++i) { - const item = cst.items[i]; - - switch (item.type) { - case PlainValue$4.Type.BLANK_LINE: - comments.push({ - afterKey: !!key, - before: items.length - }); - break; - - case PlainValue$4.Type.COMMENT: - comments.push({ - afterKey: !!key, - before: items.length, - comment: item.comment - }); - break; - - case PlainValue$4.Type.MAP_KEY: - if (key !== undefined) items.push(new Pair(key)); - if (item.error) doc.errors.push(item.error); - key = resolveNode(doc, item.node); - keyStart = null; - break; - - case PlainValue$4.Type.MAP_VALUE: - { - if (key === undefined) key = null; - if (item.error) doc.errors.push(item.error); - - if (!item.context.atLineStart && item.node && item.node.type === PlainValue$4.Type.MAP && !item.node.context.atLineStart) { - const msg = 'Nested mappings are not allowed in compact mappings'; - doc.errors.push(new PlainValue$4.YAMLSemanticError(item.node, msg)); - } - - let valueNode = item.node; - - if (!valueNode && item.props.length > 0) { - // Comments on an empty mapping value need to be preserved, so we - // need to construct a minimal empty node here to use instead of the - // missing `item.node`. -- eemeli/yaml#19 - valueNode = new PlainValue$4.PlainValue(PlainValue$4.Type.PLAIN, []); - valueNode.context = { - parent: item, - src: item.context.src - }; - const pos = item.range.start + 1; - valueNode.range = { - start: pos, - end: pos - }; - valueNode.valueRange = { - start: pos, - end: pos - }; - - if (typeof item.range.origStart === 'number') { - const origPos = item.range.origStart + 1; - valueNode.range.origStart = valueNode.range.origEnd = origPos; - valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos; - } - } - - const pair = new Pair(key, resolveNode(doc, valueNode)); - resolvePairComment(item, pair); - items.push(pair); - - if (key && typeof keyStart === 'number') { - if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); - } - - key = undefined; - keyStart = null; - } - break; - - default: - if (key !== undefined) items.push(new Pair(key)); - key = resolveNode(doc, item); - keyStart = item.range.start; - if (item.error) doc.errors.push(item.error); - - next: for (let j = i + 1;; ++j) { - const nextItem = cst.items[j]; - - switch (nextItem && nextItem.type) { - case PlainValue$4.Type.BLANK_LINE: - case PlainValue$4.Type.COMMENT: - continue next; - - case PlainValue$4.Type.MAP_VALUE: - break next; - - default: - { - const msg = 'Implicit map keys need to be followed by map values'; - doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); - break next; - } - } - } - - if (item.valueRangeContainsNewline) { - const msg = 'Implicit map keys need to be on a single line'; - doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); - } - - } - } - - if (key !== undefined) items.push(new Pair(key)); - return { - comments, - items - }; -} - -function resolveFlowMapItems(doc, cst) { - const comments = []; - const items = []; - let key = undefined; - let explicitKey = false; - let next = '{'; - - for (let i = 0; i < cst.items.length; ++i) { - const item = cst.items[i]; - - if (typeof item.char === 'string') { - const { - char, - offset - } = item; - - if (char === '?' && key === undefined && !explicitKey) { - explicitKey = true; - next = ':'; - continue; - } - - if (char === ':') { - if (key === undefined) key = null; - - if (next === ':') { - next = ','; - continue; - } - } else { - if (explicitKey) { - if (key === undefined && char !== ',') key = null; - explicitKey = false; - } - - if (key !== undefined) { - items.push(new Pair(key)); - key = undefined; - - if (char === ',') { - next = ':'; - continue; - } - } - } - - if (char === '}') { - if (i === cst.items.length - 1) continue; - } else if (char === next) { - next = ':'; - continue; - } - - const msg = `Flow map contains an unexpected ${char}`; - const err = new PlainValue$4.YAMLSyntaxError(cst, msg); - err.offset = offset; - doc.errors.push(err); - } else if (item.type === PlainValue$4.Type.BLANK_LINE) { - comments.push({ - afterKey: !!key, - before: items.length - }); - } else if (item.type === PlainValue$4.Type.COMMENT) { - checkFlowCommentSpace(doc.errors, item); - comments.push({ - afterKey: !!key, - before: items.length, - comment: item.comment - }); - } else if (key === undefined) { - if (next === ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Separator , missing in flow map')); - key = resolveNode(doc, item); - } else { - if (next !== ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Indicator : missing in flow map entry')); - items.push(new Pair(key, resolveNode(doc, item))); - key = undefined; - explicitKey = false; - } - } - - checkFlowCollectionEnd(doc.errors, cst); - if (key !== undefined) items.push(new Pair(key)); - return { - comments, - items - }; -} - -function resolveSeq$3(doc, cst) { - if (cst.type !== PlainValue$4.Type.SEQ && cst.type !== PlainValue$4.Type.FLOW_SEQ) { - const msg = `A ${cst.type} node cannot be resolved as a sequence`; - doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg)); - return null; - } - - const { - comments, - items - } = cst.type === PlainValue$4.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst); - const seq = new YAMLSeq(); - seq.items = items; - resolveComments(seq, comments); - - if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection)) { - const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; - doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn)); - } - - cst.resolved = seq; - return seq; -} - -function resolveBlockSeqItems(doc, cst) { - const comments = []; - const items = []; - - for (let i = 0; i < cst.items.length; ++i) { - const item = cst.items[i]; - - switch (item.type) { - case PlainValue$4.Type.BLANK_LINE: - comments.push({ - before: items.length - }); - break; - - case PlainValue$4.Type.COMMENT: - comments.push({ - comment: item.comment, - before: items.length - }); - break; - - case PlainValue$4.Type.SEQ_ITEM: - if (item.error) doc.errors.push(item.error); - items.push(resolveNode(doc, item.node)); - - if (item.hasProps) { - const msg = 'Sequence items cannot have tags or anchors before the - indicator'; - doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); - } - - break; - - default: - if (item.error) doc.errors.push(item.error); - doc.errors.push(new PlainValue$4.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`)); - } - } - - return { - comments, - items - }; -} - -function resolveFlowSeqItems(doc, cst) { - const comments = []; - const items = []; - let explicitKey = false; - let key = undefined; - let keyStart = null; - let next = '['; - let prevItem = null; - - for (let i = 0; i < cst.items.length; ++i) { - const item = cst.items[i]; - - if (typeof item.char === 'string') { - const { - char, - offset - } = item; - - if (char !== ':' && (explicitKey || key !== undefined)) { - if (explicitKey && key === undefined) key = next ? items.pop() : null; - items.push(new Pair(key)); - explicitKey = false; - key = undefined; - keyStart = null; - } - - if (char === next) { - next = null; - } else if (!next && char === '?') { - explicitKey = true; - } else if (next !== '[' && char === ':' && key === undefined) { - if (next === ',') { - key = items.pop(); - - if (key instanceof Pair) { - const msg = 'Chaining flow sequence pairs is invalid'; - const err = new PlainValue$4.YAMLSemanticError(cst, msg); - err.offset = offset; - doc.errors.push(err); - } - - if (!explicitKey && typeof keyStart === 'number') { - const keyEnd = item.range ? item.range.start : item.offset; - if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); - const { - src - } = prevItem.context; - - for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') { - const msg = 'Implicit keys of flow sequence pairs need to be on a single line'; - doc.errors.push(new PlainValue$4.YAMLSemanticError(prevItem, msg)); - break; - } - } - } else { - key = null; - } - - keyStart = null; - explicitKey = false; - next = null; - } else if (next === '[' || char !== ']' || i < cst.items.length - 1) { - const msg = `Flow sequence contains an unexpected ${char}`; - const err = new PlainValue$4.YAMLSyntaxError(cst, msg); - err.offset = offset; - doc.errors.push(err); - } - } else if (item.type === PlainValue$4.Type.BLANK_LINE) { - comments.push({ - before: items.length - }); - } else if (item.type === PlainValue$4.Type.COMMENT) { - checkFlowCommentSpace(doc.errors, item); - comments.push({ - comment: item.comment, - before: items.length - }); - } else { - if (next) { - const msg = `Expected a ${next} in flow sequence`; - doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); - } - - const value = resolveNode(doc, item); - - if (key === undefined) { - items.push(value); - prevItem = item; - } else { - items.push(new Pair(key, value)); - key = undefined; - } - - keyStart = item.range.start; - next = ','; - } - } - - checkFlowCollectionEnd(doc.errors, cst); - if (key !== undefined) items.push(new Pair(key)); - return { - comments, - items - }; -} - -resolveSeqD03cb037.Alias = Alias; -resolveSeqD03cb037.Collection = Collection; -resolveSeqD03cb037.Merge = Merge; -resolveSeqD03cb037.Node = Node$1; -resolveSeqD03cb037.Pair = Pair; -resolveSeqD03cb037.Scalar = Scalar; -resolveSeqD03cb037.YAMLMap = YAMLMap; -resolveSeqD03cb037.YAMLSeq = YAMLSeq; -resolveSeqD03cb037.addComment = addComment; -resolveSeqD03cb037.binaryOptions = binaryOptions; -resolveSeqD03cb037.boolOptions = boolOptions; -resolveSeqD03cb037.findPair = findPair; -resolveSeqD03cb037.intOptions = intOptions; -resolveSeqD03cb037.isEmptyPath = isEmptyPath; -resolveSeqD03cb037.nullOptions = nullOptions; -resolveSeqD03cb037.resolveMap = resolveMap; -resolveSeqD03cb037.resolveNode = resolveNode; -resolveSeqD03cb037.resolveSeq = resolveSeq$3; -resolveSeqD03cb037.resolveString = resolveString; -resolveSeqD03cb037.strOptions = strOptions; -resolveSeqD03cb037.stringifyNumber = stringifyNumber; -resolveSeqD03cb037.stringifyString = stringifyString; -resolveSeqD03cb037.toJSON = toJSON; - -var Schema88e323a7 = {}; - -var warnings1000a372 = {}; - -var PlainValue$3 = PlainValueEc8e588e; -var resolveSeq$2 = resolveSeqD03cb037; - -/* global atob, btoa, Buffer */ -const binary = { - identify: value => value instanceof Uint8Array, - // Buffer inherits from Uint8Array - default: false, - tag: 'tag:yaml.org,2002:binary', - - /** - * Returns a Buffer in node and an Uint8Array in browsers - * - * To use the resulting buffer as an image, you'll want to do something like: - * - * const blob = new Blob([buffer], { type: 'image/jpeg' }) - * document.querySelector('#photo').src = URL.createObjectURL(blob) - */ - resolve: (doc, node) => { - const src = resolveSeq$2.resolveString(doc, node); - - if (typeof Buffer === 'function') { - return Buffer.from(src, 'base64'); - } else if (typeof atob === 'function') { - // On IE 11, atob() can't handle newlines - const str = atob(src.replace(/[\n\r]/g, '')); - const buffer = new Uint8Array(str.length); - - for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i); - - return buffer; - } else { - const msg = 'This environment does not support reading binary tags; either Buffer or atob is required'; - doc.errors.push(new PlainValue$3.YAMLReferenceError(node, msg)); - return null; - } - }, - options: resolveSeq$2.binaryOptions, - stringify: ({ - comment, - type, - value - }, ctx, onComment, onChompKeep) => { - let src; - - if (typeof Buffer === 'function') { - src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64'); - } else if (typeof btoa === 'function') { - let s = ''; - - for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]); - - src = btoa(s); - } else { - throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); - } - - if (!type) type = resolveSeq$2.binaryOptions.defaultType; - - if (type === PlainValue$3.Type.QUOTE_DOUBLE) { - value = src; - } else { - const { - lineWidth - } = resolveSeq$2.binaryOptions; - const n = Math.ceil(src.length / lineWidth); - const lines = new Array(n); - - for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { - lines[i] = src.substr(o, lineWidth); - } - - value = lines.join(type === PlainValue$3.Type.BLOCK_LITERAL ? '\n' : ' '); - } - - return resolveSeq$2.stringifyString({ - comment, - type, - value - }, ctx, onComment, onChompKeep); - } -}; - -function parsePairs(doc, cst) { - const seq = resolveSeq$2.resolveSeq(doc, cst); - - for (let i = 0; i < seq.items.length; ++i) { - let item = seq.items[i]; - if (item instanceof resolveSeq$2.Pair) continue;else if (item instanceof resolveSeq$2.YAMLMap) { - if (item.items.length > 1) { - const msg = 'Each pair must have its own sequence indicator'; - throw new PlainValue$3.YAMLSemanticError(cst, msg); - } - - const pair = item.items[0] || new resolveSeq$2.Pair(); - if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore; - if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment; - item = pair; - } - seq.items[i] = item instanceof resolveSeq$2.Pair ? item : new resolveSeq$2.Pair(item); - } - - return seq; -} -function createPairs(schema, iterable, ctx) { - const pairs = new resolveSeq$2.YAMLSeq(schema); - pairs.tag = 'tag:yaml.org,2002:pairs'; - - for (const it of iterable) { - let key, value; - - if (Array.isArray(it)) { - if (it.length === 2) { - key = it[0]; - value = it[1]; - } else throw new TypeError(`Expected [key, value] tuple: ${it}`); - } else if (it && it instanceof Object) { - const keys = Object.keys(it); - - if (keys.length === 1) { - key = keys[0]; - value = it[key]; - } else throw new TypeError(`Expected { key: value } tuple: ${it}`); - } else { - key = it; - } - - const pair = schema.createPair(key, value, ctx); - pairs.items.push(pair); - } - - return pairs; -} -const pairs = { - default: false, - tag: 'tag:yaml.org,2002:pairs', - resolve: parsePairs, - createNode: createPairs -}; - -class YAMLOMap extends resolveSeq$2.YAMLSeq { - constructor() { - super(); - - PlainValue$3._defineProperty(this, "add", resolveSeq$2.YAMLMap.prototype.add.bind(this)); - - PlainValue$3._defineProperty(this, "delete", resolveSeq$2.YAMLMap.prototype.delete.bind(this)); - - PlainValue$3._defineProperty(this, "get", resolveSeq$2.YAMLMap.prototype.get.bind(this)); - - PlainValue$3._defineProperty(this, "has", resolveSeq$2.YAMLMap.prototype.has.bind(this)); - - PlainValue$3._defineProperty(this, "set", resolveSeq$2.YAMLMap.prototype.set.bind(this)); - - this.tag = YAMLOMap.tag; - } - - toJSON(_, ctx) { - const map = new Map(); - if (ctx && ctx.onCreate) ctx.onCreate(map); - - for (const pair of this.items) { - let key, value; - - if (pair instanceof resolveSeq$2.Pair) { - key = resolveSeq$2.toJSON(pair.key, '', ctx); - value = resolveSeq$2.toJSON(pair.value, key, ctx); - } else { - key = resolveSeq$2.toJSON(pair, '', ctx); - } - - if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys'); - map.set(key, value); - } - - return map; - } - -} - -PlainValue$3._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap'); - -function parseOMap(doc, cst) { - const pairs = parsePairs(doc, cst); - const seenKeys = []; - - for (const { - key - } of pairs.items) { - if (key instanceof resolveSeq$2.Scalar) { - if (seenKeys.includes(key.value)) { - const msg = 'Ordered maps must not include duplicate keys'; - throw new PlainValue$3.YAMLSemanticError(cst, msg); - } else { - seenKeys.push(key.value); - } - } - } - - return Object.assign(new YAMLOMap(), pairs); -} - -function createOMap(schema, iterable, ctx) { - const pairs = createPairs(schema, iterable, ctx); - const omap = new YAMLOMap(); - omap.items = pairs.items; - return omap; -} - -const omap = { - identify: value => value instanceof Map, - nodeClass: YAMLOMap, - default: false, - tag: 'tag:yaml.org,2002:omap', - resolve: parseOMap, - createNode: createOMap -}; - -class YAMLSet extends resolveSeq$2.YAMLMap { - constructor() { - super(); - this.tag = YAMLSet.tag; - } - - add(key) { - const pair = key instanceof resolveSeq$2.Pair ? key : new resolveSeq$2.Pair(key); - const prev = resolveSeq$2.findPair(this.items, pair.key); - if (!prev) this.items.push(pair); - } - - get(key, keepPair) { - const pair = resolveSeq$2.findPair(this.items, key); - return !keepPair && pair instanceof resolveSeq$2.Pair ? pair.key instanceof resolveSeq$2.Scalar ? pair.key.value : pair.key : pair; - } - - set(key, value) { - if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); - const prev = resolveSeq$2.findPair(this.items, key); - - if (prev && !value) { - this.items.splice(this.items.indexOf(prev), 1); - } else if (!prev && value) { - this.items.push(new resolveSeq$2.Pair(key)); - } - } - - toJSON(_, ctx) { - return super.toJSON(_, ctx, Set); - } - - toString(ctx, onComment, onChompKeep) { - if (!ctx) return JSON.stringify(this); - if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values'); - } - -} - -PlainValue$3._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set'); - -function parseSet(doc, cst) { - const map = resolveSeq$2.resolveMap(doc, cst); - if (!map.hasAllNullValues()) throw new PlainValue$3.YAMLSemanticError(cst, 'Set items must all have null values'); - return Object.assign(new YAMLSet(), map); -} - -function createSet(schema, iterable, ctx) { - const set = new YAMLSet(); - - for (const value of iterable) set.items.push(schema.createPair(value, null, ctx)); - - return set; -} - -const set = { - identify: value => value instanceof Set, - nodeClass: YAMLSet, - default: false, - tag: 'tag:yaml.org,2002:set', - resolve: parseSet, - createNode: createSet -}; - -const parseSexagesimal = (sign, parts) => { - const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0); - return sign === '-' ? -n : n; -}; // hhhh:mm:ss.sss - - -const stringifySexagesimal = ({ - value -}) => { - if (isNaN(value) || !isFinite(value)) return resolveSeq$2.stringifyNumber(value); - let sign = ''; - - if (value < 0) { - sign = '-'; - value = Math.abs(value); - } - - const parts = [value % 60]; // seconds, including ms - - if (value < 60) { - parts.unshift(0); // at least one : is required - } else { - value = Math.round((value - parts[0]) / 60); - parts.unshift(value % 60); // minutes - - if (value >= 60) { - value = Math.round((value - parts[0]) / 60); - parts.unshift(value); // hours - } - } - - return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error - ; -}; - -const intTime = { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'TIME', - test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/, - resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), - stringify: stringifySexagesimal -}; -const floatTime = { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - format: 'TIME', - test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/, - resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), - stringify: stringifySexagesimal -}; -const timestamp = { - identify: value => value instanceof Date, - default: true, - tag: 'tag:yaml.org,2002:timestamp', - // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part - // may be omitted altogether, resulting in a date format. In such a case, the time part is - // assumed to be 00:00:00Z (start of day, UTC). - test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd - '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace - '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? - '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 - ')?' + ')$'), - resolve: (str, year, month, day, hour, minute, second, millisec, tz) => { - if (millisec) millisec = (millisec + '00').substr(1, 3); - let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0); - - if (tz && tz !== 'Z') { - let d = parseSexagesimal(tz[0], tz.slice(1)); - if (Math.abs(d) < 30) d *= 60; - date -= 60000 * d; - } - - return new Date(date); - }, - stringify: ({ - value - }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '') -}; - -/* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */ -function shouldWarn(deprecation) { - const env = typeof process !== 'undefined' && process.env || {}; - - if (deprecation) { - if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS; - return !env.YAML_SILENCE_DEPRECATION_WARNINGS; - } - - if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS; - return !env.YAML_SILENCE_WARNINGS; -} - -function warn(warning, type) { - if (shouldWarn(false)) { - const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to - // https://github.com/facebook/jest/issues/2549 - - if (emit) emit(warning, type);else { - // eslint-disable-next-line no-console - console.warn(type ? `${type}: ${warning}` : warning); - } - } -} -function warnFileDeprecation(filename) { - if (shouldWarn(true)) { - const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/'); - warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning'); - } -} -const warned = {}; -function warnOptionDeprecation(name, alternative) { - if (!warned[name] && shouldWarn(true)) { - warned[name] = true; - let msg = `The option '${name}' will be removed in a future release`; - msg += alternative ? `, use '${alternative}' instead.` : '.'; - warn(msg, 'DeprecationWarning'); - } -} - -warnings1000a372.binary = binary; -warnings1000a372.floatTime = floatTime; -warnings1000a372.intTime = intTime; -warnings1000a372.omap = omap; -warnings1000a372.pairs = pairs; -warnings1000a372.set = set; -warnings1000a372.timestamp = timestamp; -warnings1000a372.warn = warn; -warnings1000a372.warnFileDeprecation = warnFileDeprecation; -warnings1000a372.warnOptionDeprecation = warnOptionDeprecation; - -var PlainValue$2 = PlainValueEc8e588e; -var resolveSeq$1 = resolveSeqD03cb037; -var warnings$1 = warnings1000a372; - -function createMap(schema, obj, ctx) { - const map = new resolveSeq$1.YAMLMap(schema); - - if (obj instanceof Map) { - for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx)); - } else if (obj && typeof obj === 'object') { - for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx)); - } - - if (typeof schema.sortMapEntries === 'function') { - map.items.sort(schema.sortMapEntries); - } - - return map; -} - -const map$1 = { - createNode: createMap, - default: true, - nodeClass: resolveSeq$1.YAMLMap, - tag: 'tag:yaml.org,2002:map', - resolve: resolveSeq$1.resolveMap -}; - -function createSeq(schema, obj, ctx) { - const seq = new resolveSeq$1.YAMLSeq(schema); - - if (obj && obj[Symbol.iterator]) { - for (const it of obj) { - const v = schema.createNode(it, ctx.wrapScalars, null, ctx); - seq.items.push(v); - } - } - - return seq; -} - -const seq = { - createNode: createSeq, - default: true, - nodeClass: resolveSeq$1.YAMLSeq, - tag: 'tag:yaml.org,2002:seq', - resolve: resolveSeq$1.resolveSeq -}; - -const string = { - identify: value => typeof value === 'string', - default: true, - tag: 'tag:yaml.org,2002:str', - resolve: resolveSeq$1.resolveString, - - stringify(item, ctx, onComment, onChompKeep) { - ctx = Object.assign({ - actualString: true - }, ctx); - return resolveSeq$1.stringifyString(item, ctx, onComment, onChompKeep); - }, - - options: resolveSeq$1.strOptions -}; - -const failsafe = [map$1, seq, string]; - -/* global BigInt */ - -const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value); - -const intResolve$1 = (src, part, radix) => resolveSeq$1.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix); - -function intStringify$1(node, radix, prefix) { - const { - value - } = node; - if (intIdentify$2(value) && value >= 0) return prefix + value.toString(radix); - return resolveSeq$1.stringifyNumber(node); -} - -const nullObj = { - identify: value => value == null, - createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, - default: true, - tag: 'tag:yaml.org,2002:null', - test: /^(?:~|[Nn]ull|NULL)?$/, - resolve: () => null, - options: resolveSeq$1.nullOptions, - stringify: () => resolveSeq$1.nullOptions.nullStr -}; -const boolObj = { - identify: value => typeof value === 'boolean', - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, - resolve: str => str[0] === 't' || str[0] === 'T', - options: resolveSeq$1.boolOptions, - stringify: ({ - value - }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr -}; -const octObj = { - identify: value => intIdentify$2(value) && value >= 0, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'OCT', - test: /^0o([0-7]+)$/, - resolve: (str, oct) => intResolve$1(str, oct, 8), - options: resolveSeq$1.intOptions, - stringify: node => intStringify$1(node, 8, '0o') -}; -const intObj = { - identify: intIdentify$2, - default: true, - tag: 'tag:yaml.org,2002:int', - test: /^[-+]?[0-9]+$/, - resolve: str => intResolve$1(str, str, 10), - options: resolveSeq$1.intOptions, - stringify: resolveSeq$1.stringifyNumber -}; -const hexObj = { - identify: value => intIdentify$2(value) && value >= 0, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'HEX', - test: /^0x([0-9a-fA-F]+)$/, - resolve: (str, hex) => intResolve$1(str, hex, 16), - options: resolveSeq$1.intOptions, - stringify: node => intStringify$1(node, 16, '0x') -}; -const nanObj = { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^(?:[-+]?\.inf|(\.nan))$/i, - resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, - stringify: resolveSeq$1.stringifyNumber -}; -const expObj = { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - format: 'EXP', - test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, - resolve: str => parseFloat(str), - stringify: ({ - value - }) => Number(value).toExponential() -}; -const floatObj = { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/, - - resolve(str, frac1, frac2) { - const frac = frac1 || frac2; - const node = new resolveSeq$1.Scalar(parseFloat(str)); - if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length; - return node; - }, - - stringify: resolveSeq$1.stringifyNumber -}; -const core$2 = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]); - -/* global BigInt */ - -const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value); - -const stringifyJSON = ({ - value -}) => JSON.stringify(value); - -const json = [map$1, seq, { - identify: value => typeof value === 'string', - default: true, - tag: 'tag:yaml.org,2002:str', - resolve: resolveSeq$1.resolveString, - stringify: stringifyJSON -}, { - identify: value => value == null, - createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, - default: true, - tag: 'tag:yaml.org,2002:null', - test: /^null$/, - resolve: () => null, - stringify: stringifyJSON -}, { - identify: value => typeof value === 'boolean', - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^true|false$/, - resolve: str => str === 'true', - stringify: stringifyJSON -}, { - identify: intIdentify$1, - default: true, - tag: 'tag:yaml.org,2002:int', - test: /^-?(?:0|[1-9][0-9]*)$/, - resolve: str => resolveSeq$1.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10), - stringify: ({ - value - }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) -}, { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, - resolve: str => parseFloat(str), - stringify: stringifyJSON -}]; - -json.scalarFallback = str => { - throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`); -}; - -/* global BigInt */ - -const boolStringify = ({ - value -}) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr; - -const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value); - -function intResolve(sign, src, radix) { - let str = src.replace(/_/g, ''); - - if (resolveSeq$1.intOptions.asBigInt) { - switch (radix) { - case 2: - str = `0b${str}`; - break; - - case 8: - str = `0o${str}`; - break; - - case 16: - str = `0x${str}`; - break; - } - - const n = BigInt(str); - return sign === '-' ? BigInt(-1) * n : n; - } - - const n = parseInt(str, radix); - return sign === '-' ? -1 * n : n; -} - -function intStringify(node, radix, prefix) { - const { - value - } = node; - - if (intIdentify(value)) { - const str = value.toString(radix); - return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; - } - - return resolveSeq$1.stringifyNumber(node); -} - -const yaml11 = failsafe.concat([{ - identify: value => value == null, - createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, - default: true, - tag: 'tag:yaml.org,2002:null', - test: /^(?:~|[Nn]ull|NULL)?$/, - resolve: () => null, - options: resolveSeq$1.nullOptions, - stringify: () => resolveSeq$1.nullOptions.nullStr -}, { - identify: value => typeof value === 'boolean', - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, - resolve: () => true, - options: resolveSeq$1.boolOptions, - stringify: boolStringify -}, { - identify: value => typeof value === 'boolean', - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i, - resolve: () => false, - options: resolveSeq$1.boolOptions, - stringify: boolStringify -}, { - identify: intIdentify, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'BIN', - test: /^([-+]?)0b([0-1_]+)$/, - resolve: (str, sign, bin) => intResolve(sign, bin, 2), - stringify: node => intStringify(node, 2, '0b') -}, { - identify: intIdentify, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'OCT', - test: /^([-+]?)0([0-7_]+)$/, - resolve: (str, sign, oct) => intResolve(sign, oct, 8), - stringify: node => intStringify(node, 8, '0') -}, { - identify: intIdentify, - default: true, - tag: 'tag:yaml.org,2002:int', - test: /^([-+]?)([0-9][0-9_]*)$/, - resolve: (str, sign, abs) => intResolve(sign, abs, 10), - stringify: resolveSeq$1.stringifyNumber -}, { - identify: intIdentify, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'HEX', - test: /^([-+]?)0x([0-9a-fA-F_]+)$/, - resolve: (str, sign, hex) => intResolve(sign, hex, 16), - stringify: node => intStringify(node, 16, '0x') -}, { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^(?:[-+]?\.inf|(\.nan))$/i, - resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, - stringify: resolveSeq$1.stringifyNumber -}, { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - format: 'EXP', - test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/, - resolve: str => parseFloat(str.replace(/_/g, '')), - stringify: ({ - value - }) => Number(value).toExponential() -}, { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/, - - resolve(str, frac) { - const node = new resolveSeq$1.Scalar(parseFloat(str.replace(/_/g, ''))); - - if (frac) { - const f = frac.replace(/_/g, ''); - if (f[f.length - 1] === '0') node.minFractionDigits = f.length; - } - - return node; - }, - - stringify: resolveSeq$1.stringifyNumber -}], warnings$1.binary, warnings$1.omap, warnings$1.pairs, warnings$1.set, warnings$1.intTime, warnings$1.floatTime, warnings$1.timestamp); - -const schemas = { - core: core$2, - failsafe, - json, - yaml11 -}; -const tags = { - binary: warnings$1.binary, - bool: boolObj, - float: floatObj, - floatExp: expObj, - floatNaN: nanObj, - floatTime: warnings$1.floatTime, - int: intObj, - intHex: hexObj, - intOct: octObj, - intTime: warnings$1.intTime, - map: map$1, - null: nullObj, - omap: warnings$1.omap, - pairs: warnings$1.pairs, - seq, - set: warnings$1.set, - timestamp: warnings$1.timestamp -}; - -function findTagObject(value, tagName, tags) { - if (tagName) { - const match = tags.filter(t => t.tag === tagName); - const tagObj = match.find(t => !t.format) || match[0]; - if (!tagObj) throw new Error(`Tag ${tagName} not found`); - return tagObj; - } // TODO: deprecate/remove class check - - - return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format); -} - -function createNode$1(value, tagName, ctx) { - if (value instanceof resolveSeq$1.Node) return value; - const { - defaultPrefix, - onTagObj, - prevObjects, - schema, - wrapScalars - } = ctx; - if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2); - let tagObj = findTagObject(value, tagName, schema.tags); - - if (!tagObj) { - if (typeof value.toJSON === 'function') value = value.toJSON(); - if (!value || typeof value !== 'object') return wrapScalars ? new resolveSeq$1.Scalar(value) : value; - tagObj = value instanceof Map ? map$1 : value[Symbol.iterator] ? seq : map$1; - } - - if (onTagObj) { - onTagObj(tagObj); - delete ctx.onTagObj; - } // Detect duplicate references to the same object & use Alias nodes for all - // after first. The `obj` wrapper allows for circular references to resolve. - - - const obj = { - value: undefined, - node: undefined - }; - - if (value && typeof value === 'object' && prevObjects) { - const prev = prevObjects.get(value); - - if (prev) { - const alias = new resolveSeq$1.Alias(prev); // leaves source dirty; must be cleaned by caller - - ctx.aliasNodes.push(alias); // defined along with prevObjects - - return alias; - } - - obj.value = value; - prevObjects.set(value, obj); - } - - obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq$1.Scalar(value) : value; - if (tagName && obj.node instanceof resolveSeq$1.Node) obj.node.tag = tagName; - return obj.node; -} - -function getSchemaTags(schemas, knownTags, customTags, schemaId) { - let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11' - - if (!tags) { - const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', '); - throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`); - } - - if (Array.isArray(customTags)) { - for (const tag of customTags) tags = tags.concat(tag); - } else if (typeof customTags === 'function') { - tags = customTags(tags.slice()); - } - - for (let i = 0; i < tags.length; ++i) { - const tag = tags[i]; - - if (typeof tag === 'string') { - const tagObj = knownTags[tag]; - - if (!tagObj) { - const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', '); - throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`); - } - - tags[i] = tagObj; - } - } - - return tags; -} - -const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; - -class Schema$2 { - // TODO: remove in v2 - // TODO: remove in v2 - constructor({ - customTags, - merge, - schema, - sortMapEntries, - tags: deprecatedCustomTags - }) { - this.merge = !!merge; - this.name = schema; - this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null; - if (!customTags && deprecatedCustomTags) warnings$1.warnOptionDeprecation('tags', 'customTags'); - this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema); - } - - createNode(value, wrapScalars, tagName, ctx) { - const baseCtx = { - defaultPrefix: Schema$2.defaultPrefix, - schema: this, - wrapScalars - }; - const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx; - return createNode$1(value, tagName, createCtx); - } - - createPair(key, value, ctx) { - if (!ctx) ctx = { - wrapScalars: true - }; - const k = this.createNode(key, ctx.wrapScalars, null, ctx); - const v = this.createNode(value, ctx.wrapScalars, null, ctx); - return new resolveSeq$1.Pair(k, v); - } - -} - -PlainValue$2._defineProperty(Schema$2, "defaultPrefix", PlainValue$2.defaultTagPrefix); - -PlainValue$2._defineProperty(Schema$2, "defaultTags", PlainValue$2.defaultTags); - -Schema88e323a7.Schema = Schema$2; - -var PlainValue$1 = PlainValueEc8e588e; -var resolveSeq = resolveSeqD03cb037; -var Schema$1 = Schema88e323a7; - -const defaultOptions$1 = { - anchorPrefix: 'a', - customTags: null, - indent: 2, - indentSeq: true, - keepCstNodes: false, - keepNodeTypes: true, - keepBlobsInJSON: true, - mapAsMap: false, - maxAliasCount: 100, - prettyErrors: false, - // TODO Set true in v2 - simpleKeys: false, - version: '1.2' -}; -const scalarOptions = { - get binary() { - return resolveSeq.binaryOptions; - }, - - set binary(opt) { - Object.assign(resolveSeq.binaryOptions, opt); - }, - - get bool() { - return resolveSeq.boolOptions; - }, - - set bool(opt) { - Object.assign(resolveSeq.boolOptions, opt); - }, - - get int() { - return resolveSeq.intOptions; - }, - - set int(opt) { - Object.assign(resolveSeq.intOptions, opt); - }, - - get null() { - return resolveSeq.nullOptions; - }, - - set null(opt) { - Object.assign(resolveSeq.nullOptions, opt); - }, - - get str() { - return resolveSeq.strOptions; - }, - - set str(opt) { - Object.assign(resolveSeq.strOptions, opt); - } - -}; -const documentOptions = { - '1.0': { - schema: 'yaml-1.1', - merge: true, - tagPrefixes: [{ - handle: '!', - prefix: PlainValue$1.defaultTagPrefix - }, { - handle: '!!', - prefix: 'tag:private.yaml.org,2002:' - }] - }, - 1.1: { - schema: 'yaml-1.1', - merge: true, - tagPrefixes: [{ - handle: '!', - prefix: '!' - }, { - handle: '!!', - prefix: PlainValue$1.defaultTagPrefix - }] - }, - 1.2: { - schema: 'core', - merge: false, - tagPrefixes: [{ - handle: '!', - prefix: '!' - }, { - handle: '!!', - prefix: PlainValue$1.defaultTagPrefix - }] - } -}; - -function stringifyTag(doc, tag) { - if ((doc.version || doc.options.version) === '1.0') { - const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/); - if (priv) return '!' + priv[1]; - const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/); - return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`; - } - - let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0); - - if (!p) { - const dtp = doc.getDefaults().tagPrefixes; - p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0); - } - - if (!p) return tag[0] === '!' ? tag : `!<${tag}>`; - const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({ - '!': '%21', - ',': '%2C', - '[': '%5B', - ']': '%5D', - '{': '%7B', - '}': '%7D' - })[ch]); - return p.handle + suffix; -} - -function getTagObject(tags, item) { - if (item instanceof resolveSeq.Alias) return resolveSeq.Alias; - - if (item.tag) { - const match = tags.filter(t => t.tag === item.tag); - if (match.length > 0) return match.find(t => t.format === item.format) || match[0]; - } - - let tagObj, obj; - - if (item instanceof resolveSeq.Scalar) { - obj = item.value; // TODO: deprecate/remove class check - - const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class); - tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format); - } else { - obj = item; - tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass); - } - - if (!tagObj) { - const name = obj && obj.constructor ? obj.constructor.name : typeof obj; - throw new Error(`Tag not resolved for ${name} value`); - } - - return tagObj; -} // needs to be called before value stringifier to allow for circular anchor refs - - -function stringifyProps(node, tagObj, { - anchors, - doc -}) { - const props = []; - const anchor = doc.anchors.getName(node); - - if (anchor) { - anchors[anchor] = node; - props.push(`&${anchor}`); - } - - if (node.tag) { - props.push(stringifyTag(doc, node.tag)); - } else if (!tagObj.default) { - props.push(stringifyTag(doc, tagObj.tag)); - } - - return props.join(' '); -} - -function stringify$2(item, ctx, onComment, onChompKeep) { - const { - anchors, - schema - } = ctx.doc; - let tagObj; - - if (!(item instanceof resolveSeq.Node)) { - const createCtx = { - aliasNodes: [], - onTagObj: o => tagObj = o, - prevObjects: new Map() - }; - item = schema.createNode(item, true, null, createCtx); - - for (const alias of createCtx.aliasNodes) { - alias.source = alias.source.node; - let name = anchors.getName(alias.source); - - if (!name) { - name = anchors.newName(); - anchors.map[name] = alias.source; - } - } - } - - if (item instanceof resolveSeq.Pair) return item.toString(ctx, onComment, onChompKeep); - if (!tagObj) tagObj = getTagObject(schema.tags, item); - const props = stringifyProps(item, tagObj, ctx); - if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1; - const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq.Scalar ? resolveSeq.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep); - if (!props) return str; - return item instanceof resolveSeq.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`; -} - -class Anchors { - static validAnchorNode(node) { - return node instanceof resolveSeq.Scalar || node instanceof resolveSeq.YAMLSeq || node instanceof resolveSeq.YAMLMap; - } - - constructor(prefix) { - PlainValue$1._defineProperty(this, "map", Object.create(null)); - - this.prefix = prefix; - } - - createAlias(node, name) { - this.setAnchor(node, name); - return new resolveSeq.Alias(node); - } - - createMergePair(...sources) { - const merge = new resolveSeq.Merge(); - merge.value.items = sources.map(s => { - if (s instanceof resolveSeq.Alias) { - if (s.source instanceof resolveSeq.YAMLMap) return s; - } else if (s instanceof resolveSeq.YAMLMap) { - return this.createAlias(s); - } - - throw new Error('Merge sources must be Map nodes or their Aliases'); - }); - return merge; - } - - getName(node) { - const { - map - } = this; - return Object.keys(map).find(a => map[a] === node); - } - - getNames() { - return Object.keys(this.map); - } - - getNode(name) { - return this.map[name]; - } - - newName(prefix) { - if (!prefix) prefix = this.prefix; - const names = Object.keys(this.map); - - for (let i = 1; true; ++i) { - const name = `${prefix}${i}`; - if (!names.includes(name)) return name; - } - } // During parsing, map & aliases contain CST nodes - - - resolveNodes() { - const { - map, - _cstAliases - } = this; - Object.keys(map).forEach(a => { - map[a] = map[a].resolved; - }); - - _cstAliases.forEach(a => { - a.source = a.source.resolved; - }); - - delete this._cstAliases; - } - - setAnchor(node, name) { - if (node != null && !Anchors.validAnchorNode(node)) { - throw new Error('Anchors may only be set for Scalar, Seq and Map nodes'); - } - - if (name && /[\x00-\x19\s,[\]{}]/.test(name)) { - throw new Error('Anchor names must not contain whitespace or control characters'); - } - - const { - map - } = this; - const prev = node && Object.keys(map).find(a => map[a] === node); - - if (prev) { - if (!name) { - return prev; - } else if (prev !== name) { - delete map[prev]; - map[name] = node; - } - } else { - if (!name) { - if (!node) return null; - name = this.newName(); - } - - map[name] = node; - } - - return name; - } - -} - -const visit$1 = (node, tags) => { - if (node && typeof node === 'object') { - const { - tag - } = node; - - if (node instanceof resolveSeq.Collection) { - if (tag) tags[tag] = true; - node.items.forEach(n => visit$1(n, tags)); - } else if (node instanceof resolveSeq.Pair) { - visit$1(node.key, tags); - visit$1(node.value, tags); - } else if (node instanceof resolveSeq.Scalar) { - if (tag) tags[tag] = true; - } - } - - return tags; -}; - -const listTagNames = node => Object.keys(visit$1(node, {})); - -function parseContents(doc, contents) { - const comments = { - before: [], - after: [] - }; - let body = undefined; - let spaceBefore = false; - - for (const node of contents) { - if (node.valueRange) { - if (body !== undefined) { - const msg = 'Document contains trailing content not separated by a ... or --- line'; - doc.errors.push(new PlainValue$1.YAMLSyntaxError(node, msg)); - break; - } - - const res = resolveSeq.resolveNode(doc, node); - - if (spaceBefore) { - res.spaceBefore = true; - spaceBefore = false; - } - - body = res; - } else if (node.comment !== null) { - const cc = body === undefined ? comments.before : comments.after; - cc.push(node.comment); - } else if (node.type === PlainValue$1.Type.BLANK_LINE) { - spaceBefore = true; - - if (body === undefined && comments.before.length > 0 && !doc.commentBefore) { - // space-separated comments at start are parsed as document comments - doc.commentBefore = comments.before.join('\n'); - comments.before = []; - } - } - } - - doc.contents = body || null; - - if (!body) { - doc.comment = comments.before.concat(comments.after).join('\n') || null; - } else { - const cb = comments.before.join('\n'); - - if (cb) { - const cbNode = body instanceof resolveSeq.Collection && body.items[0] ? body.items[0] : body; - cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb; - } - - doc.comment = comments.after.join('\n') || null; - } -} - -function resolveTagDirective({ - tagPrefixes -}, directive) { - const [handle, prefix] = directive.parameters; - - if (!handle || !prefix) { - const msg = 'Insufficient parameters given for %TAG directive'; - throw new PlainValue$1.YAMLSemanticError(directive, msg); - } - - if (tagPrefixes.some(p => p.handle === handle)) { - const msg = 'The %TAG directive must only be given at most once per handle in the same document.'; - throw new PlainValue$1.YAMLSemanticError(directive, msg); - } - - return { - handle, - prefix - }; -} - -function resolveYamlDirective(doc, directive) { - let [version] = directive.parameters; - if (directive.name === 'YAML:1.0') version = '1.0'; - - if (!version) { - const msg = 'Insufficient parameters given for %YAML directive'; - throw new PlainValue$1.YAMLSemanticError(directive, msg); - } - - if (!documentOptions[version]) { - const v0 = doc.version || doc.options.version; - const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`; - doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg)); - } - - return version; -} - -function parseDirectives(doc, directives, prevDoc) { - const directiveComments = []; - let hasDirectives = false; - - for (const directive of directives) { - const { - comment, - name - } = directive; - - switch (name) { - case 'TAG': - try { - doc.tagPrefixes.push(resolveTagDirective(doc, directive)); - } catch (error) { - doc.errors.push(error); - } - - hasDirectives = true; - break; - - case 'YAML': - case 'YAML:1.0': - if (doc.version) { - const msg = 'The %YAML directive must only be given at most once per document.'; - doc.errors.push(new PlainValue$1.YAMLSemanticError(directive, msg)); - } - - try { - doc.version = resolveYamlDirective(doc, directive); - } catch (error) { - doc.errors.push(error); - } - - hasDirectives = true; - break; - - default: - if (name) { - const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`; - doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg)); - } - - } - - if (comment) directiveComments.push(comment); - } - - if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) { - const copyTagPrefix = ({ - handle, - prefix - }) => ({ - handle, - prefix - }); - - doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix); - doc.version = prevDoc.version; - } - - doc.commentBefore = directiveComments.join('\n') || null; -} - -function assertCollection(contents) { - if (contents instanceof resolveSeq.Collection) return true; - throw new Error('Expected a YAML collection as document contents'); -} - -class Document$2 { - constructor(options) { - this.anchors = new Anchors(options.anchorPrefix); - this.commentBefore = null; - this.comment = null; - this.contents = null; - this.directivesEndMarker = null; - this.errors = []; - this.options = options; - this.schema = null; - this.tagPrefixes = []; - this.version = null; - this.warnings = []; - } - - add(value) { - assertCollection(this.contents); - return this.contents.add(value); - } - - addIn(path, value) { - assertCollection(this.contents); - this.contents.addIn(path, value); - } - - delete(key) { - assertCollection(this.contents); - return this.contents.delete(key); - } - - deleteIn(path) { - if (resolveSeq.isEmptyPath(path)) { - if (this.contents == null) return false; - this.contents = null; - return true; - } - - assertCollection(this.contents); - return this.contents.deleteIn(path); - } - - getDefaults() { - return Document$2.defaults[this.version] || Document$2.defaults[this.options.version] || {}; - } - - get(key, keepScalar) { - return this.contents instanceof resolveSeq.Collection ? this.contents.get(key, keepScalar) : undefined; - } - - getIn(path, keepScalar) { - if (resolveSeq.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq.Scalar ? this.contents.value : this.contents; - return this.contents instanceof resolveSeq.Collection ? this.contents.getIn(path, keepScalar) : undefined; - } - - has(key) { - return this.contents instanceof resolveSeq.Collection ? this.contents.has(key) : false; - } - - hasIn(path) { - if (resolveSeq.isEmptyPath(path)) return this.contents !== undefined; - return this.contents instanceof resolveSeq.Collection ? this.contents.hasIn(path) : false; - } - - set(key, value) { - assertCollection(this.contents); - this.contents.set(key, value); - } - - setIn(path, value) { - if (resolveSeq.isEmptyPath(path)) this.contents = value;else { - assertCollection(this.contents); - this.contents.setIn(path, value); - } - } - - setSchema(id, customTags) { - if (!id && !customTags && this.schema) return; - if (typeof id === 'number') id = id.toFixed(1); - - if (id === '1.0' || id === '1.1' || id === '1.2') { - if (this.version) this.version = id;else this.options.version = id; - delete this.options.schema; - } else if (id && typeof id === 'string') { - this.options.schema = id; - } - - if (Array.isArray(customTags)) this.options.customTags = customTags; - const opt = Object.assign({}, this.getDefaults(), this.options); - this.schema = new Schema$1.Schema(opt); - } - - parse(node, prevDoc) { - if (this.options.keepCstNodes) this.cstNode = node; - if (this.options.keepNodeTypes) this.type = 'DOCUMENT'; - const { - directives = [], - contents = [], - directivesEndMarker, - error, - valueRange - } = node; - - if (error) { - if (!error.source) error.source = this; - this.errors.push(error); - } - - parseDirectives(this, directives, prevDoc); - if (directivesEndMarker) this.directivesEndMarker = true; - this.range = valueRange ? [valueRange.start, valueRange.end] : null; - this.setSchema(); - this.anchors._cstAliases = []; - parseContents(this, contents); - this.anchors.resolveNodes(); - - if (this.options.prettyErrors) { - for (const error of this.errors) if (error instanceof PlainValue$1.YAMLError) error.makePretty(); - - for (const warn of this.warnings) if (warn instanceof PlainValue$1.YAMLError) warn.makePretty(); - } - - return this; - } - - listNonDefaultTags() { - return listTagNames(this.contents).filter(t => t.indexOf(Schema$1.Schema.defaultPrefix) !== 0); - } - - setTagPrefix(handle, prefix) { - if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !'); - - if (prefix) { - const prev = this.tagPrefixes.find(p => p.handle === handle); - if (prev) prev.prefix = prefix;else this.tagPrefixes.push({ - handle, - prefix - }); - } else { - this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle); - } - } - - toJSON(arg, onAnchor) { - const { - keepBlobsInJSON, - mapAsMap, - maxAliasCount - } = this.options; - const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq.Scalar)); - const ctx = { - doc: this, - indentStep: ' ', - keep, - mapAsMap: keep && !!mapAsMap, - maxAliasCount, - stringify: stringify$2 // Requiring directly in Pair would create circular dependencies - - }; - const anchorNames = Object.keys(this.anchors.map); - if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], { - alias: [], - aliasCount: 0, - count: 1 - }])); - const res = resolveSeq.toJSON(this.contents, arg, ctx); - if (typeof onAnchor === 'function' && ctx.anchors) for (const { - count, - res - } of ctx.anchors.values()) onAnchor(res, count); - return res; - } - - toString() { - if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified'); - const indentSize = this.options.indent; - - if (!Number.isInteger(indentSize) || indentSize <= 0) { - const s = JSON.stringify(indentSize); - throw new Error(`"indent" option must be a positive integer, not ${s}`); - } - - this.setSchema(); - const lines = []; - let hasDirectives = false; - - if (this.version) { - let vd = '%YAML 1.2'; - - if (this.schema.name === 'yaml-1.1') { - if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1'; - } - - lines.push(vd); - hasDirectives = true; - } - - const tagNames = this.listNonDefaultTags(); - this.tagPrefixes.forEach(({ - handle, - prefix - }) => { - if (tagNames.some(t => t.indexOf(prefix) === 0)) { - lines.push(`%TAG ${handle} ${prefix}`); - hasDirectives = true; - } - }); - if (hasDirectives || this.directivesEndMarker) lines.push('---'); - - if (this.commentBefore) { - if (hasDirectives || !this.directivesEndMarker) lines.unshift(''); - lines.unshift(this.commentBefore.replace(/^/gm, '#')); - } - - const ctx = { - anchors: Object.create(null), - doc: this, - indent: '', - indentStep: ' '.repeat(indentSize), - stringify: stringify$2 // Requiring directly in nodes would create circular dependencies - - }; - let chompKeep = false; - let contentComment = null; - - if (this.contents) { - if (this.contents instanceof resolveSeq.Node) { - if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push(''); - if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment - - ctx.forceBlockIndent = !!this.comment; - contentComment = this.contents.comment; - } - - const onChompKeep = contentComment ? null : () => chompKeep = true; - const body = stringify$2(this.contents, ctx, () => contentComment = null, onChompKeep); - lines.push(resolveSeq.addComment(body, '', contentComment)); - } else if (this.contents !== undefined) { - lines.push(stringify$2(this.contents, ctx)); - } - - if (this.comment) { - if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push(''); - lines.push(this.comment.replace(/^/gm, '#')); - } - - return lines.join('\n') + '\n'; - } - -} - -PlainValue$1._defineProperty(Document$2, "defaults", documentOptions); - -Document9b4560a1.Document = Document$2; -Document9b4560a1.defaultOptions = defaultOptions$1; -Document9b4560a1.scalarOptions = scalarOptions; - -var parseCst = parseCst$1; -var Document$1 = Document9b4560a1; -var Schema = Schema88e323a7; -var PlainValue = PlainValueEc8e588e; -var warnings = warnings1000a372; - - -function createNode(value, wrapScalars = true, tag) { - if (tag === undefined && typeof wrapScalars === 'string') { - tag = wrapScalars; - wrapScalars = true; - } - - const options = Object.assign({}, Document$1.Document.defaults[Document$1.defaultOptions.version], Document$1.defaultOptions); - const schema = new Schema.Schema(options); - return schema.createNode(value, wrapScalars, tag); -} - -class Document extends Document$1.Document { - constructor(options) { - super(Object.assign({}, Document$1.defaultOptions, options)); - } - -} - -function parseAllDocuments(src, options) { - const stream = []; - let prev; - - for (const cstDoc of parseCst.parse(src)) { - const doc = new Document(options); - doc.parse(cstDoc, prev); - stream.push(doc); - prev = doc; - } - - return stream; -} - -function parseDocument(src, options) { - const cst = parseCst.parse(src); - const doc = new Document(options).parse(cst[0]); - - if (cst.length > 1) { - const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()'; - doc.errors.unshift(new PlainValue.YAMLSemanticError(cst[1], errMsg)); - } - - return doc; -} - -function parse$g(src, options) { - const doc = parseDocument(src, options); - doc.warnings.forEach(warning => warnings.warn(warning)); - if (doc.errors.length > 0) throw doc.errors[0]; - return doc.toJSON(); -} - -function stringify$1(value, options) { - const doc = new Document(options); - doc.contents = value; - return String(doc); -} - -const YAML = { - createNode, - defaultOptions: Document$1.defaultOptions, - Document, - parse: parse$g, - parseAllDocuments, - parseCST: parseCst.parse, - parseDocument, - scalarOptions: Document$1.scalarOptions, - stringify: stringify$1 -}; - -dist$1.YAML = YAML; - -var yaml$1 = dist$1.YAML; - -var importCwd = {exports: {}}; - -var importFrom$1 = {exports: {}}; - -var resolveFrom$2 = {exports: {}}; - -const path$i = path__default; -const Module = require$$0__default$3; -const fs$i = fs__default; - -const resolveFrom$1 = (fromDirectory, moduleId, silent) => { - if (typeof fromDirectory !== 'string') { - throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``); - } - - if (typeof moduleId !== 'string') { - throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``); - } - - try { - fromDirectory = fs$i.realpathSync(fromDirectory); - } catch (error) { - if (error.code === 'ENOENT') { - fromDirectory = path$i.resolve(fromDirectory); - } else if (silent) { - return; - } else { - throw error; - } - } - - const fromFile = path$i.join(fromDirectory, 'noop.js'); - - const resolveFileName = () => Module._resolveFilename(moduleId, { - id: fromFile, - filename: fromFile, - paths: Module._nodeModulePaths(fromDirectory) - }); - - if (silent) { - try { - return resolveFileName(); - } catch (error) { - return; - } - } - - return resolveFileName(); -}; - -resolveFrom$2.exports = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId); -resolveFrom$2.exports.silent = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId, true); - -const resolveFrom = resolveFrom$2.exports; - -importFrom$1.exports = (fromDirectory, moduleId) => eval('require')(resolveFrom(fromDirectory, moduleId)); - -importFrom$1.exports.silent = (fromDirectory, moduleId) => { - try { - return eval('require')(resolveFrom(fromDirectory, moduleId)); - } catch (_) {} -}; - -const importFrom = importFrom$1.exports; - -importCwd.exports = moduleId => importFrom(process.cwd(), moduleId); -importCwd.exports.silent = moduleId => importFrom.silent(process.cwd(), moduleId); - -const req$1 = importCwd.exports; - -/** - * Load Options - * - * @private - * @method options - * - * @param {Object} config PostCSS Config - * - * @return {Object} options PostCSS Options - */ -const options = (config, file) => { - if (config.parser && typeof config.parser === 'string') { - try { - config.parser = req$1(config.parser); - } catch (err) { - throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`) - } - } - - if (config.syntax && typeof config.syntax === 'string') { - try { - config.syntax = req$1(config.syntax); - } catch (err) { - throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`) - } - } - - if (config.stringifier && typeof config.stringifier === 'string') { - try { - config.stringifier = req$1(config.stringifier); - } catch (err) { - throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`) - } - } - - if (config.plugins) { - delete config.plugins; - } - - return config -}; - -var options_1 = options; - -const req = importCwd.exports; - -/** - * Plugin Loader - * - * @private - * @method load - * - * @param {String} plugin PostCSS Plugin Name - * @param {Object} options PostCSS Plugin Options - * - * @return {Function} PostCSS Plugin - */ -const load$1 = (plugin, options, file) => { - try { - if ( - options === null || - options === undefined || - Object.keys(options).length === 0 - ) { - return req(plugin) - } else { - return req(plugin)(options) - } - } catch (err) { - throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`) - } -}; - -/** - * Load Plugins - * - * @private - * @method plugins - * - * @param {Object} config PostCSS Config Plugins - * - * @return {Array} plugins PostCSS Plugins - */ -const plugins = (config, file) => { - let plugins = []; - - if (Array.isArray(config.plugins)) { - plugins = config.plugins.filter(Boolean); - } else { - plugins = Object.keys(config.plugins) - .filter((plugin) => { - return config.plugins[plugin] !== false ? plugin : '' - }) - .map((plugin) => { - return load$1(plugin, config.plugins[plugin], file) - }); - } - - if (plugins.length && plugins.length > 0) { - plugins.forEach((plugin, i) => { - if (plugin.default) { - plugin = plugin.default; - } - - if (plugin.postcss === true) { - plugin = plugin(); - } else if (plugin.postcss) { - plugin = plugin.postcss; - } - - if ( - // eslint-disable-next-line - !( - (typeof plugin === 'object' && Array.isArray(plugin.plugins)) || - (typeof plugin === 'object' && plugin.postcssPlugin) || - (typeof plugin === 'function') - ) - ) { - throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`) - } - }); - } - - return plugins -}; - -var plugins_1 = plugins; - -const resolve$2 = path__default.resolve; - -const config$1 = dist$2; -const yaml = yaml$1; - -const loadOptions = options_1; -const loadPlugins = plugins_1; - -/* istanbul ignore next */ -const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj }; - -/** - * Process the result from cosmiconfig - * - * @param {Object} ctx Config Context - * @param {Object} result Cosmiconfig result - * - * @return {Object} PostCSS Config - */ -const processResult = (ctx, result) => { - const file = result.filepath || ''; - let config = interopRequireDefault(result.config).default || {}; - - if (typeof config === 'function') { - config = config(ctx); - } else { - config = Object.assign({}, config, ctx); - } - - if (!config.plugins) { - config.plugins = []; - } - - return { - plugins: loadPlugins(config, file), - options: loadOptions(config, file), - file: file - } -}; - -/** - * Builds the Config Context - * - * @param {Object} ctx Config Context - * - * @return {Object} Config Context - */ -const createContext = (ctx) => { - /** - * @type {Object} - * - * @prop {String} cwd=process.cwd() Config search start location - * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined` - */ - ctx = Object.assign({ - cwd: process.cwd(), - env: process.env.NODE_ENV - }, ctx); - - if (!ctx.env) { - process.env.NODE_ENV = 'development'; - } - - return ctx -}; - -const addTypeScriptLoader = (options = {}, loader) => { - const moduleName = 'postcss'; - - return { - ...options, - searchPlaces: [ - ...(options.searchPlaces || []), - 'package.json', - `.${moduleName}rc`, - `.${moduleName}rc.json`, - `.${moduleName}rc.yaml`, - `.${moduleName}rc.yml`, - `.${moduleName}rc.ts`, - `.${moduleName}rc.js`, - `.${moduleName}rc.cjs`, - `${moduleName}.config.ts`, - `${moduleName}.config.js`, - `${moduleName}.config.cjs` - ], - loaders: { - ...options.loaders, - '.yaml': (filepath, content) => yaml.parse(content), - '.yml': (filepath, content) => yaml.parse(content), - '.ts': loader - } - } -}; - -const withTypeScriptLoader = (rcFunc) => { - return (ctx, path, options) => { - return rcFunc(ctx, path, addTypeScriptLoader(options, (configFile) => { - let registerer = { enabled () {} }; - - try { - // Register TypeScript compiler instance - registerer = require('ts-node').register(); - - return commonjsRequire(configFile) - } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - throw new Error( - `'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${err.message}` - ) - } - - throw err - } finally { - registerer.enabled(false); - } - })) - } -}; - -/** - * Load Config - * - * @method rc - * - * @param {Object} ctx Config Context - * @param {String} path Config Path - * @param {Object} options Config Options - * - * @return {Promise} config PostCSS Config - */ -const rc = withTypeScriptLoader((ctx, path, options) => { - /** - * @type {Object} The full Config Context - */ - ctx = createContext(ctx); - - /** - * @type {String} `process.cwd()` - */ - path = path ? resolve$2(path) : process.cwd(); - - return config$1.lilconfig('postcss', options) - .search(path) - .then((result) => { - if (!result) { - throw new Error(`No PostCSS Config found in: ${path}`) - } - - return processResult(ctx, result) - }) -}); - -rc.sync = withTypeScriptLoader((ctx, path, options) => { - /** - * @type {Object} The full Config Context - */ - ctx = createContext(ctx); - - /** - * @type {String} `process.cwd()` - */ - path = path ? resolve$2(path) : process.cwd(); - - const result = config$1.lilconfigSync('postcss', options).search(path); - - if (!result) { - throw new Error(`No PostCSS Config found in: ${path}`) - } - - return processResult(ctx, result) -}); - -/** - * Autoload Config for PostCSS - * - * @author Michael Ciniawsky @michael-ciniawsky - * @license MIT - * - * @module postcss-load-config - * @version 2.1.0 - * - * @requires comsiconfig - * @requires ./options - * @requires ./plugins - */ -var src$1 = rc; - -// Helper since Typescript can't detect readonly arrays with Array.isArray -function isArray$3(arg) { - return Array.isArray(arg); -} -function ensureArray$1(thing) { - if (isArray$3(thing)) - return thing; - if (thing == null) - return []; - return [thing]; -} - -const normalizePath$3 = function normalizePath(filename) { - return filename.split(path$t.win32.sep).join(path$t.posix.sep); -}; - -function getMatcherString$1(id, resolutionBase) { - if (resolutionBase === false || path$t.isAbsolute(id) || id.startsWith('*')) { - return id; - } - // resolve('') is valid and will default to process.cwd() - const basePath = normalizePath$3(path$t.resolve(resolutionBase || '')) - // escape all possible (posix + win) path characters that might interfere with regex - .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); - // Note that we use posix.join because: - // 1. the basePath has been normalized to use / - // 2. the incoming glob (id) matcher, also uses / - // otherwise Node will force backslash (\) on windows - return path$t.posix.join(basePath, id); -} -const createFilter$1 = function createFilter(include, exclude, options) { - const resolutionBase = options && options.resolve; - const getMatcher = (id) => id instanceof RegExp - ? id - : { - test: (what) => { - // this refactor is a tad overly verbose but makes for easy debugging - const pattern = getMatcherString$1(id, resolutionBase); - const fn = picomatch$3(pattern, { dot: true }); - const result = fn(what); - return result; - } - }; - const includeMatchers = ensureArray$1(include).map(getMatcher); - const excludeMatchers = ensureArray$1(exclude).map(getMatcher); - return function result(id) { - if (typeof id !== 'string') - return false; - if (/\0/.test(id)) - return false; - const pathId = normalizePath$3(id); - for (let i = 0; i < excludeMatchers.length; ++i) { - const matcher = excludeMatchers[i]; - if (matcher.test(pathId)) - return false; - } - for (let i = 0; i < includeMatchers.length; ++i) { - const matcher = includeMatchers[i]; - if (matcher.test(pathId)) - return true; - } - return !includeMatchers.length; - }; -}; - -const reservedWords$2 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; -const builtins$1 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; -const forbiddenIdentifiers$1 = new Set(`${reservedWords$2} ${builtins$1}`.split(' ')); -forbiddenIdentifiers$1.add(''); -const makeLegalIdentifier$1 = function makeLegalIdentifier(str) { - let identifier = str - .replace(/-(\w)/g, (_, letter) => letter.toUpperCase()) - .replace(/[^$_a-zA-Z0-9]/g, '_'); - if (/\d/.test(identifier[0]) || forbiddenIdentifiers$1.has(identifier)) { - identifier = `_${identifier}`; - } - return identifier || '_'; -}; - -function stringify(obj) { - return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`); -} -function serializeArray(arr, indent, baseIndent) { - let output = '['; - const separator = indent ? `\n${baseIndent}${indent}` : ''; - for (let i = 0; i < arr.length; i++) { - const key = arr[i]; - output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`; - } - return `${output}${indent ? `\n${baseIndent}` : ''}]`; -} -function serializeObject(obj, indent, baseIndent) { - let output = '{'; - const separator = indent ? `\n${baseIndent}${indent}` : ''; - const entries = Object.entries(obj); - for (let i = 0; i < entries.length; i++) { - const [key, value] = entries[i]; - const stringKey = makeLegalIdentifier$1(key) === key ? key : stringify(key); - output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`; - } - return `${output}${indent ? `\n${baseIndent}` : ''}}`; -} -function serialize(obj, indent, baseIndent) { - if (obj === Infinity) - return 'Infinity'; - if (obj === -Infinity) - return '-Infinity'; - if (obj === 0 && 1 / obj === -Infinity) - return '-0'; - if (obj instanceof Date) - return `new Date(${obj.getTime()})`; - if (obj instanceof RegExp) - return obj.toString(); - if (obj !== obj) - return 'NaN'; // eslint-disable-line no-self-compare - if (Array.isArray(obj)) - return serializeArray(obj, indent, baseIndent); - if (obj === null) - return 'null'; - if (typeof obj === 'object') - return serializeObject(obj, indent, baseIndent); - return stringify(obj); -} -const dataToEsm = function dataToEsm(data, options = {}) { - const t = options.compact ? '' : 'indent' in options ? options.indent : '\t'; - const _ = options.compact ? '' : ' '; - const n = options.compact ? '' : '\n'; - const declarationType = options.preferConst ? 'const' : 'var'; - if (options.namedExports === false || - typeof data !== 'object' || - Array.isArray(data) || - data instanceof Date || - data instanceof RegExp || - data === null) { - const code = serialize(data, options.compact ? null : t, ''); - const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape - return `export default${magic}${code};`; - } - let namedExportCode = ''; - const defaultExportRows = []; - for (const [key, value] of Object.entries(data)) { - if (key === makeLegalIdentifier$1(key)) { - if (options.objectShorthand) - defaultExportRows.push(key); - else - defaultExportRows.push(`${key}:${_}${key}`); - namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`; - } - else { - defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`); - } - } - return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`; -}; - -const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`; -const cssLangRE = new RegExp(cssLangs); -const cssModuleRE = new RegExp(`\\.module${cssLangs}`); -const directRequestRE = /(\?|&)direct\b/; -const commonjsProxyRE = /\?commonjs-proxy/; -const inlineRE = /(\?|&)inline\b/; -const usedRE = /(\?|&)used\b/; -const isCSSRequest = (request) => cssLangRE.test(request); -const isDirectCSSRequest = (request) => cssLangRE.test(request) && directRequestRE.test(request); -const isDirectRequest = (request) => directRequestRE.test(request); -const cssModulesCache = new WeakMap(); -const chunkToEmittedCssFileMap = new WeakMap(); -const removedPureCssFilesCache = new WeakMap(); -const postcssConfigCache = new WeakMap(); -/** - * Plugin applied before user plugins - */ -function cssPlugin(config) { - let server; - let moduleCache; - const resolveUrl = config.createResolver({ - preferRelative: true, - tryIndex: false, - extensions: [] - }); - const atImportResolvers = createCSSResolvers(config); - return { - name: 'vite:css', - configureServer(_server) { - server = _server; - }, - buildStart() { - // Ensure a new cache for every build (i.e. rebuilding in watch mode) - moduleCache = new Map(); - cssModulesCache.set(config, moduleCache); - removedPureCssFilesCache.set(config, new Map()); - }, - async transform(raw, id) { - if (!isCSSRequest(id) || commonjsProxyRE.test(id) || isURLRequest(id)) { - return; - } - const urlReplacer = async (url, importer) => { - if (checkPublicFile(url, config)) { - return config.base + url.slice(1); - } - const resolved = await resolveUrl(url, importer); - if (resolved) { - return fileToUrl(resolved, config, this); - } - return url; - }; - const { code: css, modules, deps } = await compileCSS(id, raw, config, urlReplacer, atImportResolvers, server); - if (modules) { - moduleCache.set(id, modules); - } - // track deps for build watch mode - if (config.command === 'build' && config.build.watch && deps) { - for (const file of deps) { - this.addWatchFile(file); - } - } - // dev - if (server) { - // server only logic for handling CSS @import dependency hmr - const { moduleGraph } = server; - const thisModule = moduleGraph.getModuleById(id); - if (thisModule) { - // CSS modules cannot self-accept since it exports values - const isSelfAccepting = !modules; - if (deps) { - // record deps in the module graph so edits to @import css can trigger - // main import to hot update - const depModules = new Set(); - for (const file of deps) { - depModules.add(isCSSRequest(file) - ? moduleGraph.createFileOnlyEntry(file) - : await moduleGraph.ensureEntryFromUrl((await fileToUrl(file, config, this)).replace(config.base, '/'))); - } - moduleGraph.updateModuleInfo(thisModule, depModules, - // The root CSS proxy module is self-accepting and should not - // have an explicit accept list - new Set(), isSelfAccepting); - for (const file of deps) { - this.addWatchFile(file); - } - } - else { - thisModule.isSelfAccepting = isSelfAccepting; - } - } - } - return { - code: css, - // TODO CSS source map - map: { mappings: '' } - }; - } - }; -} -/** - * Plugin applied after user plugins - */ -function cssPostPlugin(config) { - // styles initialization in buildStart causes a styling loss in watch - const styles = new Map(); - let pureCssChunks; - // when there are multiple rollup outputs and extracting CSS, only emit once, - // since output formats have no effect on the generated CSS. - let outputToExtractedCSSMap; - let hasEmitted = false; - return { - name: 'vite:css-post', - buildStart() { - // Ensure new caches for every build (i.e. rebuilding in watch mode) - pureCssChunks = new Set(); - outputToExtractedCSSMap = new Map(); - hasEmitted = false; - }, - async transform(css, id, ssr) { - if (!isCSSRequest(id) || commonjsProxyRE.test(id) || isURLRequest(id)) { - return; - } - const inlined = inlineRE.test(id); - const modules = cssModulesCache.get(config).get(id); - const modulesCode = modules && dataToEsm(modules, { namedExports: true, preferConst: true }); - if (config.command === 'serve') { - if (isDirectCSSRequest(id)) { - return css; - } - else { - // server only - if (ssr) { - return modulesCode || `export default ${JSON.stringify(css)}`; - } - if (inlined) { - return `export default ${JSON.stringify(css)}`; - } - return [ - `import { updateStyle, removeStyle } from ${JSON.stringify(path__default.posix.join(config.base, CLIENT_PUBLIC_PATH))}`, - `const id = ${JSON.stringify(id)}`, - `const css = ${JSON.stringify(css)}`, - `updateStyle(id, css)`, - // css modules exports change on edit so it can't self accept - `${modulesCode || `import.meta.hot.accept()\nexport default css`}`, - `import.meta.hot.prune(() => removeStyle(id))` - ].join('\n'); - } - } - // build CSS handling ---------------------------------------------------- - // record css - if (!inlined) { - styles.set(id, css); - } - else { - css = await minifyCSS(css, config); - } - return { - code: modulesCode || - (usedRE.test(id) - ? `export default ${JSON.stringify(css)}` - : `export default ''`), - map: { mappings: '' }, - // avoid the css module from being tree-shaken so that we can retrieve - // it in renderChunk() - moduleSideEffects: inlined ? false : 'no-treeshake' - }; - }, - async renderChunk(code, chunk, opts) { - let chunkCSS = ''; - let isPureCssChunk = true; - const ids = Object.keys(chunk.modules); - for (const id of ids) { - if (!isCSSRequest(id) || - cssModuleRE.test(id) || - commonjsProxyRE.test(id)) { - isPureCssChunk = false; - } - if (styles.has(id)) { - chunkCSS += styles.get(id); - } - } - if (!chunkCSS) { - return null; - } - // resolve asset URL placeholders to their built file URLs and perform - // minification if necessary - const processChunkCSS = async (css, { inlined, minify }) => { - // replace asset url references with resolved url. - const isRelativeBase = config.base === '' || config.base.startsWith('.'); - css = css.replace(assetUrlRE, (_, fileHash, postfix = '') => { - const filename = getAssetFilename(fileHash, config) + postfix; - registerAssetToChunk(chunk, filename); - if (!isRelativeBase || inlined) { - // absolute base or relative base but inlined (injected as style tag into - // index.html) use the base as-is - return config.base + filename; - } - else { - // relative base + extracted CSS - asset file will be in the same dir - return `./${path__default.posix.basename(filename)}`; - } - }); - // only external @imports should exist at this point - and they need to - // be hoisted to the top of the CSS chunk per spec (#1845) - if (css.includes('@import')) { - css = await hoistAtImports(css); - } - if (minify && config.build.minify) { - css = await minifyCSS(css, config); - } - return css; - }; - if (config.build.cssCodeSplit) { - if (isPureCssChunk) { - // this is a shared CSS-only chunk that is empty. - pureCssChunks.add(chunk.fileName); - } - if (opts.format === 'es' || opts.format === 'cjs') { - chunkCSS = await processChunkCSS(chunkCSS, { - inlined: false, - minify: true - }); - // emit corresponding css file - const fileHandle = this.emitFile({ - name: chunk.name + '.css', - type: 'asset', - source: chunkCSS - }); - chunkToEmittedCssFileMap.set(chunk, new Set([this.getFileName(fileHandle)])); - } - else if (!config.build.ssr) { - // legacy build, inline css - chunkCSS = await processChunkCSS(chunkCSS, { - inlined: true, - minify: true - }); - const style = `__vite_style__`; - const injectCode = `var ${style} = document.createElement('style');` + - `${style}.innerHTML = ${JSON.stringify(chunkCSS)};` + - `document.head.appendChild(${style});`; - if (config.build.sourcemap) { - const s = new MagicString(code); - s.prepend(injectCode); - return { - code: s.toString(), - map: s.generateMap({ hires: true }) - }; - } - else { - return { code: injectCode + code }; - } - } - } - else { - // non-split extracted CSS will be minified together - chunkCSS = await processChunkCSS(chunkCSS, { - inlined: false, - minify: false - }); - outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS); - } - return null; - }, - async generateBundle(opts, bundle) { - // remove empty css chunks and their imports - if (pureCssChunks.size) { - const emptyChunkFiles = [...pureCssChunks] - .map((file) => path__default.basename(file)) - .join('|') - .replace(/\./g, '\\.'); - const emptyChunkRE = new RegExp(opts.format === 'es' - ? `\\bimport\\s*"[^"]*(?:${emptyChunkFiles})";\n?` - : `\\brequire\\(\\s*"[^"]*(?:${emptyChunkFiles})"\\);\n?`, 'g'); - for (const file in bundle) { - const chunk = bundle[file]; - if (chunk.type === 'chunk') { - // remove pure css chunk from other chunk's imports, - // and also register the emitted CSS files under the importer - // chunks instead. - chunk.imports = chunk.imports.filter((file) => { - if (pureCssChunks.has(file)) { - const css = chunkToEmittedCssFileMap.get(bundle[file]); - if (css) { - let existing = chunkToEmittedCssFileMap.get(chunk); - if (!existing) { - existing = new Set(); - } - css.forEach((file) => existing.add(file)); - chunkToEmittedCssFileMap.set(chunk, existing); - } - return false; - } - return true; - }); - chunk.code = chunk.code.replace(emptyChunkRE, - // remove css import while preserving source map location - (m) => `/* empty css ${''.padEnd(m.length - 15)}*/`); - } - } - const removedPureCssFiles = removedPureCssFilesCache.get(config); - pureCssChunks.forEach((fileName) => { - removedPureCssFiles.set(fileName, bundle[fileName]); - delete bundle[fileName]; - }); - } - let extractedCss = outputToExtractedCSSMap.get(opts); - if (extractedCss && !hasEmitted) { - hasEmitted = true; - // minify css - if (config.build.minify) { - extractedCss = await minifyCSS(extractedCss, config); - } - this.emitFile({ - name: 'style.css', - type: 'asset', - source: extractedCss - }); - } - } - }; -} -function createCSSResolvers(config) { - let cssResolve; - let sassResolve; - let lessResolve; - return { - get css() { - return (cssResolve || - (cssResolve = config.createResolver({ - extensions: ['.css'], - mainFields: ['style'], - tryIndex: false, - preferRelative: true - }))); - }, - get sass() { - return (sassResolve || - (sassResolve = config.createResolver({ - extensions: ['.scss', '.sass', '.css'], - mainFields: ['sass', 'style'], - tryIndex: true, - tryPrefix: '_', - preferRelative: true - }))); - }, - get less() { - return (lessResolve || - (lessResolve = config.createResolver({ - extensions: ['.less', '.css'], - mainFields: ['less', 'style'], - tryIndex: false, - preferRelative: true - }))); - } - }; -} -function getCssResolversKeys(resolvers) { - return Object.keys(resolvers); -} -async function compileCSS(id, code, config, urlReplacer, atImportResolvers, server) { - var _a; - const { modules: modulesOptions, preprocessorOptions } = config.css || {}; - const isModule = modulesOptions !== false && cssModuleRE.test(id); - // although at serve time it can work without processing, we do need to - // crawl them in order to register watch dependencies. - const needInlineImport = code.includes('@import'); - const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code); - const postcssConfig = await resolvePostcssConfig(config); - const lang = (_a = id.match(cssLangRE)) === null || _a === void 0 ? void 0 : _a[1]; - // 1. plain css that needs no processing - if (lang === 'css' && - !postcssConfig && - !isModule && - !needInlineImport && - !hasUrl) { - return { code }; - } - let map; - let modules; - const deps = new Set(); - // 2. pre-processors: sass etc. - if (isPreProcessor(lang)) { - const preProcessor = preProcessors[lang]; - let opts = (preprocessorOptions && preprocessorOptions[lang]) || {}; - // support @import from node dependencies by default - switch (lang) { - case "scss" /* scss */: - case "sass" /* sass */: - opts = { - includePaths: ['node_modules'], - alias: config.resolve.alias, - ...opts - }; - break; - case "less" /* less */: - case "styl" /* styl */: - case "stylus" /* stylus */: - opts = { - paths: ['node_modules'], - alias: config.resolve.alias, - ...opts - }; - } - // important: set this for relative import resolving - opts.filename = cleanUrl(id); - const preprocessResult = await preProcessor(code, config.root, opts, atImportResolvers); - if (preprocessResult.errors.length) { - throw preprocessResult.errors[0]; - } - code = preprocessResult.code; - map = preprocessResult.map; - if (preprocessResult.deps) { - preprocessResult.deps.forEach((dep) => { - // sometimes sass registers the file itself as a dep - if (normalizePath$4(dep) !== normalizePath$4(opts.filename)) { - deps.add(dep); - } - }); - } - } - // 3. postcss - const postcssOptions = (postcssConfig && postcssConfig.options) || {}; - const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : []; - if (needInlineImport) { - postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-e39b05d6.js'); }).then(function (n) { return n.index; })).default({ - async resolve(id, basedir) { - const resolved = await atImportResolvers.css(id, path__default.join(basedir, '*')); - if (resolved) { - return path__default.resolve(resolved); - } - return id; - } - })); - } - postcssPlugins.push(UrlRewritePostcssPlugin({ - replacer: urlReplacer - })); - if (isModule) { - postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-dab866a6.js'); }).then(function (n) { return n.index; })).default({ - ...modulesOptions, - getJSON(cssFileName, _modules, outputFileName) { - modules = _modules; - if (modulesOptions && typeof modulesOptions.getJSON === 'function') { - modulesOptions.getJSON(cssFileName, _modules, outputFileName); - } - }, - async resolve(id) { - for (const key of getCssResolversKeys(atImportResolvers)) { - const resolved = await atImportResolvers[key](id); - if (resolved) { - return path__default.resolve(resolved); - } - } - return id; - } - })); - } - if (!postcssPlugins.length) { - return { - code, - map - }; - } - // postcss is an unbundled dep and should be lazy imported - const postcssResult = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); })) - .default(postcssPlugins) - .process(code, { - ...postcssOptions, - to: id, - from: id, - map: { - inline: false, - annotation: false, - prev: map - } - }); - // record CSS dependencies from @imports - for (const message of postcssResult.messages) { - if (message.type === 'dependency') { - deps.add(message.file); - } - else if (message.type === 'dir-dependency') { - // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies - const { dir, glob: globPattern = '**' } = message; - const pattern = normalizePath$4(path__default.resolve(path__default.dirname(id), dir)) + `/` + globPattern; - const files = out.sync(pattern, { - ignore: ['**/node_modules/**'] - }); - for (let i = 0; i < files.length; i++) { - deps.add(files[i]); - } - if (server) { - // register glob importers so we can trigger updates on file add/remove - if (!(id in server._globImporters)) { - server._globImporters[id] = { - module: server.moduleGraph.getModuleById(id), - importGlobs: [] - }; - } - server._globImporters[id].importGlobs.push({ - base: config.root, - pattern - }); - } - } - else if (message.type === 'warning') { - let msg = `[vite:css] ${message.text}`; - if (message.line && message.column) { - msg += `\n${generateCodeFrame(code, { - line: message.line, - column: message.column - })}`; - } - config.logger.warn(source.yellow(msg)); - } - } - return { - ast: postcssResult, - code: postcssResult.css, - map: postcssResult.map, - modules, - deps - }; -} -async function resolvePostcssConfig(config) { - var _a; - let result = postcssConfigCache.get(config); - if (result !== undefined) { - return result; - } - // inline postcss config via vite config - const inlineOptions = (_a = config.css) === null || _a === void 0 ? void 0 : _a.postcss; - if (isObject$3(inlineOptions)) { - const options = { ...inlineOptions }; - delete options.plugins; - result = { - options, - plugins: inlineOptions.plugins || [] - }; - } - else { - try { - const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root; - // @ts-ignore - result = await src$1({}, searchPath); - } - catch (e) { - if (!/No PostCSS Config found/.test(e.message)) { - throw e; - } - result = null; - } - } - postcssConfigCache.set(config, result); - return result; -} -// https://drafts.csswg.org/css-syntax-3/#identifier-code-point -const cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/; -const cssImageSetRE = /image-set\(([^)]+)\)/; -const UrlRewritePostcssPlugin = (opts) => { - if (!opts) { - throw new Error('base or replace is required'); - } - return { - postcssPlugin: 'vite-url-rewrite', - Once(root) { - const promises = []; - root.walkDecls((declaration) => { - const isCssUrl = cssUrlRE.test(declaration.value); - const isCssImageSet = cssImageSetRE.test(declaration.value); - if (isCssUrl || isCssImageSet) { - const replacerForDeclaration = (rawUrl) => { - var _a; - const importer = (_a = declaration.source) === null || _a === void 0 ? void 0 : _a.input.file; - return opts.replacer(rawUrl, importer); - }; - const rewriterToUse = isCssUrl ? rewriteCssUrls : rewriteCssImageSet; - promises.push(rewriterToUse(declaration.value, replacerForDeclaration).then((url) => { - declaration.value = url; - })); - } - }); - if (promises.length) { - return Promise.all(promises); - } - } - }; -}; -UrlRewritePostcssPlugin.postcss = true; -function rewriteCssUrls(css, replacer) { - return asyncReplace(css, cssUrlRE, async (match) => { - const [matched, rawUrl] = match; - return await doUrlReplace(rawUrl, matched, replacer); - }); -} -function rewriteCssImageSet(css, replacer) { - return asyncReplace(css, cssImageSetRE, async (match) => { - const [matched, rawUrl] = match; - const url = await processSrcSet(rawUrl, ({ url }) => doUrlReplace(url, matched, replacer)); - return `image-set(${url})`; - }); -} -async function doUrlReplace(rawUrl, matched, replacer) { - let wrap = ''; - const first = rawUrl[0]; - if (first === `"` || first === `'`) { - wrap = first; - rawUrl = rawUrl.slice(1, -1); - } - if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl.startsWith('#')) { - return matched; - } - return `url(${wrap}${await replacer(rawUrl)}${wrap})`; -} -async function minifyCSS(css, config) { - const { code, warnings } = await esbuild.transform(css, { - loader: 'css', - minify: true, - target: config.build.cssTarget || undefined - }); - if (warnings.length) { - const msgs = await esbuild.formatMessages(warnings, { kind: 'warning' }); - config.logger.warn(source.yellow(`warnings when minifying css:\n${msgs.join('\n')}`)); - } - return code; -} -// #1845 -// CSS @import can only appear at top of the file. We need to hoist all @import -// to top when multiple files are concatenated. -async function hoistAtImports(css) { - const postcss = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); }); - return (await postcss.default([AtImportHoistPlugin]).process(css)).css; -} -const AtImportHoistPlugin = () => { - return { - postcssPlugin: 'vite-hoist-at-imports', - Once(root) { - const imports = []; - root.walkAtRules((rule) => { - if (rule.name === 'import') { - // record in reverse so that can simply prepend to preserve order - imports.unshift(rule); - } - }); - imports.forEach((i) => root.prepend(i)); - } - }; -}; -AtImportHoistPlugin.postcss = true; -const loadedPreprocessors = {}; -function loadPreprocessor(lang, root) { - var _a, _b; - if (lang in loadedPreprocessors) { - return loadedPreprocessors[lang]; - } - try { - // Search for the preprocessor in the root directory first, and fall back - // to the default require paths. - const fallbackPaths = ((_b = (_a = require.resolve).paths) === null || _b === void 0 ? void 0 : _b.call(_a, lang)) || []; - const resolved = require.resolve(lang, { paths: [root, ...fallbackPaths] }); - return (loadedPreprocessors[lang] = require(resolved)); - } - catch (e) { - throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it?`); - } -} -// .scss/.sass processor -const scss = async (source, root, options, resolvers) => { - const render = loadPreprocessor("sass" /* sass */, root).render; - const internalImporter = (url, importer, done) => { - resolvers.sass(url, importer).then((resolved) => { - if (resolved) { - rebaseUrls(resolved, options.filename, options.alias) - .then(done) - .catch(done); - } - else { - done(null); - } - }); - }; - const importer = [internalImporter]; - if (options.importer) { - Array.isArray(options.importer) - ? importer.push(...options.importer) - : importer.push(options.importer); - } - const finalOptions = { - ...options, - data: await getSource(source, options.filename, options.additionalData), - file: options.filename, - outFile: options.filename, - importer - }; - try { - const result = await new Promise((resolve, reject) => { - render(finalOptions, (err, res) => { - if (err) { - reject(err); - } - else { - resolve(res); - } - }); - }); - const deps = result.stats.includedFiles; - return { - code: result.css.toString(), - errors: [], - deps - }; - } - catch (e) { - // normalize SASS error - e.id = e.file; - e.frame = e.formatted; - return { code: '', errors: [e], deps: [] }; - } -}; -const sass = (source, root, options, aliasResolver) => scss(source, root, { - ...options, - indentedSyntax: true -}, aliasResolver); -/** - * relative url() inside \@imported sass and less files must be rebased to use - * root file as base. - */ -async function rebaseUrls(file, rootFile, alias) { - file = path__default.resolve(file); // ensure os-specific flashes - // in the same dir, no need to rebase - const fileDir = path__default.dirname(file); - const rootDir = path__default.dirname(rootFile); - if (fileDir === rootDir) { - return { file }; - } - // no url() - const content = fs__default.readFileSync(file, 'utf-8'); - if (!cssUrlRE.test(content)) { - return { file }; - } - const rebased = await rewriteCssUrls(content, (url) => { - if (url.startsWith('/')) - return url; - // match alias, no need to rewrite - for (const { find } of alias) { - const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url); - if (matches) { - return url; - } - } - const absolute = path__default.resolve(fileDir, url); - const relative = path__default.relative(rootDir, absolute); - return normalizePath$4(relative); - }); - return { - file, - contents: rebased - }; -} -// .less -const less = async (source, root, options, resolvers) => { - const nodeLess = loadPreprocessor("less" /* less */, root); - const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename, options.alias, resolvers); - source = await getSource(source, options.filename, options.additionalData); - let result; - try { - result = await nodeLess.render(source, { - ...options, - plugins: [viteResolverPlugin, ...(options.plugins || [])] - }); - } - catch (e) { - const error = e; - // normalize error info - const normalizedError = new Error(error.message || error.type); - normalizedError.loc = { - file: error.filename || options.filename, - line: error.line, - column: error.column - }; - return { code: '', errors: [normalizedError], deps: [] }; - } - return { - code: result.css.toString(), - deps: result.imports, - errors: [] - }; -}; -/** - * Less manager, lazy initialized - */ -let ViteLessManager; -function createViteLessPlugin(less, rootFile, alias, resolvers) { - if (!ViteLessManager) { - ViteLessManager = class ViteManager extends less.FileManager { - constructor(rootFile, resolvers, alias) { - super(); - this.rootFile = rootFile; - this.resolvers = resolvers; - this.alias = alias; - } - supports() { - return true; - } - supportsSync() { - return false; - } - async loadFile(filename, dir, opts, env) { - const resolved = await this.resolvers.less(filename, path__default.join(dir, '*')); - if (resolved) { - const result = await rebaseUrls(resolved, this.rootFile, this.alias); - let contents; - if (result && 'contents' in result) { - contents = result.contents; - } - else { - contents = fs__default.readFileSync(resolved, 'utf-8'); - } - return { - filename: path__default.resolve(resolved), - contents - }; - } - else { - return super.loadFile(filename, dir, opts, env); - } - } - }; - } - return { - install(_, pluginManager) { - pluginManager.addFileManager(new ViteLessManager(rootFile, resolvers, alias)); - }, - minVersion: [3, 0, 0] - }; -} -// .styl -const styl = async (source, root, options) => { - var _a; - const nodeStylus = loadPreprocessor("stylus" /* stylus */, root); - // Get source with preprocessor options.additionalData. Make sure a new line separator - // is added to avoid any render error, as added stylus content may not have semi-colon separators - source = await getSource(source, options.filename, options.additionalData, '\n'); - // Get preprocessor options.imports dependencies as stylus - // does not return them with its builtin `.deps()` method - const importsDeps = ((_a = options.imports) !== null && _a !== void 0 ? _a : []).map((dep) => path__default.resolve(dep)); - try { - const ref = nodeStylus(source, options); - // if (map) ref.set('sourcemap', { inline: false, comment: false }) - const result = ref.render(); - // Concat imports deps with computed deps - const deps = [...ref.deps(), ...importsDeps]; - return { code: result, errors: [], deps }; - } - catch (e) { - return { code: '', errors: [e], deps: [] }; - } -}; -function getSource(source, filename, additionalData, sep = '') { - if (!additionalData) - return source; - if (typeof additionalData === 'function') { - return additionalData(source, filename); - } - return additionalData + sep + source; -} -const preProcessors = Object.freeze({ - ["less" /* less */]: less, - ["sass" /* sass */]: sass, - ["scss" /* scss */]: scss, - ["styl" /* styl */]: styl, - ["stylus" /* stylus */]: styl -}); -function isPreProcessor(lang) { - return lang && lang in preProcessors; -} - -/* es-module-lexer 0.9.2 */ -const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$f(E,g="@"){if(!B)return init.then(()=>parse$f(E));const I=E.length+1,w=(B.__heap_base.value||B.__heap_base)+4*I-B.memory.buffer.byteLength;w>0&&B.memory.grow(Math.ceil(w/65536));const D=B.sa(I-1);if((A?C:Q)(E,new Uint16Array(B.memory.buffer,D,I)),!B.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,B.e()).split("\n").length}:${B.e()-E.lastIndexOf("\n",B.e()-1)}`),{idx:B.e()});const k=[],L=[];for(;B.ri();){const A=B.is(),Q=B.ie(),C=B.ai(),g=B.id(),I=B.ss(),w=B.se();let D;B.ip()&&(D=o(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),k.push({n:D,s:A,e:Q,ss:I,se:w,d:g,a:C});}for(;B.re();){const A=E.slice(B.es(),B.ee()),Q=A[0];L.push('"'===Q||"'"===Q?o(A):A);}function o(A){try{return (0, eval)(A)}catch(A){}}return [k,L,!!B.f()]}function Q(A,Q){const C=A.length;let B=0;for(;B>>8;}}function C(A,Q){const C=A.length;let B=0;for(;BA.charCodeAt(0)))).then(WebAssembly.instantiate).then(({exports:A})=>{B=A;});var E; - -async function transformImportGlob(source, pos, importer, importIndex, root, normalizeUrl, preload = true) { - const isEager = source.slice(pos, pos + 21) === 'import.meta.globEager'; - const isEagerDefault = isEager && source.slice(pos + 21, pos + 28) === 'Default'; - const err = (msg) => { - const e = new Error(`Invalid glob import syntax: ${msg}`); - e.pos = pos; - return e; - }; - importer = cleanUrl(importer); - const importerBasename = path__default.basename(importer); - let [pattern, endIndex] = lexGlobPattern(source, pos); - if (!pattern.startsWith('.') && !pattern.startsWith('/')) { - throw err(`pattern must start with "." or "/" (relative to project root)`); - } - let base; - let parentDepth = 0; - const isAbsolute = pattern.startsWith('/'); - if (isAbsolute) { - base = path__default.resolve(root); - pattern = pattern.slice(1); - } - else { - base = path__default.dirname(importer); - while (pattern.startsWith('../')) { - pattern = pattern.slice(3); - base = path__default.resolve(base, '../'); - parentDepth++; - } - if (pattern.startsWith('./')) { - pattern = pattern.slice(2); - } - } - const files = out.sync(pattern, { - cwd: base, - ignore: ['**/node_modules/**'] - }); - const imports = []; - let importsString = ``; - let entries = ``; - for (let i = 0; i < files.length; i++) { - // skip importer itself - if (files[i] === importerBasename) - continue; - const file = isAbsolute - ? `/${files[i]}` - : parentDepth - ? `${'../'.repeat(parentDepth)}${files[i]}` - : `./${files[i]}`; - let importee = file; - if (normalizeUrl) { - [importee] = await normalizeUrl(file, pos); - } - imports.push(importee); - const identifier = `__glob_${importIndex}_${i}`; - if (isEager) { - importsString += `import ${isEagerDefault ? `` : `* as `}${identifier} from ${JSON.stringify(importee)};`; - entries += ` ${JSON.stringify(file)}: ${identifier},`; - } - else { - let imp = `import(${JSON.stringify(importee)})`; - if (!normalizeUrl && preload) { - imp = - `(${isModernFlag}` + - `? ${preloadMethod}(()=>${imp},"${preloadMarker}")` + - `: ${imp})`; - } - entries += ` ${JSON.stringify(file)}: () => ${imp},`; - } - } - return { - imports, - importsString, - exp: `{${entries}}`, - endIndex, - isEager, - pattern, - base - }; -} -function lexGlobPattern(code, pos) { - let state = 0 /* inCall */; - let pattern = ''; - let i = code.indexOf(`(`, pos) + 1; - outer: for (; i < code.length; i++) { - const char = code.charAt(i); - switch (state) { - case 0 /* inCall */: - if (char === `'`) { - state = 1 /* inSingleQuoteString */; - } - else if (char === `"`) { - state = 2 /* inDoubleQuoteString */; - } - else if (char === '`') { - state = 3 /* inTemplateString */; - } - else if (/\s/.test(char)) { - continue; - } - else { - error$3(i); - } - break; - case 1 /* inSingleQuoteString */: - if (char === `'`) { - break outer; - } - else { - pattern += char; - } - break; - case 2 /* inDoubleQuoteString */: - if (char === `"`) { - break outer; - } - else { - pattern += char; - } - break; - case 3 /* inTemplateString */: - if (char === '`') { - break outer; - } - else { - pattern += char; - } - break; - default: - throw new Error('unknown import.meta.glob lexer state'); - } - } - return [pattern, code.indexOf(`)`, i) + 1]; -} -function error$3(pos) { - const err = new Error(`import.meta.glob() can only accept string literals.`); - err.pos = pos; - throw err; -} - -/** - * A flag for injected helpers. This flag will be set to `false` if the output - * target is not native es - so that injected helper logic can be conditionally - * dropped. - */ -const isModernFlag = `__VITE_IS_MODERN__`; -const preloadMethod = `__vitePreload`; -const preloadMarker = `__VITE_PRELOAD__`; -const preloadBaseMarker = `__VITE_PRELOAD_BASE__`; -const preloadHelperId = 'vite/preload-helper'; -const preloadMarkerRE = new RegExp(`"${preloadMarker}"`, 'g'); -/** - * Helper for preloading CSS and direct imports of async chunks in parallel to - * the async chunk itself. - */ -function detectScriptRel() { - // @ts-ignore - const relList = document.createElement('link').relList; - // @ts-ignore - return relList && relList.supports && relList.supports('modulepreload') - ? 'modulepreload' - : 'preload'; -} -function preload(baseModule, deps) { - // @ts-ignore - if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) { - return baseModule(); - } - return Promise.all(deps.map((dep) => { - // @ts-ignore - dep = `${base}${dep}`; - // @ts-ignore - if (dep in seen) - return; - // @ts-ignore - seen[dep] = true; - const isCss = dep.endsWith('.css'); - const cssSelector = isCss ? '[rel="stylesheet"]' : ''; - // @ts-ignore check if the file is already preloaded by SSR markup - if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) { - return; - } - // @ts-ignore - const link = document.createElement('link'); - // @ts-ignore - link.rel = isCss ? 'stylesheet' : scriptRel; - if (!isCss) { - link.as = 'script'; - link.crossOrigin = ''; - } - link.href = dep; - // @ts-ignore - document.head.appendChild(link); - if (isCss) { - return new Promise((res, rej) => { - link.addEventListener('load', res); - link.addEventListener('error', rej); - }); - } - })).then(() => baseModule()); -} -/** - * Build only. During serve this is performed as part of ./importAnalysis. - */ -function buildImportAnalysisPlugin(config) { - const ssr = !!config.build.ssr; - const insertPreload = !(ssr || !!config.build.lib); - const scriptRel = config.build.polyfillModulePreload - ? `'modulepreload'` - : `(${detectScriptRel.toString()})()`; - const preloadCode = `const scriptRel = ${scriptRel};const seen = {};const base = '${preloadBaseMarker}';export const ${preloadMethod} = ${preload.toString()}`; - return { - name: 'vite:build-import-analysis', - resolveId(id) { - if (id === preloadHelperId) { - return id; - } - }, - load(id) { - if (id === preloadHelperId) { - return preloadCode.replace(preloadBaseMarker, config.base); - } - }, - async transform(source, importer) { - if (importer.includes('node_modules') && - !source.includes('import.meta.glob')) { - return; - } - await init; - let imports = []; - try { - imports = parse$f(source)[0]; - } - catch (e) { - this.error(e, e.idx); - } - if (!imports.length) { - return null; - } - let s; - const str = () => s || (s = new MagicString(source)); - let needPreloadHelper = false; - for (let index = 0; index < imports.length; index++) { - const { s: start, e: end, ss: expStart, n: specifier, d: dynamicIndex } = imports[index]; - // import.meta.glob - if (source.slice(start, end) === 'import.meta' && - source.slice(end, end + 5) === '.glob') { - const { importsString, exp, endIndex, isEager } = await transformImportGlob(source, start, importer, index, config.root, undefined, insertPreload); - str().prepend(importsString); - str().overwrite(expStart, endIndex, exp); - if (!isEager) { - needPreloadHelper = true; - } - continue; - } - if (dynamicIndex > -1 && insertPreload) { - needPreloadHelper = true; - const dynamicEnd = source.indexOf(`)`, end) + 1; - const original = source.slice(dynamicIndex, dynamicEnd); - const replacement = `${preloadMethod}(() => ${original},${isModernFlag}?"${preloadMarker}":void 0)`; - str().overwrite(dynamicIndex, dynamicEnd, replacement); - } - // Differentiate CSS imports that use the default export from those that - // do not by injecting a ?used query - this allows us to avoid including - // the CSS string when unnecessary (esbuild has trouble treeshaking - // them) - if (specifier && - isCSSRequest(specifier) && - source.slice(expStart, start).includes('from') && - // edge case for package names ending with .css (e.g normalize.css) - !(bareImportRE.test(specifier) && !specifier.includes('/'))) { - const url = specifier.replace(/\?|$/, (m) => `?used${m ? '&' : ''}`); - str().overwrite(start, end, dynamicIndex > -1 ? `'${url}'` : url); - } - } - if (needPreloadHelper && - insertPreload && - !source.includes(`const ${preloadMethod} =`)) { - str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`); - } - if (s) { - return { - code: s.toString(), - map: config.build.sourcemap ? s.generateMap({ hires: true }) : null - }; - } - }, - renderChunk(code, _, { format }) { - // make sure we only perform the preload logic in modern builds. - if (code.indexOf(isModernFlag) > -1) { - const re = new RegExp(isModernFlag, 'g'); - const isModern = String(format === 'es'); - if (config.build.sourcemap) { - const s = new MagicString(code); - let match; - while ((match = re.exec(code))) { - s.overwrite(match.index, match.index + isModernFlag.length, isModern); - } - return { - code: s.toString(), - map: s.generateMap({ hires: true }) - }; - } - else { - return code.replace(re, isModern); - } - } - return null; - }, - generateBundle({ format }, bundle) { - if (format !== 'es' || ssr) { - return; - } - for (const file in bundle) { - const chunk = bundle[file]; - // can't use chunk.dynamicImports.length here since some modules e.g. - // dynamic import to constant json may get inlined. - if (chunk.type === 'chunk' && chunk.code.indexOf(preloadMarker) > -1) { - const code = chunk.code; - let imports; - try { - imports = parse$f(code)[0].filter((i) => i.d > -1); - } - catch (e) { - this.error(e, e.idx); - } - if (imports.length) { - const s = new MagicString(code); - for (let index = 0; index < imports.length; index++) { - const { s: start, e: end, d: dynamicIndex } = imports[index]; - // check the chunk being imported - const url = code.slice(start, end); - const deps = new Set(); - let hasRemovedPureCssChunk = false; - if (url[0] === `"` && url[url.length - 1] === `"`) { - const ownerFilename = chunk.fileName; - // literal import - trace direct imports and add to deps - const analyzed = new Set(); - const addDeps = (filename) => { - if (filename === ownerFilename) - return; - if (analyzed.has(filename)) - return; - analyzed.add(filename); - const chunk = bundle[filename]; - if (chunk) { - deps.add(chunk.fileName); - const cssFiles = chunkToEmittedCssFileMap.get(chunk); - if (cssFiles) { - cssFiles.forEach((file) => { - deps.add(file); - }); - } - chunk.imports.forEach(addDeps); - } - else { - const removedPureCssFiles = removedPureCssFilesCache.get(config); - const chunk = removedPureCssFiles.get(filename); - if (chunk) { - const cssFiles = chunkToEmittedCssFileMap.get(chunk); - if (cssFiles && cssFiles.size > 0) { - cssFiles.forEach((file) => { - deps.add(file); - }); - hasRemovedPureCssChunk = true; - } - s.overwrite(dynamicIndex, end + 1, 'Promise.resolve({})'); - } - } - }; - const normalizedFile = path__default.posix.join(path__default.posix.dirname(chunk.fileName), url.slice(1, -1)); - addDeps(normalizedFile); - } - let markPos = code.indexOf(preloadMarker, end); - // fix issue #3051 - if (markPos === -1 && imports.length === 1) { - markPos = code.indexOf(preloadMarker); - } - if (markPos > 0) { - s.overwrite(markPos - 1, markPos + preloadMarker.length + 1, - // the dep list includes the main chunk, so only need to - // preload when there are actual other deps. - deps.size > 1 || - // main chunk is removed - (hasRemovedPureCssChunk && deps.size > 0) - ? `[${[...deps].map((d) => JSON.stringify(d)).join(',')}]` - : `[]`); - } - } - chunk.code = s.toString(); - // TODO source map - } - // there may still be markers due to inlined dynamic imports, remove - // all the markers regardless - chunk.code = chunk.code.replace(preloadMarkerRE, 'void 0'); - } - } - } - }; -} - -const modulePreloadPolyfillId = 'vite/modulepreload-polyfill'; -function modulePreloadPolyfillPlugin(config) { - const skip = config.build.ssr; - let polyfillString; - return { - name: 'vite:modulepreload-polyfill', - resolveId(id) { - if (id === modulePreloadPolyfillId) { - return id; - } - }, - load(id) { - if (id === modulePreloadPolyfillId) { - if (skip) { - return ''; - } - if (!polyfillString) { - polyfillString = - `const p = ${polyfill.toString()};` + `${isModernFlag}&&p();`; - } - return polyfillString; - } - } - }; -} -function polyfill() { - const relList = document.createElement('link').relList; - if (relList && relList.supports && relList.supports('modulepreload')) { - return; - } - for (const link of document.querySelectorAll('link[rel="modulepreload"]')) { - processPreload(link); - } - new MutationObserver((mutations) => { - for (const mutation of mutations) { - if (mutation.type !== 'childList') { - continue; - } - for (const node of mutation.addedNodes) { - if (node.tagName === 'LINK' && node.rel === 'modulepreload') - processPreload(node); - } - } - }).observe(document, { childList: true, subtree: true }); - function getFetchOpts(script) { - const fetchOpts = {}; - if (script.integrity) - fetchOpts.integrity = script.integrity; - if (script.referrerpolicy) - fetchOpts.referrerPolicy = script.referrerpolicy; - if (script.crossorigin === 'use-credentials') - fetchOpts.credentials = 'include'; - else if (script.crossorigin === 'anonymous') - fetchOpts.credentials = 'omit'; - else - fetchOpts.credentials = 'same-origin'; - return fetchOpts; - } - function processPreload(link) { - if (link.ep) - // ep marker = processed - return; - link.ep = true; - // prepopulate the load record - const fetchOpts = getFetchOpts(link); - fetch(link.href, fetchOpts); - } -} - -const htmlProxyRE = /\?html-proxy&index=(\d+)\.js$/; -const isHTMLProxy = (id) => htmlProxyRE.test(id); -// HTML Proxy Caches are stored by config -> filePath -> index -const htmlProxyMap = new WeakMap(); -function htmlInlineScriptProxyPlugin(config) { - return { - name: 'vite:html-inline-script-proxy', - resolveId(id) { - if (htmlProxyRE.test(id)) { - return id; - } - }, - buildStart() { - htmlProxyMap.set(config, new Map()); - }, - load(id) { - const proxyMatch = id.match(htmlProxyRE); - if (proxyMatch) { - const index = Number(proxyMatch[1]); - const file = cleanUrl(id); - const url = file.replace(normalizePath$4(config.root), ''); - const result = htmlProxyMap.get(config).get(url)[index]; - if (result) { - return result; - } - else { - throw new Error(`No matching HTML proxy module found from ${id}`); - } - } - } - }; -} -/** Add script to cache */ -function addToHTMLProxyCache(config, filePath, index, code) { - if (!htmlProxyMap.get(config)) { - htmlProxyMap.set(config, new Map()); - } - if (!htmlProxyMap.get(config).get(filePath)) { - htmlProxyMap.get(config).set(filePath, []); - } - htmlProxyMap.get(config).get(filePath)[index] = code; -} -// this extends the config in @vue/compiler-sfc with -const assetAttrsConfig = { - link: ['href'], - video: ['src', 'poster'], - source: ['src', 'srcset'], - img: ['src', 'srcset'], - image: ['xlink:href', 'href'], - use: ['xlink:href', 'href'] -}; -const isAsyncScriptMap = new WeakMap(); -async function traverseHtml(html, filePath, visitor) { - // lazy load compiler - const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-a5b4350d.js'); }).then(function (n) { return n.compilerDom_cjs; }); - // @vue/compiler-core doesn't like lowercase doctypes - html = html.replace(/ url.startsWith('#') || - isExternalUrl(url) || - isDataUrl(url) || - checkPublicFile(url, config); - return { - name: 'vite:build-html', - buildStart() { - isAsyncScriptMap.set(config, new Map()); - }, - async transform(html, id) { - if (id.endsWith('.html')) { - const publicPath = `/${slash$3(path__default.relative(config.root, id))}`; - // pre-transform - html = await applyHtmlTransforms(html, preHooks, { - path: publicPath, - filename: id - }); - let js = ''; - const s = new MagicString(html); - const assetUrls = []; - let inlineModuleIndex = -1; - let everyScriptIsAsync = true; - let someScriptsAreAsync = false; - let someScriptsAreDefer = false; - await traverseHtml(html, id, (node) => { - if (node.type !== 1 /* ELEMENT */) { - return; - } - let shouldRemove = false; - // script tags - if (node.tag === 'script') { - const { src, isModule, isAsync } = getScriptInfo(node); - const url = src && src.value && src.value.content; - if (url && checkPublicFile(url, config)) { - // referencing public dir url, prefix with base - s.overwrite(src.value.loc.start.offset, src.value.loc.end.offset, `"${config.base + url.slice(1)}"`); - } - if (isModule) { - inlineModuleIndex++; - if (url && !isExcludedUrl(url)) { - // - const filePath = id.replace(normalizePath$4(config.root), '') - addToHTMLProxyCache(config, filePath, inlineModuleIndex, contents); - js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`; - shouldRemove = true; - } - everyScriptIsAsync && (everyScriptIsAsync = isAsync); - someScriptsAreAsync || (someScriptsAreAsync = isAsync); - someScriptsAreDefer || (someScriptsAreDefer = !isAsync); - } - } - // For asset references in index.html, also generate an import - // statement for each - this will be handled by the asset plugin - const assetAttrs = assetAttrsConfig[node.tag]; - if (assetAttrs) { - for (const p of node.props) { - if (p.type === 6 /* ATTRIBUTE */ && - p.value && - assetAttrs.includes(p.name)) { - const url = p.value.content; - if (!isExcludedUrl(url)) { - if (node.tag === 'link' && isCSSRequest(url)) { - // CSS references, convert to import - js += `\nimport ${JSON.stringify(url)}`; - shouldRemove = true; - } - else { - assetUrls.push(p); - } - } - else if (checkPublicFile(url, config)) { - s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"`); - } - } - } - } - if (shouldRemove) { - // remove the script tag from the html. we are going to inject new - // ones in the end. - s.remove(node.loc.start.offset, node.loc.end.offset); - } - }); - isAsyncScriptMap.get(config).set(id, everyScriptIsAsync); - if (someScriptsAreAsync && someScriptsAreDefer) { - config.logger.warn(`\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`); - } - // for each encountered asset url, rewrite original html so that it - // references the post-build location. - for (const attr of assetUrls) { - const value = attr.value; - try { - const url = attr.name === 'srcset' - ? await processSrcSet(value.content, ({ url }) => urlToBuiltUrl(url, id, config, this)) - : await urlToBuiltUrl(value.content, id, config, this); - s.overwrite(value.loc.start.offset, value.loc.end.offset, `"${url}"`); - } - catch (e) { - // #1885 preload may be pointing to urls that do not exist - // locally on disk - if (e.code !== 'ENOENT') { - throw e; - } - } - } - processedHtml.set(id, s.toString()); - // inject module preload polyfill only when configured and needed - if (config.build.polyfillModulePreload && - (someScriptsAreAsync || someScriptsAreDefer)) { - js = `import "${modulePreloadPolyfillId}";\n${js}`; - } - return js; - } - }, - async generateBundle(options, bundle) { - const analyzedChunk = new Map(); - const getImportedChunks = (chunk, seen = new Set()) => { - const chunks = []; - chunk.imports.forEach((file) => { - const importee = bundle[file]; - if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk' && !seen.has(file)) { - seen.add(file); - // post-order traversal - chunks.push(...getImportedChunks(importee, seen)); - chunks.push(importee); - } - }); - return chunks; - }; - const toScriptTag = (chunk, isAsync) => ({ - tag: 'script', - attrs: { - ...(isAsync ? { async: true } : {}), - type: 'module', - crossorigin: true, - src: toPublicPath(chunk.fileName, config) - } - }); - const toPreloadTag = (chunk) => ({ - tag: 'link', - attrs: { - rel: 'modulepreload', - href: toPublicPath(chunk.fileName, config) - } - }); - const getCssTagsForChunk = (chunk, seen = new Set()) => { - const tags = []; - if (!analyzedChunk.has(chunk)) { - analyzedChunk.set(chunk, 1); - chunk.imports.forEach((file) => { - const importee = bundle[file]; - if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk') { - tags.push(...getCssTagsForChunk(importee, seen)); - } - }); - } - const cssFiles = chunkToEmittedCssFileMap.get(chunk); - if (cssFiles) { - cssFiles.forEach((file) => { - if (!seen.has(file)) { - seen.add(file); - tags.push({ - tag: 'link', - attrs: { - rel: 'stylesheet', - href: toPublicPath(file, config) - } - }); - } - }); - } - return tags; - }; - for (const [id, html] of processedHtml) { - const isAsync = isAsyncScriptMap.get(config).get(id); - // resolve asset url references - let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => { - return config.base + getAssetFilename(fileHash, config) + postfix; - }); - // find corresponding entry chunk - const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' && - chunk.isEntry && - chunk.facadeModuleId === id); - let canInlineEntry = false; - // inject chunk asset links - if (chunk) { - // an entry chunk can be inlined if - // - it's an ES module (e.g. not generated by the legacy plugin) - // - it contains no meaningful code other than import statements - if (options.format === 'es' && isEntirelyImport(chunk.code)) { - canInlineEntry = true; - } - // when not inlined, inject `); - } - } - // elements with [href/src] attrs - const assetAttrs = assetAttrsConfig[node.tag]; - if (assetAttrs) { - for (const p of node.props) { - if (p.type === 6 /* ATTRIBUTE */ && - p.value && - assetAttrs.includes(p.name)) { - processNodeUrl(p, s, config, htmlPath, originalUrl); - } - } - } - }); - html = s.toString(); - return { - html, - tags: [ - { - tag: 'script', - attrs: { - type: 'module', - src: path__default.posix.join(base, CLIENT_PUBLIC_PATH) - }, - injectTo: 'head-prepend' - } - ] - }; -}; -function indexHtmlMiddleware(server) { - // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` - return async function viteIndexHtmlMiddleware(req, res, next) { - if (res.writableEnded) { - return next(); - } - const url = req.url && cleanUrl(req.url); - // spa-fallback always redirects to /index.html - if ((url === null || url === void 0 ? void 0 : url.endsWith('.html')) && req.headers['sec-fetch-dest'] !== 'script') { - const filename = getHtmlFilename(url, server); - if (fs__default.existsSync(filename)) { - try { - let html = fs__default.readFileSync(filename, 'utf-8'); - html = await server.transformIndexHtml(url, html, req.originalUrl); - return send$1(req, res, html, 'html'); - } - catch (e) { - return next(e); - } - } - } - next(); - }; -} - -const logTime = createDebugger('vite:time'); -function timeMiddleware(root) { - // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` - return function viteTimeMiddleware(req, res, next) { - const start = perf_hooks.performance.now(); - const end = res.end; - res.end = (...args) => { - logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`); - // @ts-ignore - return end.call(res, ...args); - }; - next(); - }; -} - -class ModuleNode { - constructor(url) { - /** - * Resolved file system path + query - */ - this.id = null; - this.file = null; - this.importers = new Set(); - this.importedModules = new Set(); - this.acceptedHmrDeps = new Set(); - this.isSelfAccepting = false; - this.transformResult = null; - this.ssrTransformResult = null; - this.ssrModule = null; - this.lastHMRTimestamp = 0; - this.url = url; - this.type = isDirectCSSRequest(url) ? 'css' : 'js'; - } -} -function invalidateSSRModule(mod, seen) { - if (seen.has(mod)) { - return; - } - seen.add(mod); - mod.ssrModule = null; - mod.importers.forEach((importer) => invalidateSSRModule(importer, seen)); -} -class ModuleGraph { - constructor(container) { - this.urlToModuleMap = new Map(); - this.idToModuleMap = new Map(); - // a single file may corresponds to multiple modules with different queries - this.fileToModulesMap = new Map(); - this.safeModulesPath = new Set(); - this.container = container; - } - async getModuleByUrl(rawUrl) { - const [url] = await this.resolveUrl(rawUrl); - return this.urlToModuleMap.get(url); - } - getModuleById(id) { - return this.idToModuleMap.get(removeTimestampQuery(id)); - } - getModulesByFile(file) { - return this.fileToModulesMap.get(file); - } - onFileChange(file) { - const mods = this.getModulesByFile(file); - if (mods) { - const seen = new Set(); - mods.forEach((mod) => { - this.invalidateModule(mod, seen); - }); - } - } - invalidateModule(mod, seen = new Set()) { - mod.transformResult = null; - mod.ssrTransformResult = null; - invalidateSSRModule(mod, seen); - } - invalidateAll() { - const seen = new Set(); - this.idToModuleMap.forEach((mod) => { - this.invalidateModule(mod, seen); - }); - } - /** - * Update the module graph based on a module's updated imports information - * If there are dependencies that no longer have any importers, they are - * returned as a Set. - */ - async updateModuleInfo(mod, importedModules, acceptedModules, isSelfAccepting) { - mod.isSelfAccepting = isSelfAccepting; - const prevImports = mod.importedModules; - const nextImports = (mod.importedModules = new Set()); - let noLongerImported; - // update import graph - for (const imported of importedModules) { - const dep = typeof imported === 'string' - ? await this.ensureEntryFromUrl(imported) - : imported; - dep.importers.add(mod); - nextImports.add(dep); - } - // remove the importer from deps that were imported but no longer are. - prevImports.forEach((dep) => { - if (!nextImports.has(dep)) { - dep.importers.delete(mod); - if (!dep.importers.size) { - (noLongerImported || (noLongerImported = new Set())).add(dep); - } - } - }); - // update accepted hmr deps - const deps = (mod.acceptedHmrDeps = new Set()); - for (const accepted of acceptedModules) { - const dep = typeof accepted === 'string' - ? await this.ensureEntryFromUrl(accepted) - : accepted; - deps.add(dep); - } - return noLongerImported; - } - async ensureEntryFromUrl(rawUrl) { - const [url, resolvedId] = await this.resolveUrl(rawUrl); - let mod = this.urlToModuleMap.get(url); - if (!mod) { - mod = new ModuleNode(url); - this.urlToModuleMap.set(url, mod); - mod.id = resolvedId; - this.idToModuleMap.set(resolvedId, mod); - const file = (mod.file = cleanUrl(resolvedId)); - let fileMappedModules = this.fileToModulesMap.get(file); - if (!fileMappedModules) { - fileMappedModules = new Set(); - this.fileToModulesMap.set(file, fileMappedModules); - } - fileMappedModules.add(mod); - } - return mod; - } - // some deps, like a css file referenced via @import, don't have its own - // url because they are inlined into the main css import. But they still - // need to be represented in the module graph so that they can trigger - // hmr in the importing css file. - createFileOnlyEntry(file) { - file = normalizePath$4(file); - let fileMappedModules = this.fileToModulesMap.get(file); - if (!fileMappedModules) { - fileMappedModules = new Set(); - this.fileToModulesMap.set(file, fileMappedModules); - } - const url = `${FS_PREFIX}${file}`; - for (const m of fileMappedModules) { - if (m.url === url || m.id === file) { - return m; - } - } - const mod = new ModuleNode(url); - mod.file = file; - fileMappedModules.add(mod); - return mod; - } - // for incoming urls, it is important to: - // 1. remove the HMR timestamp query (?t=xxxx) - // 2. resolve its extension so that urls with or without extension all map to - // the same module - async resolveUrl(url) { - var _a; - url = removeImportQuery(removeTimestampQuery(url)); - const resolvedId = ((_a = (await this.container.resolveId(url))) === null || _a === void 0 ? void 0 : _a.id) || url; - const ext = path$t.extname(cleanUrl(resolvedId)); - const { pathname, search, hash } = require$$0$8.parse(url); - if (ext && !pathname.endsWith(ext)) { - url = pathname + ext + (search || '') + (hash || ''); - } - return [url, resolvedId]; - } -} - -const debugHmr = createDebugger('vite:hmr'); -const normalizedClientDir = normalizePath$4(CLIENT_DIR); -function getShortName(file, root) { - return file.startsWith(root + '/') ? path__default.posix.relative(root, file) : file; -} -async function handleHMRUpdate(file, server) { - const { ws, config, moduleGraph } = server; - const shortFile = getShortName(file, config.root); - const isConfig = file === config.configFile; - const isConfigDependency = config.configFileDependencies.some((name) => file === path__default.resolve(name)); - const isEnv = config.inlineConfig.envFile !== false && file.endsWith('.env'); - if (isConfig || isConfigDependency || isEnv) { - // auto restart server - debugHmr(`[config change] ${source.dim(shortFile)}`); - config.logger.info(source.green(`${path__default.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true }); - await restartServer(server); - return; - } - debugHmr(`[file change] ${source.dim(shortFile)}`); - // (dev only) the client itself cannot be hot updated. - if (file.startsWith(normalizedClientDir)) { - ws.send({ - type: 'full-reload', - path: '*' - }); - return; - } - const mods = moduleGraph.getModulesByFile(file); - // check if any plugin wants to perform custom HMR handling - const timestamp = Date.now(); - const hmrContext = { - file, - timestamp, - modules: mods ? [...mods] : [], - read: () => readModifiedFile(file), - server - }; - for (const plugin of config.plugins) { - if (plugin.handleHotUpdate) { - const filteredModules = await plugin.handleHotUpdate(hmrContext); - if (filteredModules) { - hmrContext.modules = filteredModules; - break; - } - } - } - if (!hmrContext.modules.length) { - // html file cannot be hot updated - if (file.endsWith('.html')) { - config.logger.info(source.green(`page reload `) + source.dim(shortFile), { - clear: true, - timestamp: true - }); - ws.send({ - type: 'full-reload', - path: config.server.middlewareMode - ? '*' - : '/' + normalizePath$4(path__default.relative(config.root, file)) - }); - } - else { - // loaded but not in the module graph, probably not js - debugHmr(`[no modules matched] ${source.dim(shortFile)}`); - } - return; - } - updateModules(shortFile, hmrContext.modules, timestamp, server); -} -function updateModules(file, modules, timestamp, { config, ws }) { - const updates = []; - const invalidatedModules = new Set(); - let needFullReload = false; - for (const mod of modules) { - invalidate(mod, timestamp, invalidatedModules); - if (needFullReload) { - continue; - } - const boundaries = new Set(); - const hasDeadEnd = propagateUpdate(mod, boundaries); - if (hasDeadEnd) { - needFullReload = true; - continue; - } - updates.push(...[...boundaries].map(({ boundary, acceptedVia }) => ({ - type: `${boundary.type}-update`, - timestamp, - path: boundary.url, - acceptedPath: acceptedVia.url - }))); - } - if (needFullReload) { - config.logger.info(source.green(`page reload `) + source.dim(file), { - clear: true, - timestamp: true - }); - ws.send({ - type: 'full-reload' - }); - } - else { - config.logger.info(updates - .map(({ path }) => source.green(`hmr update `) + source.dim(path)) - .join('\n'), { clear: true, timestamp: true }); - ws.send({ - type: 'update', - updates - }); - } -} -async function handleFileAddUnlink(file, server, isUnlink = false) { - var _a; - const modules = [...((_a = server.moduleGraph.getModulesByFile(file)) !== null && _a !== void 0 ? _a : [])]; - if (isUnlink && file in server._globImporters) { - delete server._globImporters[file]; - } - else { - for (const i in server._globImporters) { - const { module, importGlobs } = server._globImporters[i]; - for (const { base, pattern } of importGlobs) { - if (minimatch_1(file, pattern) || minimatch_1(path__default.relative(base, file), pattern)) { - modules.push(module); - // We use `onFileChange` to invalidate `module.file` so that subsequent `ssrLoadModule()` - // calls get fresh glob import results with(out) the newly added(/removed) `file`. - server.moduleGraph.onFileChange(module.file); - break; - } - } - } - } - if (modules.length > 0) { - updateModules(getShortName(file, server.config.root), modules, Date.now(), server); - } -} -function propagateUpdate(node, boundaries, currentChain = [node]) { - if (node.isSelfAccepting) { - boundaries.add({ - boundary: node, - acceptedVia: node - }); - // additionally check for CSS importers, since a PostCSS plugin like - // Tailwind JIT may register any file as a dependency to a CSS file. - for (const importer of node.importers) { - if (isCSSRequest(importer.url) && !currentChain.includes(importer)) { - propagateUpdate(importer, boundaries, currentChain.concat(importer)); - } - } - return false; - } - if (!node.importers.size) { - return true; - } - // #3716, #3913 - // For a non-CSS file, if all of its importers are CSS files (registered via - // PostCSS plugins) it should be considered a dead end and force full reload. - if (!isCSSRequest(node.url) && - [...node.importers].every((i) => isCSSRequest(i.url))) { - return true; - } - for (const importer of node.importers) { - const subChain = currentChain.concat(importer); - if (importer.acceptedHmrDeps.has(node)) { - boundaries.add({ - boundary: importer, - acceptedVia: node - }); - continue; - } - if (currentChain.includes(importer)) { - // circular deps is considered dead end - return true; - } - if (propagateUpdate(importer, boundaries, subChain)) { - return true; - } - } - return false; -} -function invalidate(mod, timestamp, seen) { - if (seen.has(mod)) { - return; - } - seen.add(mod); - mod.lastHMRTimestamp = timestamp; - mod.transformResult = null; - mod.ssrModule = null; - mod.ssrTransformResult = null; - mod.importers.forEach((importer) => { - if (!importer.acceptedHmrDeps.has(mod)) { - invalidate(importer, timestamp, seen); - } - }); -} -function handlePrunedModules(mods, { ws }) { - // update the disposed modules' hmr timestamp - // since if it's re-imported, it should re-apply side effects - // and without the timestamp the browser will not re-import it! - const t = Date.now(); - mods.forEach((mod) => { - mod.lastHMRTimestamp = t; - debugHmr(`[dispose] ${source.dim(mod.file)}`); - }); - ws.send({ - type: 'prune', - paths: [...mods].map((m) => m.url) - }); -} -/** - * Lex import.meta.hot.accept() for accepted deps. - * Since hot.accept() can only accept string literals or array of string - * literals, we don't really need a heavy @babel/parse call on the entire source. - * - * @returns selfAccepts - */ -function lexAcceptedHmrDeps(code, start, urls) { - let state = 0 /* inCall */; - // the state can only be 2 levels deep so no need for a stack - let prevState = 0 /* inCall */; - let currentDep = ''; - function addDep(index) { - urls.add({ - url: currentDep, - start: index - currentDep.length - 1, - end: index + 1 - }); - currentDep = ''; - } - for (let i = start; i < code.length; i++) { - const char = code.charAt(i); - switch (state) { - case 0 /* inCall */: - case 4 /* inArray */: - if (char === `'`) { - prevState = state; - state = 1 /* inSingleQuoteString */; - } - else if (char === `"`) { - prevState = state; - state = 2 /* inDoubleQuoteString */; - } - else if (char === '`') { - prevState = state; - state = 3 /* inTemplateString */; - } - else if (/\s/.test(char)) { - continue; - } - else { - if (state === 0 /* inCall */) { - if (char === `[`) { - state = 4 /* inArray */; - } - else { - // reaching here means the first arg is neither a string literal - // nor an Array literal (direct callback) or there is no arg - // in both case this indicates a self-accepting module - return true; // done - } - } - else if (state === 4 /* inArray */) { - if (char === `]`) { - return false; // done - } - else if (char === ',') { - continue; - } - else { - error$1(i); - } - } - } - break; - case 1 /* inSingleQuoteString */: - if (char === `'`) { - addDep(i); - if (prevState === 0 /* inCall */) { - // accept('foo', ...) - return false; - } - else { - state = prevState; - } - } - else { - currentDep += char; - } - break; - case 2 /* inDoubleQuoteString */: - if (char === `"`) { - addDep(i); - if (prevState === 0 /* inCall */) { - // accept('foo', ...) - return false; - } - else { - state = prevState; - } - } - else { - currentDep += char; - } - break; - case 3 /* inTemplateString */: - if (char === '`') { - addDep(i); - if (prevState === 0 /* inCall */) { - // accept('foo', ...) - return false; - } - else { - state = prevState; - } - } - else if (char === '$' && code.charAt(i + 1) === '{') { - error$1(i); - } - else { - currentDep += char; - } - break; - default: - throw new Error('unknown import.meta.hot lexer state'); - } - } - return false; -} -function error$1(pos) { - const err = new Error(`import.meta.accept() can only accept string literals or an ` + - `Array of string literals.`); - err.pos = pos; - throw err; -} -// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file -// change event and sometimes this can be too early and get an empty buffer. -// Poll until the file's modified time has changed before reading again. -async function readModifiedFile(file) { - const content = fs__default.readFileSync(file, 'utf-8'); - if (!content) { - const mtime = fs__default.statSync(file).mtimeMs; - await new Promise((r) => { - let n = 0; - const poll = async () => { - n++; - const newMtime = fs__default.statSync(file).mtimeMs; - if (newMtime !== mtime || n > 10) { - r(0); - } - else { - setTimeout(poll, 10); - } - }; - setTimeout(poll, 10); - }); - return fs__default.readFileSync(file, 'utf-8'); - } - else { - return content; - } -} -async function restartServer(server) { - // @ts-ignore - global.__vite_start_time = perf_hooks.performance.now(); - const { port } = server.config.server; - await server.close(); - let newServer = null; - try { - newServer = await createServer(server.config.inlineConfig); - } - catch (err) { - server.config.logger.error(err.message, { - timestamp: true - }); - return; - } - for (const key in newServer) { - if (key !== 'app') { - // @ts-ignore - server[key] = newServer[key]; - } - } - if (!server.config.server.middlewareMode) { - await server.listen(port, true); - } - else { - server.config.logger.info('server restarted.', { timestamp: true }); - } -} - -var isWsl$2 = {exports: {}}; - -const fs$7 = fs__default; - -let isDocker$2; - -function hasDockerEnv() { - try { - fs$7.statSync('/.dockerenv'); - return true; - } catch (_) { - return false; - } -} - -function hasDockerCGroup() { - try { - return fs$7.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); - } catch (_) { - return false; - } -} - -var isDocker_1 = () => { - if (isDocker$2 === undefined) { - isDocker$2 = hasDockerEnv() || hasDockerCGroup(); - } - - return isDocker$2; -}; - -const os$4 = require$$0__default$1; -const fs$6 = fs__default; -const isDocker$1 = isDocker_1; - -const isWsl$1 = () => { - if (process.platform !== 'linux') { - return false; - } - - if (os$4.release().toLowerCase().includes('microsoft')) { - if (isDocker$1()) { - return false; - } - - return true; - } - - try { - return fs$6.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? - !isDocker$1() : false; - } catch (_) { - return false; - } -}; - -if (process.env.__IS_WSL_TEST__) { - isWsl$2.exports = isWsl$1; -} else { - isWsl$2.exports = isWsl$1(); -} - -var defineLazyProp = (object, propertyName, fn) => { - const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); - - Object.defineProperty(object, propertyName, { - configurable: true, - enumerable: true, - get() { - const result = fn(); - define(result); - return result; - }, - set(value) { - define(value); - } - }); - - return object; -}; - -const path$9 = path__default; -const childProcess$3 = require$$1__default$4; -const {promises: fs$5, constants: fsConstants} = fs__default; -const isWsl = isWsl$2.exports; -const isDocker = isDocker_1; -const defineLazyProperty = defineLazyProp; - -// Path to included `xdg-open`. -const localXdgOpenPath = path$9.join(__dirname, 'xdg-open'); - -const {platform, arch} = process; - -/** -Get the mount point for fixed drives in WSL. - -@inner -@returns {string} The mount point. -*/ -const getWslDrivesMountPoint = (() => { - // Default value for "root" param - // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config - const defaultMountPoint = '/mnt/'; - - let mountPoint; - - return async function () { - if (mountPoint) { - // Return memoized mount point value - return mountPoint; - } - - const configFilePath = '/etc/wsl.conf'; - - let isConfigFileExists = false; - try { - await fs$5.access(configFilePath, fsConstants.F_OK); - isConfigFileExists = true; - } catch {} - - if (!isConfigFileExists) { - return defaultMountPoint; - } - - const configContent = await fs$5.readFile(configFilePath, {encoding: 'utf8'}); - const configMountPoint = /(?.*)/g.exec(configContent); - - if (!configMountPoint) { - return defaultMountPoint; - } - - mountPoint = configMountPoint.groups.mountPoint.trim(); - mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`; - - return mountPoint; - }; -})(); - -const pTryEach = async (array, mapper) => { - let latestError; - - for (const item of array) { - try { - return await mapper(item); // eslint-disable-line no-await-in-loop - } catch (error) { - latestError = error; - } - } - - throw latestError; -}; - -const open = async (target, options) => { - if (typeof target !== 'string') { - throw new TypeError('Expected a `target`'); - } - - options = { - wait: false, - background: false, - newInstance: false, - allowNonzeroExitCode: false, - ...options - }; - - if (Array.isArray(options.app)) { - return pTryEach(options.app, singleApp => open(target, { - ...options, - app: singleApp - })); - } - - let {name: app, arguments: appArguments = []} = options.app || {}; - appArguments = [...appArguments]; - - if (Array.isArray(app)) { - return pTryEach(app, appName => open(target, { - ...options, - app: { - name: appName, - arguments: appArguments - } - })); - } - - let command; - const cliArguments = []; - const childProcessOptions = {}; - - if (platform === 'darwin') { - command = 'open'; - - if (options.wait) { - cliArguments.push('--wait-apps'); - } - - if (options.background) { - cliArguments.push('--background'); - } - - if (options.newInstance) { - cliArguments.push('--new'); - } - - if (app) { - cliArguments.push('-a', app); - } - } else if (platform === 'win32' || (isWsl && !isDocker())) { - const mountPoint = await getWslDrivesMountPoint(); - - command = isWsl ? - `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : - `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; - - cliArguments.push( - '-NoProfile', - '-NonInteractive', - '–ExecutionPolicy', - 'Bypass', - '-EncodedCommand' - ); - - if (!isWsl) { - childProcessOptions.windowsVerbatimArguments = true; - } - - const encodedArguments = ['Start']; - - if (options.wait) { - encodedArguments.push('-Wait'); - } - - if (app) { - // Double quote with double quotes to ensure the inner quotes are passed through. - // Inner quotes are delimited for PowerShell interpretation with backticks. - encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList'); - appArguments.unshift(target); - } else { - encodedArguments.push(`"${target}"`); - } - - if (appArguments.length > 0) { - appArguments = appArguments.map(arg => `"\`"${arg}\`""`); - encodedArguments.push(appArguments.join(',')); - } - - // Using Base64-encoded command, accepted by PowerShell, to allow special characters. - target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); - } else { - if (app) { - command = app; - } else { - // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. - const isBundled = !__dirname || __dirname === '/'; - - // Check if local `xdg-open` exists and is executable. - let exeLocalXdgOpen = false; - try { - await fs$5.access(localXdgOpenPath, fsConstants.X_OK); - exeLocalXdgOpen = true; - } catch {} - - const useSystemXdgOpen = process.versions.electron || - platform === 'android' || isBundled || !exeLocalXdgOpen; - command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; - } - - if (appArguments.length > 0) { - cliArguments.push(...appArguments); - } - - if (!options.wait) { - // `xdg-open` will block the process unless stdio is ignored - // and it's detached from the parent even if it's unref'd. - childProcessOptions.stdio = 'ignore'; - childProcessOptions.detached = true; - } - } - - cliArguments.push(target); - - if (platform === 'darwin' && appArguments.length > 0) { - cliArguments.push('--args', ...appArguments); - } - - const subprocess = childProcess$3.spawn(command, cliArguments, childProcessOptions); - - if (options.wait) { - return new Promise((resolve, reject) => { - subprocess.once('error', reject); - - subprocess.once('close', exitCode => { - if (options.allowNonzeroExitCode && exitCode > 0) { - reject(new Error(`Exited with code ${exitCode}`)); - return; - } - - resolve(subprocess); - }); - }); - } - - subprocess.unref(); - - return subprocess; -}; - -function detectArchBinary(binary) { - if (typeof binary === 'string' || Array.isArray(binary)) { - return binary; - } - - const {[arch]: archBinary} = binary; - - if (!archBinary) { - throw new Error(`${arch} is not supported`); - } - - return archBinary; -} - -function detectPlatformBinary({[platform]: platformBinary}, {wsl}) { - if (wsl && isWsl) { - return detectArchBinary(wsl); - } - - if (!platformBinary) { - throw new Error(`${platform} is not supported`); - } - - return detectArchBinary(platformBinary); -} - -const apps = {}; - -defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({ - darwin: 'google chrome', - win32: 'chrome', - linux: ['google-chrome', 'google-chrome-stable'] -}, { - wsl: { - ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe', - x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'] - } -})); - -defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({ - darwin: 'firefox', - win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', - linux: 'firefox' -}, { - wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe' -})); - -defineLazyProperty(apps, 'edge', () => detectPlatformBinary({ - darwin: 'microsoft edge', - win32: 'msedge', - linux: 'microsoft-edge' -}, { - wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' -})); - -open.apps = apps; - -var open_1 = open; - -var execa$2 = {exports: {}}; - -var crossSpawn$1 = {exports: {}}; - -var windows$1 = isexe$3; -isexe$3.sync = sync$2; - -var fs$4 = fs__default; - -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT; - - if (!pathext) { - return true - } - - pathext = pathext.split(';'); - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase(); - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false -} - -function checkStat$1 (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) -} - -function isexe$3 (path, options, cb) { - fs$4.stat(path, function (er, stat) { - cb(er, er ? false : checkStat$1(stat, path, options)); - }); -} - -function sync$2 (path, options) { - return checkStat$1(fs$4.statSync(path), path, options) -} - -var mode = isexe$2; -isexe$2.sync = sync$1; - -var fs$3 = fs__default; - -function isexe$2 (path, options, cb) { - fs$3.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)); - }); -} - -function sync$1 (path, options) { - return checkStat(fs$3.statSync(path), options) -} - -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) -} - -function checkMode (stat, options) { - var mod = stat.mode; - var uid = stat.uid; - var gid = stat.gid; - - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid(); - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid(); - - var u = parseInt('100', 8); - var g = parseInt('010', 8); - var o = parseInt('001', 8); - var ug = u | g; - - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0; - - return ret -} - -var core$1; -if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { - core$1 = windows$1; -} else { - core$1 = mode; -} - -var isexe_1 = isexe$1; -isexe$1.sync = sync; - -function isexe$1 (path, options, cb) { - if (typeof options === 'function') { - cb = options; - options = {}; - } - - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') - } - - return new Promise(function (resolve, reject) { - isexe$1(path, options || {}, function (er, is) { - if (er) { - reject(er); - } else { - resolve(is); - } - }); - }) - } - - core$1(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null; - is = false; - } - } - cb(er, is); - }); -} - -function sync (path, options) { - // my kingdom for a filtered catch - try { - return core$1.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false - } else { - throw er - } - } -} - -const isWindows = process.platform === 'win32' || - process.env.OSTYPE === 'cygwin' || - process.env.OSTYPE === 'msys'; - -const path$8 = path__default; -const COLON = isWindows ? ';' : ':'; -const isexe = isexe_1; - -const getNotFoundError = (cmd) => - Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); - -const getPathInfo = (cmd, opt) => { - const colon = opt.colon || COLON; - - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] - : ( - [ - // windows always checks the cwd first - ...(isWindows ? [process.cwd()] : []), - ...(opt.path || process.env.PATH || - /* istanbul ignore next: very unusual */ '').split(colon), - ] - ); - const pathExtExe = isWindows - ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' - : ''; - const pathExt = isWindows ? pathExtExe.split(colon) : ['']; - - if (isWindows) { - if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') - pathExt.unshift(''); - } - - return { - pathEnv, - pathExt, - pathExtExe, - } -}; - -const which$1 = (cmd, opt, cb) => { - if (typeof opt === 'function') { - cb = opt; - opt = {}; - } - if (!opt) - opt = {}; - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); - const found = []; - - const step = i => new Promise((resolve, reject) => { - if (i === pathEnv.length) - return opt.all && found.length ? resolve(found) - : reject(getNotFoundError(cmd)) - - const ppRaw = pathEnv[i]; - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; - - const pCmd = path$8.join(pathPart, cmd); - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd; - - resolve(subStep(p, i, 0)); - }); - - const subStep = (p, i, ii) => new Promise((resolve, reject) => { - if (ii === pathExt.length) - return resolve(step(i + 1)) - const ext = pathExt[ii]; - isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { - if (!er && is) { - if (opt.all) - found.push(p + ext); - else - return resolve(p + ext) - } - return resolve(subStep(p, i, ii + 1)) - }); - }); - - return cb ? step(0).then(res => cb(null, res), cb) : step(0) -}; - -const whichSync = (cmd, opt) => { - opt = opt || {}; - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); - const found = []; - - for (let i = 0; i < pathEnv.length; i ++) { - const ppRaw = pathEnv[i]; - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; - - const pCmd = path$8.join(pathPart, cmd); - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd; - - for (let j = 0; j < pathExt.length; j ++) { - const cur = p + pathExt[j]; - try { - const is = isexe.sync(cur, { pathExt: pathExtExe }); - if (is) { - if (opt.all) - found.push(cur); - else - return cur - } - } catch (ex) {} - } - } - - if (opt.all && found.length) - return found - - if (opt.nothrow) - return null - - throw getNotFoundError(cmd) -}; - -var which_1 = which$1; -which$1.sync = whichSync; - -var pathKey$1 = {exports: {}}; - -const pathKey = (options = {}) => { - const environment = options.env || process.env; - const platform = options.platform || process.platform; - - if (platform !== 'win32') { - return 'PATH'; - } - - return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; -}; - -pathKey$1.exports = pathKey; -// TODO: Remove this for the next major release -pathKey$1.exports.default = pathKey; - -const path$7 = path__default; -const which = which_1; -const getPathKey = pathKey$1.exports; - -function resolveCommandAttempt(parsed, withoutPathExt) { - const env = parsed.options.env || process.env; - const cwd = process.cwd(); - const hasCustomCwd = parsed.options.cwd != null; - // Worker threads do not have process.chdir() - const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; - - // If a custom `cwd` was specified, we need to change the process cwd - // because `which` will do stat calls but does not support a custom cwd - if (shouldSwitchCwd) { - try { - process.chdir(parsed.options.cwd); - } catch (err) { - /* Empty */ - } - } - - let resolved; - - try { - resolved = which.sync(parsed.command, { - path: env[getPathKey({ env })], - pathExt: withoutPathExt ? path$7.delimiter : undefined, - }); - } catch (e) { - /* Empty */ - } finally { - if (shouldSwitchCwd) { - process.chdir(cwd); - } - } - - // If we successfully resolved, ensure that an absolute path is returned - // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it - if (resolved) { - resolved = path$7.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); - } - - return resolved; -} - -function resolveCommand$1(parsed) { - return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); -} - -var resolveCommand_1 = resolveCommand$1; - -var _escape = {}; - -// See http://www.robvanderwoude.com/escapechars.php -const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; - -function escapeCommand(arg) { - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - return arg; -} - -function escapeArgument(arg, doubleEscapeMetaChars) { - // Convert to string - arg = `${arg}`; - - // Algorithm below is based on https://qntm.org/cmd - - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); - - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); - - // All other backslashes occur literally - - // Quote the whole thing: - arg = `"${arg}"`; - - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - // Double escape meta chars if necessary - if (doubleEscapeMetaChars) { - arg = arg.replace(metaCharsRegExp, '^$1'); - } - - return arg; -} - -_escape.command = escapeCommand; -_escape.argument = escapeArgument; - -var shebangRegex$1 = /^#!(.*)/; - -const shebangRegex = shebangRegex$1; - -var shebangCommand$1 = (string = '') => { - const match = string.match(shebangRegex); - - if (!match) { - return null; - } - - const [path, argument] = match[0].replace(/#! ?/, '').split(' '); - const binary = path.split('/').pop(); - - if (binary === 'env') { - return argument; - } - - return argument ? `${binary} ${argument}` : binary; -}; - -const fs$2 = fs__default; -const shebangCommand = shebangCommand$1; - -function readShebang$1(command) { - // Read the first 150 bytes from the file - const size = 150; - const buffer = Buffer.alloc(size); - - let fd; - - try { - fd = fs$2.openSync(command, 'r'); - fs$2.readSync(fd, buffer, 0, size, 0); - fs$2.closeSync(fd); - } catch (e) { /* Empty */ } - - // Attempt to extract shebang (null is returned if not a shebang) - return shebangCommand(buffer.toString()); -} - -var readShebang_1 = readShebang$1; - -const path$6 = path__default; -const resolveCommand = resolveCommand_1; -const escape = _escape; -const readShebang = readShebang_1; - -const isWin$2 = process.platform === 'win32'; -const isExecutableRegExp = /\.(?:com|exe)$/i; -const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; - -function detectShebang(parsed) { - parsed.file = resolveCommand(parsed); - - const shebang = parsed.file && readShebang(parsed.file); - - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; - - return resolveCommand(parsed); - } - - return parsed.file; -} - -function parseNonShell(parsed) { - if (!isWin$2) { - return parsed; - } - - // Detect & add support for shebangs - const commandFile = detectShebang(parsed); - - // We don't need a shell if the command filename is an executable - const needsShell = !isExecutableRegExp.test(commandFile); - - // If a shell is required, use cmd.exe and take care of escaping everything correctly - // Note that `forceShell` is an hidden option used only in tests - if (parsed.options.forceShell || needsShell) { - // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` - // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument - // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, - // we need to double escape them - const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); - - // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) - // This is necessary otherwise it will always fail with ENOENT in those cases - parsed.command = path$6.normalize(parsed.command); - - // Escape command & arguments - parsed.command = escape.command(parsed.command); - parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); - - const shellCommand = [parsed.command].concat(parsed.args).join(' '); - - parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } - - return parsed; -} - -function parse$4(command, args, options) { - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; - } - - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = Object.assign({}, options); // Clone object to avoid changing the original - - // Build our parsed object - const parsed = { - command, - args, - options, - file: undefined, - original: { - command, - args, - }, - }; - - // Delegate further parsing to shell or non-shell - return options.shell ? parsed : parseNonShell(parsed); -} - -var parse_1 = parse$4; - -const isWin$1 = process.platform === 'win32'; - -function notFoundError(original, syscall) { - return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { - code: 'ENOENT', - errno: 'ENOENT', - syscall: `${syscall} ${original.command}`, - path: original.command, - spawnargs: original.args, - }); -} - -function hookChildProcess(cp, parsed) { - if (!isWin$1) { - return; - } - - const originalEmit = cp.emit; - - cp.emit = function (name, arg1) { - // If emitting "exit" event and exit code is 1, we need to check if - // the command exists and emit an "error" instead - // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 - if (name === 'exit') { - const err = verifyENOENT(arg1, parsed); - - if (err) { - return originalEmit.call(cp, 'error', err); - } - } - - return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params - }; -} - -function verifyENOENT(status, parsed) { - if (isWin$1 && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawn'); - } - - return null; -} - -function verifyENOENTSync(status, parsed) { - if (isWin$1 && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } - - return null; -} - -var enoent$1 = { - hookChildProcess, - verifyENOENT, - verifyENOENTSync, - notFoundError, -}; - -const cp = require$$1__default$4; -const parse$3 = parse_1; -const enoent = enoent$1; - -function spawn(command, args, options) { - // Parse the arguments - const parsed = parse$3(command, args, options); - - // Spawn the child process - const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); - - // Hook into child process "exit" event to emit an error if the command - // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - enoent.hookChildProcess(spawned, parsed); - - return spawned; -} - -function spawnSync(command, args, options) { - // Parse the arguments - const parsed = parse$3(command, args, options); - - // Spawn the child process - const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); - - // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); - - return result; -} - -crossSpawn$1.exports = spawn; -crossSpawn$1.exports.spawn = spawn; -crossSpawn$1.exports.sync = spawnSync; - -crossSpawn$1.exports._parse = parse$3; -crossSpawn$1.exports._enoent = enoent; - -var stripFinalNewline$1 = input => { - const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); - const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); - - if (input[input.length - 1] === LF) { - input = input.slice(0, input.length - 1); - } - - if (input[input.length - 1] === CR) { - input = input.slice(0, input.length - 1); - } - - return input; -}; - -var npmRunPath$1 = {exports: {}}; - -(function (module) { -const path = path__default; -const pathKey = pathKey$1.exports; - -const npmRunPath = options => { - options = { - cwd: process.cwd(), - path: process.env[pathKey()], - execPath: process.execPath, - ...options - }; - - let previous; - let cwdPath = path.resolve(options.cwd); - const result = []; - - while (previous !== cwdPath) { - result.push(path.join(cwdPath, 'node_modules/.bin')); - previous = cwdPath; - cwdPath = path.resolve(cwdPath, '..'); - } - - // Ensure the running `node` binary is used - const execPathDir = path.resolve(options.cwd, options.execPath, '..'); - result.push(execPathDir); - - return result.concat(options.path).join(path.delimiter); -}; - -module.exports = npmRunPath; -// TODO: Remove this for the next major release -module.exports.default = npmRunPath; - -module.exports.env = options => { - options = { - env: process.env, - ...options - }; - - const env = {...options.env}; - const path = pathKey({env}); - - options.path = env[path]; - env[path] = module.exports(options); - - return env; -}; -}(npmRunPath$1)); - -var onetime$2 = {exports: {}}; - -var mimicFn$2 = {exports: {}}; - -const mimicFn$1 = (to, from) => { - for (const prop of Reflect.ownKeys(from)) { - Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); - } - - return to; -}; - -mimicFn$2.exports = mimicFn$1; -// TODO: Remove this for the next major release -mimicFn$2.exports.default = mimicFn$1; - -const mimicFn = mimicFn$2.exports; - -const calledFunctions = new WeakMap(); - -const onetime$1 = (function_, options = {}) => { - if (typeof function_ !== 'function') { - throw new TypeError('Expected a function'); - } - - let returnValue; - let callCount = 0; - const functionName = function_.displayName || function_.name || ''; - - const onetime = function (...arguments_) { - calledFunctions.set(onetime, ++callCount); - - if (callCount === 1) { - returnValue = function_.apply(this, arguments_); - function_ = null; - } else if (options.throw === true) { - throw new Error(`Function \`${functionName}\` can only be called once`); - } - - return returnValue; - }; - - mimicFn(onetime, function_); - calledFunctions.set(onetime, callCount); - - return onetime; -}; - -onetime$2.exports = onetime$1; -// TODO: Remove this for the next major release -onetime$2.exports.default = onetime$1; - -onetime$2.exports.callCount = function_ => { - if (!calledFunctions.has(function_)) { - throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); - } - - return calledFunctions.get(function_); -}; - -var main$2 = {}; - -var signals$2 = {}; - -var core = {}; - -Object.defineProperty(core,"__esModule",{value:true});core.SIGNALS=void 0; - -const SIGNALS=[ -{ -name:"SIGHUP", -number:1, -action:"terminate", -description:"Terminal closed", -standard:"posix"}, - -{ -name:"SIGINT", -number:2, -action:"terminate", -description:"User interruption with CTRL-C", -standard:"ansi"}, - -{ -name:"SIGQUIT", -number:3, -action:"core", -description:"User interruption with CTRL-\\", -standard:"posix"}, - -{ -name:"SIGILL", -number:4, -action:"core", -description:"Invalid machine instruction", -standard:"ansi"}, - -{ -name:"SIGTRAP", -number:5, -action:"core", -description:"Debugger breakpoint", -standard:"posix"}, - -{ -name:"SIGABRT", -number:6, -action:"core", -description:"Aborted", -standard:"ansi"}, - -{ -name:"SIGIOT", -number:6, -action:"core", -description:"Aborted", -standard:"bsd"}, - -{ -name:"SIGBUS", -number:7, -action:"core", -description: -"Bus error due to misaligned, non-existing address or paging error", -standard:"bsd"}, - -{ -name:"SIGEMT", -number:7, -action:"terminate", -description:"Command should be emulated but is not implemented", -standard:"other"}, - -{ -name:"SIGFPE", -number:8, -action:"core", -description:"Floating point arithmetic error", -standard:"ansi"}, - -{ -name:"SIGKILL", -number:9, -action:"terminate", -description:"Forced termination", -standard:"posix", -forced:true}, - -{ -name:"SIGUSR1", -number:10, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, - -{ -name:"SIGSEGV", -number:11, -action:"core", -description:"Segmentation fault", -standard:"ansi"}, - -{ -name:"SIGUSR2", -number:12, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, - -{ -name:"SIGPIPE", -number:13, -action:"terminate", -description:"Broken pipe or socket", -standard:"posix"}, - -{ -name:"SIGALRM", -number:14, -action:"terminate", -description:"Timeout or timer", -standard:"posix"}, - -{ -name:"SIGTERM", -number:15, -action:"terminate", -description:"Termination", -standard:"ansi"}, - -{ -name:"SIGSTKFLT", -number:16, -action:"terminate", -description:"Stack is empty or overflowed", -standard:"other"}, - -{ -name:"SIGCHLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"posix"}, - -{ -name:"SIGCLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"other"}, - -{ -name:"SIGCONT", -number:18, -action:"unpause", -description:"Unpaused", -standard:"posix", -forced:true}, - -{ -name:"SIGSTOP", -number:19, -action:"pause", -description:"Paused", -standard:"posix", -forced:true}, - -{ -name:"SIGTSTP", -number:20, -action:"pause", -description:"Paused using CTRL-Z or \"suspend\"", -standard:"posix"}, - -{ -name:"SIGTTIN", -number:21, -action:"pause", -description:"Background process cannot read terminal input", -standard:"posix"}, - -{ -name:"SIGBREAK", -number:21, -action:"terminate", -description:"User interruption with CTRL-BREAK", -standard:"other"}, - -{ -name:"SIGTTOU", -number:22, -action:"pause", -description:"Background process cannot write to terminal output", -standard:"posix"}, - -{ -name:"SIGURG", -number:23, -action:"ignore", -description:"Socket received out-of-band data", -standard:"bsd"}, - -{ -name:"SIGXCPU", -number:24, -action:"core", -description:"Process timed out", -standard:"bsd"}, - -{ -name:"SIGXFSZ", -number:25, -action:"core", -description:"File too big", -standard:"bsd"}, - -{ -name:"SIGVTALRM", -number:26, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, - -{ -name:"SIGPROF", -number:27, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, - -{ -name:"SIGWINCH", -number:28, -action:"ignore", -description:"Terminal window size changed", -standard:"bsd"}, - -{ -name:"SIGIO", -number:29, -action:"terminate", -description:"I/O is available", -standard:"other"}, - -{ -name:"SIGPOLL", -number:29, -action:"terminate", -description:"Watched event", -standard:"other"}, - -{ -name:"SIGINFO", -number:29, -action:"ignore", -description:"Request for process information", -standard:"other"}, - -{ -name:"SIGPWR", -number:30, -action:"terminate", -description:"Device running out of power", -standard:"systemv"}, - -{ -name:"SIGSYS", -number:31, -action:"core", -description:"Invalid system call", -standard:"other"}, - -{ -name:"SIGUNUSED", -number:31, -action:"terminate", -description:"Invalid system call", -standard:"other"}];core.SIGNALS=SIGNALS; - -var realtime = {}; - -Object.defineProperty(realtime,"__esModule",{value:true});realtime.SIGRTMAX=realtime.getRealtimeSignals=void 0; -const getRealtimeSignals=function(){ -const length=SIGRTMAX-SIGRTMIN+1; -return Array.from({length},getRealtimeSignal); -};realtime.getRealtimeSignals=getRealtimeSignals; - -const getRealtimeSignal=function(value,index){ -return { -name:`SIGRT${index+1}`, -number:SIGRTMIN+index, -action:"terminate", -description:"Application-specific signal (realtime)", -standard:"posix"}; - -}; - -const SIGRTMIN=34; -const SIGRTMAX=64;realtime.SIGRTMAX=SIGRTMAX; - -Object.defineProperty(signals$2,"__esModule",{value:true});signals$2.getSignals=void 0;var _os$1=require$$0__default$1; - -var _core=core; -var _realtime$1=realtime; - - - -const getSignals=function(){ -const realtimeSignals=(0, _realtime$1.getRealtimeSignals)(); -const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); -return signals; -};signals$2.getSignals=getSignals; - - - - - - - -const normalizeSignal=function({ -name, -number:defaultNumber, -description, -action, -forced=false, -standard}) -{ -const{ -signals:{[name]:constantSignal}}= -_os$1.constants; -const supported=constantSignal!==undefined; -const number=supported?constantSignal:defaultNumber; -return {name,number,description,supported,action,forced,standard}; -}; - -Object.defineProperty(main$2,"__esModule",{value:true});main$2.signalsByNumber=main$2.signalsByName=void 0;var _os=require$$0__default$1; - -var _signals=signals$2; -var _realtime=realtime; - - - -const getSignalsByName=function(){ -const signals=(0, _signals.getSignals)(); -return signals.reduce(getSignalByName,{}); -}; - -const getSignalByName=function( -signalByNameMemo, -{name,number,description,supported,action,forced,standard}) -{ -return { -...signalByNameMemo, -[name]:{name,number,description,supported,action,forced,standard}}; - -}; - -const signalsByName$1=getSignalsByName();main$2.signalsByName=signalsByName$1; - - - - -const getSignalsByNumber=function(){ -const signals=(0, _signals.getSignals)(); -const length=_realtime.SIGRTMAX+1; -const signalsA=Array.from({length},(value,number)=> -getSignalByNumber(number,signals)); - -return Object.assign({},...signalsA); -}; - -const getSignalByNumber=function(number,signals){ -const signal=findSignalByNumber(number,signals); - -if(signal===undefined){ -return {}; -} - -const{name,description,supported,action,forced,standard}=signal; -return { -[number]:{ -name, -number, -description, -supported, -action, -forced, -standard}}; - - -}; - - - -const findSignalByNumber=function(number,signals){ -const signal=signals.find(({name})=>_os.constants.signals[name]===number); - -if(signal!==undefined){ -return signal; -} - -return signals.find(signalA=>signalA.number===number); -}; - -const signalsByNumber=getSignalsByNumber();main$2.signalsByNumber=signalsByNumber; - -const {signalsByName} = main$2; - -const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { - if (timedOut) { - return `timed out after ${timeout} milliseconds`; - } - - if (isCanceled) { - return 'was canceled'; - } - - if (errorCode !== undefined) { - return `failed with ${errorCode}`; - } - - if (signal !== undefined) { - return `was killed with ${signal} (${signalDescription})`; - } - - if (exitCode !== undefined) { - return `failed with exit code ${exitCode}`; - } - - return 'failed'; -}; - -const makeError$1 = ({ - stdout, - stderr, - all, - error, - signal, - exitCode, - command, - escapedCommand, - timedOut, - isCanceled, - killed, - parsed: {options: {timeout}} -}) => { - // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. - // We normalize them to `undefined` - exitCode = exitCode === null ? undefined : exitCode; - signal = signal === null ? undefined : signal; - const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; - - const errorCode = error && error.code; - - const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); - const execaMessage = `Command ${prefix}: ${command}`; - const isError = Object.prototype.toString.call(error) === '[object Error]'; - const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; - const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); - - if (isError) { - error.originalMessage = error.message; - error.message = message; - } else { - error = new Error(message); - } - - error.shortMessage = shortMessage; - error.command = command; - error.escapedCommand = escapedCommand; - error.exitCode = exitCode; - error.signal = signal; - error.signalDescription = signalDescription; - error.stdout = stdout; - error.stderr = stderr; - - if (all !== undefined) { - error.all = all; - } - - if ('bufferedData' in error) { - delete error.bufferedData; - } - - error.failed = true; - error.timedOut = Boolean(timedOut); - error.isCanceled = isCanceled; - error.killed = killed && !timedOut; - - return error; -}; - -var error = makeError$1; - -var stdio = {exports: {}}; - -const aliases = ['stdin', 'stdout', 'stderr']; - -const hasAlias = options => aliases.some(alias => options[alias] !== undefined); - -const normalizeStdio$1 = options => { - if (!options) { - return; - } - - const {stdio} = options; - - if (stdio === undefined) { - return aliases.map(alias => options[alias]); - } - - if (hasAlias(options)) { - throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); - } - - if (typeof stdio === 'string') { - return stdio; - } - - if (!Array.isArray(stdio)) { - throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); - } - - const length = Math.max(stdio.length, aliases.length); - return Array.from({length}, (value, index) => stdio[index]); -}; - -stdio.exports = normalizeStdio$1; - -// `ipc` is pushed unless it is already present -stdio.exports.node = options => { - const stdio = normalizeStdio$1(options); - - if (stdio === 'ipc') { - return 'ipc'; - } - - if (stdio === undefined || typeof stdio === 'string') { - return [stdio, stdio, stdio, 'ipc']; - } - - if (stdio.includes('ipc')) { - return stdio; - } - - return [...stdio, 'ipc']; -}; - -var signalExit = {exports: {}}; - -var signals$1 = {exports: {}}; - -(function (module) { -// This is not the set of all possible signals. -// -// It IS, however, the set of all signals that trigger -// an exit on either Linux or BSD systems. Linux is a -// superset of the signal names supported on BSD, and -// the unknown signals just fail to register, so we can -// catch that easily enough. -// -// Don't bother with SIGKILL. It's uncatchable, which -// means that we can't fire any callbacks anyway. -// -// If a user does happen to register a handler on a non- -// fatal signal like SIGWINCH or something, and then -// exit, it'll end up firing `process.emit('exit')`, so -// the handler will be fired anyway. -// -// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised -// artificially, inherently leave the process in a -// state from which it is not safe to try and enter JS -// listeners. -module.exports = [ - 'SIGABRT', - 'SIGALRM', - 'SIGHUP', - 'SIGINT', - 'SIGTERM' -]; - -if (process.platform !== 'win32') { - module.exports.push( - 'SIGVTALRM', - 'SIGXCPU', - 'SIGXFSZ', - 'SIGUSR2', - 'SIGTRAP', - 'SIGSYS', - 'SIGQUIT', - 'SIGIOT' - // should detect profiler and enable/disable accordingly. - // see #21 - // 'SIGPROF' - ); -} - -if (process.platform === 'linux') { - module.exports.push( - 'SIGIO', - 'SIGPOLL', - 'SIGPWR', - 'SIGSTKFLT', - 'SIGUNUSED' - ); -} -}(signals$1)); - -// Note: since nyc uses this module to output coverage, any lines -// that are in the direct sync flow of nyc's outputCoverage are -// ignored, since we can never get coverage for them. -// grab a reference to node's real process object right away -var process$1 = commonjsGlobal.process; -// some kind of non-node environment, just no-op -if (typeof process$1 !== 'object' || !process$1) { - signalExit.exports = () => {}; -} else { - var assert = require$$5__default; - var signals = signals$1.exports; - var isWin = /^win/i.test(process$1.platform); - - var EE = require$$0__default$5; - /* istanbul ignore if */ - if (typeof EE !== 'function') { - EE = EE.EventEmitter; - } - - var emitter; - if (process$1.__signal_exit_emitter__) { - emitter = process$1.__signal_exit_emitter__; - } else { - emitter = process$1.__signal_exit_emitter__ = new EE(); - emitter.count = 0; - emitter.emitted = {}; - } - - // Because this emitter is a global, we have to check to see if a - // previous version of this library failed to enable infinite listeners. - // I know what you're about to say. But literally everything about - // signal-exit is a compromise with evil. Get used to it. - if (!emitter.infinite) { - emitter.setMaxListeners(Infinity); - emitter.infinite = true; - } - - signalExit.exports = function (cb, opts) { - if (commonjsGlobal.process !== process$1) { - return - } - assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler'); - - if (loaded === false) { - load(); - } - - var ev = 'exit'; - if (opts && opts.alwaysLast) { - ev = 'afterexit'; - } - - var remove = function () { - emitter.removeListener(ev, cb); - if (emitter.listeners('exit').length === 0 && - emitter.listeners('afterexit').length === 0) { - unload(); - } - }; - emitter.on(ev, cb); - - return remove - }; - - var unload = function unload () { - if (!loaded || commonjsGlobal.process !== process$1) { - return - } - loaded = false; - - signals.forEach(function (sig) { - try { - process$1.removeListener(sig, sigListeners[sig]); - } catch (er) {} - }); - process$1.emit = originalProcessEmit; - process$1.reallyExit = originalProcessReallyExit; - emitter.count -= 1; - }; - signalExit.exports.unload = unload; - - var emit = function emit (event, code, signal) { - if (emitter.emitted[event]) { - return - } - emitter.emitted[event] = true; - emitter.emit(event, code, signal); - }; - - // { : , ... } - var sigListeners = {}; - signals.forEach(function (sig) { - sigListeners[sig] = function listener () { - if (process$1 !== commonjsGlobal.process) { - return - } - // If there are no other listeners, an exit is coming! - // Simplest way: remove us and then re-send the signal. - // We know that this will kill the process, so we can - // safely emit now. - var listeners = process$1.listeners(sig); - if (listeners.length === emitter.count) { - unload(); - emit('exit', null, sig); - /* istanbul ignore next */ - emit('afterexit', null, sig); - /* istanbul ignore next */ - if (isWin && sig === 'SIGHUP') { - // "SIGHUP" throws an `ENOSYS` error on Windows, - // so use a supported signal instead - sig = 'SIGINT'; - } - process$1.kill(process$1.pid, sig); - } - }; - }); - - signalExit.exports.signals = function () { - return signals - }; - - var loaded = false; - - var load = function load () { - if (loaded || process$1 !== commonjsGlobal.process) { - return - } - loaded = true; - - // This is the number of onSignalExit's that are in play. - // It's important so that we can count the correct number of - // listeners on signals, and don't wait for the other one to - // handle it instead of us. - emitter.count += 1; - - signals = signals.filter(function (sig) { - try { - process$1.on(sig, sigListeners[sig]); - return true - } catch (er) { - return false - } - }); - - process$1.emit = processEmit; - process$1.reallyExit = processReallyExit; - }; - signalExit.exports.load = load; - - var originalProcessReallyExit = process$1.reallyExit; - var processReallyExit = function processReallyExit (code) { - if (process$1 !== commonjsGlobal.process) { - return - } - process$1.exitCode = code || 0; - emit('exit', process$1.exitCode, null); - /* istanbul ignore next */ - emit('afterexit', process$1.exitCode, null); - /* istanbul ignore next */ - originalProcessReallyExit.call(process$1, process$1.exitCode); - }; - - var originalProcessEmit = process$1.emit; - var processEmit = function processEmit (ev, arg) { - if (ev === 'exit' && process$1 === commonjsGlobal.process) { - if (arg !== undefined) { - process$1.exitCode = arg; - } - var ret = originalProcessEmit.apply(this, arguments); - emit('exit', process$1.exitCode, null); - /* istanbul ignore next */ - emit('afterexit', process$1.exitCode, null); - return ret - } else { - return originalProcessEmit.apply(this, arguments) - } - }; -} - -const os$3 = require$$0__default$1; -const onExit = signalExit.exports; - -const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; - -// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior -const spawnedKill$1 = (kill, signal = 'SIGTERM', options = {}) => { - const killResult = kill(signal); - setKillTimeout(kill, signal, options, killResult); - return killResult; -}; - -const setKillTimeout = (kill, signal, options, killResult) => { - if (!shouldForceKill(signal, options, killResult)) { - return; - } - - const timeout = getForceKillAfterTimeout(options); - const t = setTimeout(() => { - kill('SIGKILL'); - }, timeout); - - // Guarded because there's no `.unref()` when `execa` is used in the renderer - // process in Electron. This cannot be tested since we don't run tests in - // Electron. - // istanbul ignore else - if (t.unref) { - t.unref(); - } -}; - -const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => { - return isSigterm(signal) && forceKillAfterTimeout !== false && killResult; -}; - -const isSigterm = signal => { - return signal === os$3.constants.signals.SIGTERM || - (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); -}; - -const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { - if (forceKillAfterTimeout === true) { - return DEFAULT_FORCE_KILL_TIMEOUT; - } - - if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { - throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); - } - - return forceKillAfterTimeout; -}; - -// `childProcess.cancel()` -const spawnedCancel$1 = (spawned, context) => { - const killResult = spawned.kill(); - - if (killResult) { - context.isCanceled = true; - } -}; - -const timeoutKill = (spawned, signal, reject) => { - spawned.kill(signal); - reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); -}; - -// `timeout` option handling -const setupTimeout$1 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { - if (timeout === 0 || timeout === undefined) { - return spawnedPromise; - } - - let timeoutId; - const timeoutPromise = new Promise((resolve, reject) => { - timeoutId = setTimeout(() => { - timeoutKill(spawned, killSignal, reject); - }, timeout); - }); - - const safeSpawnedPromise = spawnedPromise.finally(() => { - clearTimeout(timeoutId); - }); - - return Promise.race([timeoutPromise, safeSpawnedPromise]); -}; - -const validateTimeout$1 = ({timeout}) => { - if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { - throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); - } -}; - -// `cleanup` option handling -const setExitHandler$1 = async (spawned, {cleanup, detached}, timedPromise) => { - if (!cleanup || detached) { - return timedPromise; - } - - const removeExitHandler = onExit(() => { - spawned.kill(); - }); - - return timedPromise.finally(() => { - removeExitHandler(); - }); -}; - -var kill = { - spawnedKill: spawnedKill$1, - spawnedCancel: spawnedCancel$1, - setupTimeout: setupTimeout$1, - validateTimeout: validateTimeout$1, - setExitHandler: setExitHandler$1 -}; - -const isStream$1 = stream => - stream !== null && - typeof stream === 'object' && - typeof stream.pipe === 'function'; - -isStream$1.writable = stream => - isStream$1(stream) && - stream.writable !== false && - typeof stream._write === 'function' && - typeof stream._writableState === 'object'; - -isStream$1.readable = stream => - isStream$1(stream) && - stream.readable !== false && - typeof stream._read === 'function' && - typeof stream._readableState === 'object'; - -isStream$1.duplex = stream => - isStream$1.writable(stream) && - isStream$1.readable(stream); - -isStream$1.transform = stream => - isStream$1.duplex(stream) && - typeof stream._transform === 'function'; - -var isStream_1 = isStream$1; - -var getStream$2 = {exports: {}}; - -const {PassThrough: PassThroughStream} = require$$0__default$4; - -var bufferStream$1 = options => { - options = {...options}; - - const {array} = options; - let {encoding} = options; - const isBuffer = encoding === 'buffer'; - let objectMode = false; - - if (array) { - objectMode = !(encoding || isBuffer); - } else { - encoding = encoding || 'utf8'; - } - - if (isBuffer) { - encoding = null; - } - - const stream = new PassThroughStream({objectMode}); - - if (encoding) { - stream.setEncoding(encoding); - } - - let length = 0; - const chunks = []; - - stream.on('data', chunk => { - chunks.push(chunk); - - if (objectMode) { - length = chunks.length; - } else { - length += chunk.length; - } - }); - - stream.getBufferedValue = () => { - if (array) { - return chunks; - } - - return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); - }; - - stream.getBufferedLength = () => length; - - return stream; -}; - -const {constants: BufferConstants} = require$$0__default$8; -const stream$1 = require$$0__default$4; -const {promisify} = require$$0__default$2; -const bufferStream = bufferStream$1; - -const streamPipelinePromisified = promisify(stream$1.pipeline); - -class MaxBufferError extends Error { - constructor() { - super('maxBuffer exceeded'); - this.name = 'MaxBufferError'; - } -} - -async function getStream$1(inputStream, options) { - if (!inputStream) { - throw new Error('Expected a stream'); - } - - options = { - maxBuffer: Infinity, - ...options - }; - - const {maxBuffer} = options; - const stream = bufferStream(options); - - await new Promise((resolve, reject) => { - const rejectPromise = error => { - // Don't retrieve an oversized buffer. - if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { - error.bufferedData = stream.getBufferedValue(); - } - - reject(error); - }; - - (async () => { - try { - await streamPipelinePromisified(inputStream, stream); - resolve(); - } catch (error) { - rejectPromise(error); - } - })(); - - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - rejectPromise(new MaxBufferError()); - } - }); - }); - - return stream.getBufferedValue(); -} - -getStream$2.exports = getStream$1; -getStream$2.exports.buffer = (stream, options) => getStream$1(stream, {...options, encoding: 'buffer'}); -getStream$2.exports.array = (stream, options) => getStream$1(stream, {...options, array: true}); -getStream$2.exports.MaxBufferError = MaxBufferError; - -const { PassThrough } = require$$0__default$4; - -var mergeStream$1 = function (/*streams...*/) { - var sources = []; - var output = new PassThrough({objectMode: true}); - - output.setMaxListeners(0); - - output.add = add; - output.isEmpty = isEmpty; - - output.on('unpipe', remove); - - Array.prototype.slice.call(arguments).forEach(add); - - return output - - function add (source) { - if (Array.isArray(source)) { - source.forEach(add); - return this - } - - sources.push(source); - source.once('end', remove.bind(null, source)); - source.once('error', output.emit.bind(output, 'error')); - source.pipe(output, {end: false}); - return this - } - - function isEmpty () { - return sources.length == 0; - } - - function remove (source) { - sources = sources.filter(function (it) { return it !== source }); - if (!sources.length && output.readable) { output.end(); } - } -}; - -const isStream = isStream_1; -const getStream = getStream$2.exports; -const mergeStream = mergeStream$1; - -// `input` option -const handleInput$1 = (spawned, input) => { - // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 - // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 - if (input === undefined || spawned.stdin === undefined) { - return; - } - - if (isStream(input)) { - input.pipe(spawned.stdin); - } else { - spawned.stdin.end(input); - } -}; - -// `all` interleaves `stdout` and `stderr` -const makeAllStream$1 = (spawned, {all}) => { - if (!all || (!spawned.stdout && !spawned.stderr)) { - return; - } - - const mixed = mergeStream(); - - if (spawned.stdout) { - mixed.add(spawned.stdout); - } - - if (spawned.stderr) { - mixed.add(spawned.stderr); - } - - return mixed; -}; - -// On failure, `result.stdout|stderr|all` should contain the currently buffered stream -const getBufferedData = async (stream, streamPromise) => { - if (!stream) { - return; - } - - stream.destroy(); - - try { - return await streamPromise; - } catch (error) { - return error.bufferedData; - } -}; - -const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { - if (!stream || !buffer) { - return; - } - - if (encoding) { - return getStream(stream, {encoding, maxBuffer}); - } - - return getStream.buffer(stream, {maxBuffer}); -}; - -// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) -const getSpawnedResult$1 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { - const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); - const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); - const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); - - try { - return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); - } catch (error) { - return Promise.all([ - {error, signal: error.signal, timedOut: error.timedOut}, - getBufferedData(stdout, stdoutPromise), - getBufferedData(stderr, stderrPromise), - getBufferedData(all, allPromise) - ]); - } -}; - -const validateInputSync$1 = ({input}) => { - if (isStream(input)) { - throw new TypeError('The `input` option cannot be a stream in sync mode'); - } -}; - -var stream = { - handleInput: handleInput$1, - makeAllStream: makeAllStream$1, - getSpawnedResult: getSpawnedResult$1, - validateInputSync: validateInputSync$1 -}; - -const nativePromisePrototype = (async () => {})().constructor.prototype; -const descriptors = ['then', 'catch', 'finally'].map(property => [ - property, - Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) -]); - -// The return value is a mixin of `childProcess` and `Promise` -const mergePromise$1 = (spawned, promise) => { - for (const [property, descriptor] of descriptors) { - // Starting the main `promise` is deferred to avoid consuming streams - const value = typeof promise === 'function' ? - (...args) => Reflect.apply(descriptor.value, promise(), args) : - descriptor.value.bind(promise); - - Reflect.defineProperty(spawned, property, {...descriptor, value}); - } - - return spawned; -}; - -// Use promises instead of `child_process` events -const getSpawnedPromise$1 = spawned => { - return new Promise((resolve, reject) => { - spawned.on('exit', (exitCode, signal) => { - resolve({exitCode, signal}); - }); - - spawned.on('error', error => { - reject(error); - }); - - if (spawned.stdin) { - spawned.stdin.on('error', error => { - reject(error); - }); - } - }); -}; - -var promise = { - mergePromise: mergePromise$1, - getSpawnedPromise: getSpawnedPromise$1 -}; - -const normalizeArgs = (file, args = []) => { - if (!Array.isArray(args)) { - return [file]; - } - - return [file, ...args]; -}; - -const NO_ESCAPE_REGEXP = /^[\w.-]+$/; -const DOUBLE_QUOTES_REGEXP = /"/g; - -const escapeArg = arg => { - if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { - return arg; - } - - return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`; -}; - -const joinCommand$1 = (file, args) => { - return normalizeArgs(file, args).join(' '); -}; - -const getEscapedCommand$1 = (file, args) => { - return normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' '); -}; - -const SPACES_REGEXP = / +/g; - -// Handle `execa.command()` -const parseCommand$1 = command => { - const tokens = []; - for (const token of command.trim().split(SPACES_REGEXP)) { - // Allow spaces to be escaped by a backslash if not meant as a delimiter - const previousToken = tokens[tokens.length - 1]; - if (previousToken && previousToken.endsWith('\\')) { - // Merge previous token with current one - tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; - } else { - tokens.push(token); - } - } - - return tokens; -}; - -var command = { - joinCommand: joinCommand$1, - getEscapedCommand: getEscapedCommand$1, - parseCommand: parseCommand$1 -}; - -const path$5 = path__default; -const childProcess$2 = require$$1__default$4; -const crossSpawn = crossSpawn$1.exports; -const stripFinalNewline = stripFinalNewline$1; -const npmRunPath = npmRunPath$1.exports; -const onetime = onetime$2.exports; -const makeError = error; -const normalizeStdio = stdio.exports; -const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = kill; -const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = stream; -const {mergePromise, getSpawnedPromise} = promise; -const {joinCommand, parseCommand, getEscapedCommand} = command; - -const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; - -const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { - const env = extendEnv ? {...process.env, ...envOption} : envOption; - - if (preferLocal) { - return npmRunPath.env({env, cwd: localDir, execPath}); - } - - return env; -}; - -const handleArguments = (file, args, options = {}) => { - const parsed = crossSpawn._parse(file, args, options); - file = parsed.command; - args = parsed.args; - options = parsed.options; - - options = { - maxBuffer: DEFAULT_MAX_BUFFER, - buffer: true, - stripFinalNewline: true, - extendEnv: true, - preferLocal: false, - localDir: options.cwd || process.cwd(), - execPath: process.execPath, - encoding: 'utf8', - reject: true, - cleanup: true, - all: false, - windowsHide: true, - ...options - }; - - options.env = getEnv(options); - - options.stdio = normalizeStdio(options); - - if (process.platform === 'win32' && path$5.basename(file, '.exe') === 'cmd') { - // #116 - args.unshift('/q'); - } - - return {file, args, options, parsed}; -}; - -const handleOutput = (options, value, error) => { - if (typeof value !== 'string' && !Buffer.isBuffer(value)) { - // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` - return error === undefined ? undefined : ''; - } - - if (options.stripFinalNewline) { - return stripFinalNewline(value); - } - - return value; -}; - -const execa = (file, args, options) => { - const parsed = handleArguments(file, args, options); - const command = joinCommand(file, args); - const escapedCommand = getEscapedCommand(file, args); - - validateTimeout(parsed.options); - - let spawned; - try { - spawned = childProcess$2.spawn(parsed.file, parsed.args, parsed.options); - } catch (error) { - // Ensure the returned error is always both a promise and a child process - const dummySpawned = new childProcess$2.ChildProcess(); - const errorPromise = Promise.reject(makeError({ - error, - stdout: '', - stderr: '', - all: '', - command, - escapedCommand, - parsed, - timedOut: false, - isCanceled: false, - killed: false - })); - return mergePromise(dummySpawned, errorPromise); - } - - const spawnedPromise = getSpawnedPromise(spawned); - const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); - const processDone = setExitHandler(spawned, parsed.options, timedPromise); - - const context = {isCanceled: false}; - - spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); - spawned.cancel = spawnedCancel.bind(null, spawned, context); - - const handlePromise = async () => { - const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); - const stdout = handleOutput(parsed.options, stdoutResult); - const stderr = handleOutput(parsed.options, stderrResult); - const all = handleOutput(parsed.options, allResult); - - if (error || exitCode !== 0 || signal !== null) { - const returnedError = makeError({ - error, - exitCode, - signal, - stdout, - stderr, - all, - command, - escapedCommand, - parsed, - timedOut, - isCanceled: context.isCanceled, - killed: spawned.killed - }); - - if (!parsed.options.reject) { - return returnedError; - } - - throw returnedError; - } - - return { - command, - escapedCommand, - exitCode: 0, - stdout, - stderr, - all, - failed: false, - timedOut: false, - isCanceled: false, - killed: false - }; - }; - - const handlePromiseOnce = onetime(handlePromise); - - handleInput(spawned, parsed.options.input); - - spawned.all = makeAllStream(spawned, parsed.options); - - return mergePromise(spawned, handlePromiseOnce); -}; - -execa$2.exports = execa; - -execa$2.exports.sync = (file, args, options) => { - const parsed = handleArguments(file, args, options); - const command = joinCommand(file, args); - const escapedCommand = getEscapedCommand(file, args); - - validateInputSync(parsed.options); - - let result; - try { - result = childProcess$2.spawnSync(parsed.file, parsed.args, parsed.options); - } catch (error) { - throw makeError({ - error, - stdout: '', - stderr: '', - all: '', - command, - escapedCommand, - parsed, - timedOut: false, - isCanceled: false, - killed: false - }); - } - - const stdout = handleOutput(parsed.options, result.stdout, result.error); - const stderr = handleOutput(parsed.options, result.stderr, result.error); - - if (result.error || result.status !== 0 || result.signal !== null) { - const error = makeError({ - stdout, - stderr, - error: result.error, - signal: result.signal, - exitCode: result.status, - command, - escapedCommand, - parsed, - timedOut: result.error && result.error.code === 'ETIMEDOUT', - isCanceled: false, - killed: result.signal !== null - }); - - if (!parsed.options.reject) { - return error; - } - - throw error; - } - - return { - command, - escapedCommand, - exitCode: 0, - stdout, - stderr, - failed: false, - timedOut: false, - isCanceled: false, - killed: false - }; -}; - -execa$2.exports.command = (command, options) => { - const [file, ...args] = parseCommand(command); - return execa(file, args, options); -}; - -execa$2.exports.commandSync = (command, options) => { - const [file, ...args] = parseCommand(command); - return execa.sync(file, args, options); -}; - -execa$2.exports.node = (scriptPath, args, options = {}) => { - if (args && !Array.isArray(args) && typeof args === 'object') { - options = args; - args = []; - } - - const stdio = normalizeStdio.node(options); - const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); - - const { - nodePath = process.execPath, - nodeOptions = defaultExecArgv - } = options; - - return execa( - nodePath, - [ - ...nodeOptions, - scriptPath, - ...(Array.isArray(args) ? args : []) - ], - { - ...options, - stdin: undefined, - stdout: undefined, - stderr: undefined, - stdio, - shell: false - } - ); -}; - -var execa$1 = execa$2.exports; - -/** - * The following is modified based on source found in - * https://github.com/facebook/create-react-app - * - * MIT Licensed - * Copyright (c) 2015-present, Facebook, Inc. - * https://github.com/facebook/create-react-app/blob/master/LICENSE - * - */ -// https://github.com/sindresorhus/open#app -const OSX_CHROME = 'google chrome'; -/** - * Reads the BROWSER environment variable and decides what to do with it. - * Returns true if it opened a browser or ran a node.js script, otherwise false. - */ -function openBrowser(url, opt, logger) { - // The browser executable to open. - // See https://github.com/sindresorhus/open#app for documentation. - const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''; - if (browser.toLowerCase().endsWith('.js')) { - return executeNodeScript(browser, url, logger); - } - else if (browser.toLowerCase() !== 'none') { - return startBrowserProcess(browser, url); - } - return false; -} -function executeNodeScript(scriptPath, url, logger) { - const extraArgs = process.argv.slice(2); - const child = execa$1('node', [scriptPath, ...extraArgs, url], { - stdio: 'inherit' - }); - child.on('close', (code) => { - if (code !== 0) { - logger.error(source.red(`\nThe script specified as BROWSER environment variable failed.\n\n${source.cyan(scriptPath)} exited with code ${code}.`), { error: null }); - } - }); - return true; -} -function startBrowserProcess(browser, url) { - // If we're on OS X, the user hasn't specifically - // requested a different browser, we can try opening - // Chrome with AppleScript. This lets us reuse an - // existing tab when possible instead of creating a new one. - const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME); - if (shouldTryOpenChromeWithAppleScript) { - try { - // Try our best to reuse existing tab - // on OS X Google Chrome with AppleScript - require$$1$4.execSync('ps cax | grep "Google Chrome"'); - require$$1$4.execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', { - cwd: path__default.dirname(require.resolve('vite/bin/openChrome.applescript')), - stdio: 'ignore' - }); - return true; - } - catch (err) { - // Ignore errors - } - } - // Another special case: on OS X, check if BROWSER has been set to "open". - // In this case, instead of passing the string `open` to `open` function (which won't work), - // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser): - // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768 - if (process.platform === 'darwin' && browser === 'open') { - browser = undefined; - } - // Fallback to open - // (It will always open new tab) - try { - const options = browser ? { app: { name: browser } } : {}; - open_1(url, options).catch(() => { }); // Prevent `unhandledRejection` error. - return true; - } - catch (err) { - return false; - } -} - -var chalk$1 = {exports: {}}; - -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - -var escapeStringRegexp = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - return str.replace(matchOperatorsRe, '\\$&'); -}; - -var ansiStyles = {exports: {}}; - -var conversions$2 = {exports: {}}; - -var colorName = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; - -/* MIT license */ - -var cssKeywords = colorName; - -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) - -var reverseKeywords = {}; -for (var key in cssKeywords) { - if (cssKeywords.hasOwnProperty(key)) { - reverseKeywords[cssKeywords[key]] = key; - } -} - -var convert$1 = conversions$2.exports = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} -}; - -// hide .channels and .labels properties -for (var model in convert$1) { - if (convert$1.hasOwnProperty(model)) { - if (!('channels' in convert$1[model])) { - throw new Error('missing channels property: ' + model); - } - - if (!('labels' in convert$1[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert$1[model].labels.length !== convert$1[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - var channels = convert$1[model].channels; - var labels = convert$1[model].labels; - delete convert$1[model].channels; - delete convert$1[model].labels; - Object.defineProperty(convert$1[model], 'channels', {value: channels}); - Object.defineProperty(convert$1[model], 'labels', {value: labels}); - } -} - -convert$1.rgb.hsl = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var min = Math.min(r, g, b); - var max = Math.max(r, g, b); - var delta = max - min; - var h; - var s; - var l; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - - return [h, s * 100, l * 100]; -}; - -convert$1.rgb.hsv = function (rgb) { - var rdif; - var gdif; - var bdif; - var h; - var s; - - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var v = Math.max(r, g, b); - var diff = v - Math.min(r, g, b); - var diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; - - if (diff === 0) { - h = s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - - return [ - h * 360, - s * 100, - v * 100 - ]; -}; - -convert$1.rgb.hwb = function (rgb) { - var r = rgb[0]; - var g = rgb[1]; - var b = rgb[2]; - var h = convert$1.rgb.hsl(rgb)[0]; - var w = 1 / 255 * Math.min(r, Math.min(g, b)); - - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - - return [h, w * 100, b * 100]; -}; - -convert$1.rgb.cmyk = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var c; - var m; - var y; - var k; - - k = Math.min(1 - r, 1 - g, 1 - b); - c = (1 - r - k) / (1 - k) || 0; - m = (1 - g - k) / (1 - k) || 0; - y = (1 - b - k) / (1 - k) || 0; - - return [c * 100, m * 100, y * 100, k * 100]; -}; - -/** - * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - * */ -function comparativeDistance(x, y) { - return ( - Math.pow(x[0] - y[0], 2) + - Math.pow(x[1] - y[1], 2) + - Math.pow(x[2] - y[2], 2) - ); -} - -convert$1.rgb.keyword = function (rgb) { - var reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } - - var currentClosestDistance = Infinity; - var currentClosestKeyword; - - for (var keyword in cssKeywords) { - if (cssKeywords.hasOwnProperty(keyword)) { - var value = cssKeywords[keyword]; - - // Compute comparative distance - var distance = comparativeDistance(rgb, value); - - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - } - - return currentClosestKeyword; -}; - -convert$1.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; -}; - -convert$1.rgb.xyz = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - - // assume sRGB - r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); - g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); - b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); - - var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); - - return [x * 100, y * 100, z * 100]; -}; - -convert$1.rgb.lab = function (rgb) { - var xyz = convert$1.rgb.xyz(rgb); - var x = xyz[0]; - var y = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); - - l = (116 * y) - 16; - a = 500 * (x - y); - b = 200 * (y - z); - - return [l, a, b]; -}; - -convert$1.hsl.rgb = function (hsl) { - var h = hsl[0] / 360; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var t1; - var t2; - var t3; - var rgb; - var val; - - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - - t1 = 2 * l - t2; - - rgb = [0, 0, 0]; - for (var i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - if (t3 > 1) { - t3--; - } - - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } - - rgb[i] = val * 255; - } - - return rgb; -}; - -convert$1.hsl.hsv = function (hsl) { - var h = hsl[0]; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var smin = s; - var lmin = Math.max(l, 0.01); - var sv; - var v; - - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - v = (l + s) / 2; - sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); - - return [h, sv * 100, v * 100]; -}; - -convert$1.hsv.rgb = function (hsv) { - var h = hsv[0] / 60; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var hi = Math.floor(h) % 6; - - var f = h - Math.floor(h); - var p = 255 * v * (1 - s); - var q = 255 * v * (1 - (s * f)); - var t = 255 * v * (1 - (s * (1 - f))); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } -}; - -convert$1.hsv.hsl = function (hsv) { - var h = hsv[0]; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var vmin = Math.max(v, 0.01); - var lmin; - var sl; - var l; - - l = (2 - s) * v; - lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - - return [h, sl * 100, l * 100]; -}; - -// http://dev.w3.org/csswg/css-color/#hwb-to-rgb -convert$1.hwb.rgb = function (hwb) { - var h = hwb[0] / 360; - var wh = hwb[1] / 100; - var bl = hwb[2] / 100; - var ratio = wh + bl; - var i; - var v; - var f; - var n; - - // wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - - i = Math.floor(6 * h); - v = 1 - bl; - f = 6 * h - i; - - if ((i & 0x01) !== 0) { - f = 1 - f; - } - - n = wh + f * (v - wh); // linear interpolation - - var r; - var g; - var b; - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } - - return [r * 255, g * 255, b * 255]; -}; - -convert$1.cmyk.rgb = function (cmyk) { - var c = cmyk[0] / 100; - var m = cmyk[1] / 100; - var y = cmyk[2] / 100; - var k = cmyk[3] / 100; - var r; - var g; - var b; - - r = 1 - Math.min(1, c * (1 - k) + k); - g = 1 - Math.min(1, m * (1 - k) + k); - b = 1 - Math.min(1, y * (1 - k) + k); - - return [r * 255, g * 255, b * 255]; -}; - -convert$1.xyz.rgb = function (xyz) { - var x = xyz[0] / 100; - var y = xyz[1] / 100; - var z = xyz[2] / 100; - var r; - var g; - var b; - - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); - - // assume sRGB - r = r > 0.0031308 - ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) - : r * 12.92; - - g = g > 0.0031308 - ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) - : g * 12.92; - - b = b > 0.0031308 - ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) - : b * 12.92; - - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); - - return [r * 255, g * 255, b * 255]; -}; - -convert$1.xyz.lab = function (xyz) { - var x = xyz[0]; - var y = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); - - l = (116 * y) - 16; - a = 500 * (x - y); - b = 200 * (y - z); - - return [l, a, b]; -}; - -convert$1.lab.xyz = function (lab) { - var l = lab[0]; - var a = lab[1]; - var b = lab[2]; - var x; - var y; - var z; - - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; - - var y2 = Math.pow(y, 3); - var x2 = Math.pow(x, 3); - var z2 = Math.pow(z, 3); - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; - - x *= 95.047; - y *= 100; - z *= 108.883; - - return [x, y, z]; -}; - -convert$1.lab.lch = function (lab) { - var l = lab[0]; - var a = lab[1]; - var b = lab[2]; - var hr; - var h; - var c; - - hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - - if (h < 0) { - h += 360; - } - - c = Math.sqrt(a * a + b * b); - - return [l, c, h]; -}; - -convert$1.lch.lab = function (lch) { - var l = lch[0]; - var c = lch[1]; - var h = lch[2]; - var a; - var b; - var hr; - - hr = h / 360 * 2 * Math.PI; - a = c * Math.cos(hr); - b = c * Math.sin(hr); - - return [l, a, b]; -}; - -convert$1.rgb.ansi16 = function (args) { - var r = args[0]; - var g = args[1]; - var b = args[2]; - var value = 1 in arguments ? arguments[1] : convert$1.rgb.hsv(args)[2]; // hsv -> ansi16 optimization - - value = Math.round(value / 50); - - if (value === 0) { - return 30; - } - - var ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); - - if (value === 2) { - ansi += 60; - } - - return ansi; -}; - -convert$1.hsv.ansi16 = function (args) { - // optimization here; we already know the value and don't need to get - // it converted for us. - return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]); -}; - -convert$1.rgb.ansi256 = function (args) { - var r = args[0]; - var g = args[1]; - var b = args[2]; - - // we use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } - - if (r > 248) { - return 231; - } - - return Math.round(((r - 8) / 247) * 24) + 232; - } - - var ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); - - return ansi; -}; - -convert$1.ansi16.rgb = function (args) { - var color = args % 10; - - // handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - - color = color / 10.5 * 255; - - return [color, color, color]; - } - - var mult = (~~(args > 50) + 1) * 0.5; - var r = ((color & 1) * mult) * 255; - var g = (((color >> 1) & 1) * mult) * 255; - var b = (((color >> 2) & 1) * mult) * 255; - - return [r, g, b]; -}; - -convert$1.ansi256.rgb = function (args) { - // handle greyscale - if (args >= 232) { - var c = (args - 232) * 10 + 8; - return [c, c, c]; - } - - args -= 16; - - var rem; - var r = Math.floor(args / 36) / 5 * 255; - var g = Math.floor((rem = args % 36) / 6) / 5 * 255; - var b = (rem % 6) / 5 * 255; - - return [r, g, b]; -}; - -convert$1.rgb.hex = function (args) { - var integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); - - var string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert$1.hex.rgb = function (args) { - var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } - - var colorString = match[0]; - - if (match[0].length === 3) { - colorString = colorString.split('').map(function (char) { - return char + char; - }).join(''); - } - - var integer = parseInt(colorString, 16); - var r = (integer >> 16) & 0xFF; - var g = (integer >> 8) & 0xFF; - var b = integer & 0xFF; - - return [r, g, b]; -}; - -convert$1.rgb.hcg = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var max = Math.max(Math.max(r, g), b); - var min = Math.min(Math.min(r, g), b); - var chroma = (max - min); - var grayscale; - var hue; - - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } - - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma + 4; - } - - hue /= 6; - hue %= 1; - - return [hue * 360, chroma * 100, grayscale * 100]; -}; - -convert$1.hsl.hcg = function (hsl) { - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var c = 1; - var f = 0; - - if (l < 0.5) { - c = 2.0 * s * l; - } else { - c = 2.0 * s * (1.0 - l); - } - - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } - - return [hsl[0], c * 100, f * 100]; -}; - -convert$1.hsv.hcg = function (hsv) { - var s = hsv[1] / 100; - var v = hsv[2] / 100; - - var c = s * v; - var f = 0; - - if (c < 1.0) { - f = (v - c) / (1 - c); - } - - return [hsv[0], c * 100, f * 100]; -}; - -convert$1.hcg.rgb = function (hcg) { - var h = hcg[0] / 360; - var c = hcg[1] / 100; - var g = hcg[2] / 100; - - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } - - var pure = [0, 0, 0]; - var hi = (h % 1) * 6; - var v = hi % 1; - var w = 1 - v; - var mg = 0; - - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } - - mg = (1.0 - c) * g; - - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; - -convert$1.hcg.hsv = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - - var v = c + g * (1.0 - c); - var f = 0; - - if (v > 0.0) { - f = c / v; - } - - return [hcg[0], f * 100, v * 100]; -}; - -convert$1.hcg.hsl = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - - var l = g * (1.0 - c) + 0.5 * c; - var s = 0; - - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } - - return [hcg[0], s * 100, l * 100]; -}; - -convert$1.hcg.hwb = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - var v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; -}; - -convert$1.hwb.hcg = function (hwb) { - var w = hwb[1] / 100; - var b = hwb[2] / 100; - var v = 1 - b; - var c = v - w; - var g = 0; - - if (c < 1) { - g = (v - c) / (1 - c); - } - - return [hwb[0], c * 100, g * 100]; -}; - -convert$1.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; -}; - -convert$1.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; -}; - -convert$1.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; - -convert$1.gray.hsl = convert$1.gray.hsv = function (args) { - return [0, 0, args[0]]; -}; - -convert$1.gray.hwb = function (gray) { - return [0, 100, gray[0]]; -}; - -convert$1.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; -}; - -convert$1.gray.lab = function (gray) { - return [gray[0], 0, 0]; -}; - -convert$1.gray.hex = function (gray) { - var val = Math.round(gray[0] / 100 * 255) & 0xFF; - var integer = (val << 16) + (val << 8) + val; - - var string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert$1.rgb.gray = function (rgb) { - var val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; -}; - -var conversions$1 = conversions$2.exports; - -/* - this function routes a model to all other models. - - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). - - conversions that are not possible simply are not included. -*/ - -function buildGraph() { - var graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - var models = Object.keys(conversions$1); - - for (var len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - - return graph; -} - -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS(fromModel) { - var graph = buildGraph(); - var queue = [fromModel]; // unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - var current = queue.pop(); - var adjacents = Object.keys(conversions$1[current]); - - for (var len = adjacents.length, i = 0; i < len; i++) { - var adjacent = adjacents[i]; - var node = graph[adjacent]; - - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } - - return graph; -} - -function link(from, to) { - return function (args) { - return to(from(args)); - }; -} - -function wrapConversion(toModel, graph) { - var path = [graph[toModel].parent, toModel]; - var fn = conversions$1[graph[toModel].parent][toModel]; - - var cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions$1[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; -} - -var route$1 = function (fromModel) { - var graph = deriveBFS(fromModel); - var conversion = {}; - - var models = Object.keys(graph); - for (var len = models.length, i = 0; i < len; i++) { - var toModel = models[i]; - var node = graph[toModel]; - - if (node.parent === null) { - // no possible conversion, or this node is the source model. - continue; - } - - conversion[toModel] = wrapConversion(toModel, graph); - } - - return conversion; -}; - -var conversions = conversions$2.exports; -var route = route$1; - -var convert = {}; - -var models = Object.keys(conversions); - -function wrapRaw(fn) { - var wrappedFn = function (args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } - - return fn(args); - }; - - // preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -function wrapRounded(fn) { - var wrappedFn = function (args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } - - var result = fn(args); - - // we're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (var len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - - return result; - }; - - // preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -models.forEach(function (fromModel) { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - var routes = route(fromModel); - var routeModels = Object.keys(routes); - - routeModels.forEach(function (toModel) { - var fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); - -var colorConvert = convert; - -(function (module) { -const colorConvert$1 = colorConvert; - -const wrapAnsi16 = (fn, offset) => function () { - const code = fn.apply(colorConvert$1, arguments); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => function () { - const code = fn.apply(colorConvert$1, arguments); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => function () { - const rgb = fn.apply(colorConvert$1, arguments); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Fix humans - styles.color.grey = styles.color.gray; - - for (const groupName of Object.keys(styles)) { - const group = styles[groupName]; - - for (const styleName of Object.keys(group)) { - const style = group[styleName]; - - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - } - - const ansi2ansi = n => n; - const rgb2rgb = (r, g, b) => [r, g, b]; - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - styles.color.ansi = { - ansi: wrapAnsi16(ansi2ansi, 0) - }; - styles.color.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 0) - }; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; - - styles.bgColor.ansi = { - ansi: wrapAnsi16(ansi2ansi, 10) - }; - styles.bgColor.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 10) - }; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; - - for (let key of Object.keys(colorConvert$1)) { - if (typeof colorConvert$1[key] !== 'object') { - continue; - } - - const suite = colorConvert$1[key]; - - if (key === 'ansi16') { - key = 'ansi'; - } - - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } - - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } - - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); - } - } - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); -}(ansiStyles)); - -var hasFlag$1 = (flag, argv) => { - argv = argv || process.argv; - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const pos = argv.indexOf(prefix + flag); - const terminatorPos = argv.indexOf('--'); - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); -}; - -const os$2 = require$$0__default$1; -const hasFlag = hasFlag$1; - -const env = process.env; - -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; -} - -function translateLevel(level) { - if (level === 0) { - return false; - } - - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} - -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } - - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } - - const min = forceColor ? 1 : 0; - - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os$2.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - - if (env.COLORTERM === 'truecolor') { - return 3; - } - - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } - - if (env.TERM === 'dumb') { - return min; - } - - return min; -} - -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); -} - -var supportsColor_1 = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) -}; - -const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; - -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); - -function unescape$1(c) { - if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } - - return ESCAPES.get(c) || c; -} - -function parseArguments(name, args) { - const results = []; - const chunks = args.trim().split(/\s*,\s*/g); - let matches; - - for (const chunk of chunks) { - if (!isNaN(chunk)) { - results.push(Number(chunk)); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape$1(escape) : chr)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } - - return results; -} - -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; - - const results = []; - let matches; - - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; - - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } - - return results; -} - -function buildStyle(chalk, styles) { - const enabled = {}; - - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } - - let current = chalk; - for (const styleName of Object.keys(enabled)) { - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } - - if (enabled[styleName].length > 0) { - current = current[styleName].apply(current, enabled[styleName]); - } else { - current = current[styleName]; - } - } - } - - return current; -} - -var templates = (chalk, tmp) => { - const styles = []; - const chunks = []; - let chunk = []; - - // eslint-disable-next-line max-params - tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { - if (escapeChar) { - chunk.push(unescape$1(escapeChar)); - } else if (style) { - const str = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } - - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(chr); - } - }); - - chunks.push(chunk.join('')); - - if (styles.length > 0) { - const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMsg); - } - - return chunks.join(''); -}; - -(function (module) { -const escapeStringRegexp$1 = escapeStringRegexp; -const ansiStyles$1 = ansiStyles.exports; -const stdoutColor = supportsColor_1.stdout; - -const template = templates; - -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; - -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); - -const styles = Object.create(null); - -function applyOptions(obj, options) { - options = options || {}; - - // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} - -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = Chalk; - - return chalk.template; - } - - applyOptions(this, options); -} - -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles$1.blue.open = '\u001B[94m'; -} - -for (const key of Object.keys(ansiStyles$1)) { - ansiStyles$1[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1[key].close), 'g'); - - styles[key] = { - get() { - const codes = ansiStyles$1[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; -} - -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); - } -}; - -ansiStyles$1.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.color.close), 'g'); -for (const model of Object.keys(ansiStyles$1.color.ansi)) { - if (skipModels.has(model)) { - continue; - } - - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles$1.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles$1.color.close, - closeRe: ansiStyles$1.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -ansiStyles$1.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles$1.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; - } - - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles$1.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles$1.bgColor.close, - closeRe: ansiStyles$1.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -const proto = Object.defineProperties(() => {}, styles); - -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; - - builder._styles = _styles; - builder._empty = _empty; - - const self = this; - - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); - - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); - - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; - - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto - - return builder; -} - -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); - - if (argsLen === 0) { - return ''; - } - - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } - - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles$1.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles$1.dim.open = ''; - } - - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; - - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } - - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles$1.dim.open = originalDim; - - return str; -} - -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } - - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; - - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } - - return template(chalk, parts.join('')); -} - -Object.defineProperties(Chalk.prototype, styles); - -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = stdoutColor; -module.exports.default = module.exports; // For TypeScript -}(chalk$1)); - -var shellQuote$1 = {}; - -shellQuote$1.quote = function (xs) { - return xs.map(function (s) { - if (s && typeof s === 'object') { - return s.op.replace(/(.)/g, '\\$1'); - } - else if (/["\s]/.test(s) && !/'/.test(s)) { - return "'" + s.replace(/(['\\])/g, '\\$1') + "'"; - } - else if (/["'\s]/.test(s)) { - return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"'; - } - else { - return String(s).replace(/([A-z]:)?([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '$1\\$2'); - } - }).join(' '); -}; - -// '<(' is process substitution operator and -// can be parsed the same as control operator -var CONTROL = '(?:' + [ - '\\|\\|', '\\&\\&', ';;', '\\|\\&', '\\<\\(', '>>', '>\\&', '[&;()|<>]' -].join('|') + ')'; -var META = '|&;()<> \\t'; -var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+'; -var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"'; -var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\''; - -var TOKEN = ''; -for (var i = 0; i < 4; i++) { - TOKEN += (Math.pow(16,8)*Math.random()).toString(16); -} - -shellQuote$1.parse = function (s, env, opts) { - var mapped = parse$2(s, env, opts); - if (typeof env !== 'function') return mapped; - return mapped.reduce(function (acc, s) { - if (typeof s === 'object') return acc.concat(s); - var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g')); - if (xs.length === 1) return acc.concat(xs[0]); - return acc.concat(xs.filter(Boolean).map(function (x) { - if (RegExp('^' + TOKEN).test(x)) { - return JSON.parse(x.split(TOKEN)[1]); - } - else return x; - })); - }, []); -}; - -function parse$2 (s, env, opts) { - var chunker = new RegExp([ - '(' + CONTROL + ')', // control chars - '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*' - ].join('|'), 'g'); - var match = s.match(chunker).filter(Boolean); - var commented = false; - - if (!match) return []; - if (!env) env = {}; - if (!opts) opts = {}; - return match.map(function (s, j) { - if (commented) { - return; - } - if (RegExp('^' + CONTROL + '$').test(s)) { - return { op: s }; - } - - // Hand-written scanner/parser for Bash quoting rules: - // - // 1. inside single quotes, all characters are printed literally. - // 2. inside double quotes, all characters are printed literally - // except variables prefixed by '$' and backslashes followed by - // either a double quote or another backslash. - // 3. outside of any quotes, backslashes are treated as escape - // characters and not printed (unless they are themselves escaped) - // 4. quote context can switch mid-token if there is no whitespace - // between the two quote contexts (e.g. all'one'"token" parses as - // "allonetoken") - var SQ = "'"; - var DQ = '"'; - var DS = '$'; - var BS = opts.escape || '\\'; - var quote = false; - var esc = false; - var out = ''; - var isGlob = false; - - for (var i = 0, len = s.length; i < len; i++) { - var c = s.charAt(i); - isGlob = isGlob || (!quote && (c === '*' || c === '?')); - if (esc) { - out += c; - esc = false; - } - else if (quote) { - if (c === quote) { - quote = false; - } - else if (quote == SQ) { - out += c; - } - else { // Double quote - if (c === BS) { - i += 1; - c = s.charAt(i); - if (c === DQ || c === BS || c === DS) { - out += c; - } else { - out += BS + c; - } - } - else if (c === DS) { - out += parseEnvVar(); - } - else { - out += c; - } - } - } - else if (c === DQ || c === SQ) { - quote = c; - } - else if (RegExp('^' + CONTROL + '$').test(c)) { - return { op: s }; - } - else if (RegExp('^#$').test(c)) { - commented = true; - if (out.length){ - return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }]; - } - return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }]; - } - else if (c === BS) { - esc = true; - } - else if (c === DS) { - out += parseEnvVar(); - } - else out += c; - } - - if (isGlob) return {op: 'glob', pattern: out}; - - return out; - - function parseEnvVar() { - i += 1; - var varend, varname; - //debugger - if (s.charAt(i) === '{') { - i += 1; - if (s.charAt(i) === '}') { - throw new Error("Bad substitution: " + s.substr(i - 2, 3)); - } - varend = s.indexOf('}', i); - if (varend < 0) { - throw new Error("Bad substitution: " + s.substr(i)); - } - varname = s.substr(i, varend - i); - i = varend; - } - else if (/[*@#?$!_\-]/.test(s.charAt(i))) { - varname = s.charAt(i); - i += 1; - } - else { - varend = s.substr(i).match(/[^\w\d_]/); - if (!varend) { - varname = s.substr(i); - i = s.length; - } else { - varname = s.substr(i, varend.index); - i += varend.index - 1; - } - } - return getVar(null, '', varname); - } - }) - // finalize parsed aruments - .reduce(function(prev, arg){ - if (arg === undefined){ - return prev; - } - return prev.concat(arg); - },[]); - - function getVar (_, pre, key) { - var r = typeof env === 'function' ? env(key) : env[key]; - if (r === undefined && key != '') - r = ''; - else if (r === undefined) - r = '$'; - - if (typeof r === 'object') { - return pre + TOKEN + JSON.stringify(r) + TOKEN; - } - else return pre + r; - } -} - -var osx = { - '/Applications/Atom.app/Contents/MacOS/Atom': 'atom', - '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta': - '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta', - '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets', - '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text': - '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl', - '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2': - '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl', - '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text': - '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl', - '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code', - '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron': - 'code-insiders', - '/Applications/AppCode.app/Contents/MacOS/appcode': - '/Applications/AppCode.app/Contents/MacOS/appcode', - '/Applications/CLion.app/Contents/MacOS/clion': - '/Applications/CLion.app/Contents/MacOS/clion', - '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea': - '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea', - '/Applications/PhpStorm.app/Contents/MacOS/phpstorm': - '/Applications/PhpStorm.app/Contents/MacOS/phpstorm', - '/Applications/PyCharm.app/Contents/MacOS/pycharm': - '/Applications/PyCharm.app/Contents/MacOS/pycharm', - '/Applications/PyCharm CE.app/Contents/MacOS/pycharm': - '/Applications/PyCharm CE.app/Contents/MacOS/pycharm', - '/Applications/RubyMine.app/Contents/MacOS/rubymine': - '/Applications/RubyMine.app/Contents/MacOS/rubymine', - '/Applications/WebStorm.app/Contents/MacOS/webstorm': - '/Applications/WebStorm.app/Contents/MacOS/webstorm' -}; - -var linux = { - atom: 'atom', - Brackets: 'brackets', - code: 'code', - emacs: 'emacs', - 'idea.sh': 'idea', - 'phpstorm.sh': 'phpstorm', - 'pycharm.sh': 'pycharm', - 'rubymine.sh': 'rubymine', - sublime_text: 'subl', - vim: 'vim', - 'webstorm.sh': 'webstorm' -}; - -var windows = [ - 'Brackets.exe', - 'Code.exe', - 'atom.exe', - 'sublime_text.exe', - 'notepad++.exe', - 'clion.exe', - 'clion64.exe', - 'idea.exe', - 'idea64.exe', - 'phpstorm.exe', - 'phpstorm64.exe', - 'pycharm.exe', - 'pycharm64.exe', - 'rubymine.exe', - 'rubymine64.exe', - 'webstorm.exe', - 'webstorm64.exe' -]; - -const path$4 = path__default; -const shellQuote = shellQuote$1; -const childProcess$1 = require$$1__default$4; - -// Map from full process name to binary that starts the process -// We can't just re-use full process name, because it will spawn a new instance -// of the app every time -const COMMON_EDITORS_OSX = osx; -const COMMON_EDITORS_LINUX = linux; -const COMMON_EDITORS_WIN = windows; - -var guess = function guessEditor (specifiedEditor) { - if (specifiedEditor) { - return shellQuote.parse(specifiedEditor) - } - // We can find out which editor is currently running by: - // `ps x` on macOS and Linux - // `Get-Process` on Windows - try { - if (process.platform === 'darwin') { - const output = childProcess$1.execSync('ps x').toString(); - const processNames = Object.keys(COMMON_EDITORS_OSX); - for (let i = 0; i < processNames.length; i++) { - const processName = processNames[i]; - if (output.indexOf(processName) !== -1) { - return [COMMON_EDITORS_OSX[processName]] - } - } - } else if (process.platform === 'win32') { - const output = childProcess$1 - .execSync('powershell -Command "Get-Process | Select-Object Path"', { - stdio: ['pipe', 'pipe', 'ignore'] - }) - .toString(); - const runningProcesses = output.split('\r\n'); - for (let i = 0; i < runningProcesses.length; i++) { - // `Get-Process` sometimes returns empty lines - if (!runningProcesses[i]) { - continue - } - - const fullProcessPath = runningProcesses[i].trim(); - const shortProcessName = path$4.basename(fullProcessPath); - - if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) { - return [fullProcessPath] - } - } - } else if (process.platform === 'linux') { - // --no-heading No header line - // x List all processes owned by you - // -o comm Need only names column - const output = childProcess$1 - .execSync('ps x --no-heading -o comm --sort=comm') - .toString(); - const processNames = Object.keys(COMMON_EDITORS_LINUX); - for (let i = 0; i < processNames.length; i++) { - const processName = processNames[i]; - if (output.indexOf(processName) !== -1) { - return [COMMON_EDITORS_LINUX[processName]] - } - } - } - } catch (error) { - // Ignore... - } - - // Last resort, use old skool env vars - if (process.env.VISUAL) { - return [process.env.VISUAL] - } else if (process.env.EDITOR) { - return [process.env.EDITOR] - } - - return [null] -}; - -const path$3 = path__default; - -// normalize file/line numbers into command line args for specific editors -var getArgs = function getArgumentsForPosition ( - editor, - fileName, - lineNumber, - columnNumber = 1 -) { - const editorBasename = path$3.basename(editor).replace(/\.(exe|cmd|bat)$/i, ''); - switch (editorBasename) { - case 'atom': - case 'Atom': - case 'Atom Beta': - case 'subl': - case 'sublime': - case 'sublime_text': - case 'wstorm': - case 'charm': - return [`${fileName}:${lineNumber}:${columnNumber}`] - case 'notepad++': - return ['-n' + lineNumber, fileName] - case 'vim': - case 'mvim': - return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName] - case 'joe': - return ['+' + `${lineNumber}`, fileName] - case 'emacs': - case 'emacsclient': - return [`+${lineNumber}:${columnNumber}`, fileName] - case 'rmate': - case 'mate': - case 'mine': - return ['--line', lineNumber, fileName] - case 'code': - case 'code-insiders': - case 'Code': - return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`] - case 'appcode': - case 'clion': - case 'clion64': - case 'idea': - case 'idea64': - case 'phpstorm': - case 'phpstorm64': - case 'pycharm': - case 'pycharm64': - case 'rubymine': - case 'rubymine64': - case 'webstorm': - case 'webstorm64': - return ['--line', lineNumber, fileName] - } - - // For all others, drop the lineNumber until we have - // a mapping above, since providing the lineNumber incorrectly - // can result in errors or confusing behavior. - return [fileName] -}; - -/** - * Copyright (c) 2015-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file at - * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE - * - * Modified by Yuxi Evan You - */ - -const fs$1 = fs__default; -const os$1 = require$$0__default$1; -const path$2 = path__default; -const chalk = chalk$1.exports; -const childProcess = require$$1__default$4; - -const guessEditor = guess; -const getArgumentsForPosition = getArgs; - -function wrapErrorCallback (cb) { - return (fileName, errorMessage) => { - console.log(); - console.log( - chalk.red('Could not open ' + path$2.basename(fileName) + ' in the editor.') - ); - if (errorMessage) { - if (errorMessage[errorMessage.length - 1] !== '.') { - errorMessage += '.'; - } - console.log( - chalk.red('The editor process exited with an error: ' + errorMessage) - ); - } - console.log(); - if (cb) cb(fileName, errorMessage); - } -} - -function isTerminalEditor (editor) { - switch (editor) { - case 'vim': - case 'emacs': - case 'nano': - return true - } - return false -} - -const positionRE = /:(\d+)(:(\d+))?$/; -function parseFile (file) { - const fileName = file.replace(positionRE, ''); - const match = file.match(positionRE); - const lineNumber = match && match[1]; - const columnNumber = match && match[3]; - return { - fileName, - lineNumber, - columnNumber - } -} - -let _childProcess = null; - -function launchEditor (file, specifiedEditor, onErrorCallback) { - const parsed = parseFile(file); - let { fileName } = parsed; - const { lineNumber, columnNumber } = parsed; - - if (!fs$1.existsSync(fileName)) { - return - } - - if (typeof specifiedEditor === 'function') { - onErrorCallback = specifiedEditor; - specifiedEditor = undefined; - } - - onErrorCallback = wrapErrorCallback(onErrorCallback); - - const [editor, ...args] = guessEditor(specifiedEditor); - if (!editor) { - onErrorCallback(fileName, null); - return - } - - if ( - process.platform === 'linux' && - fileName.startsWith('/mnt/') && - /Microsoft/i.test(os$1.release()) - ) { - // Assume WSL / "Bash on Ubuntu on Windows" is being used, and - // that the file exists on the Windows file system. - // `os.release()` is "4.4.0-43-Microsoft" in the current release - // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364 - // When a Windows editor is specified, interop functionality can - // handle the path translation, but only if a relative path is used. - fileName = path$2.relative('', fileName); - } - - if (lineNumber) { - const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber); - args.push.apply(args, extraArgs); - } else { - args.push(fileName); - } - - if (_childProcess && isTerminalEditor(editor)) { - // There's an existing editor process already and it's attached - // to the terminal, so go kill it. Otherwise two separate editor - // instances attach to the stdin/stdout which gets confusing. - _childProcess.kill('SIGKILL'); - } - - if (process.platform === 'win32') { - // On Windows, launch the editor in a shell because spawn can only - // launch .exe files. - _childProcess = childProcess.spawn( - 'cmd.exe', - ['/C', editor].concat(args), - { stdio: 'inherit' } - ); - } else { - _childProcess = childProcess.spawn(editor, args, { stdio: 'inherit' }); - } - _childProcess.on('exit', function (errorCode) { - _childProcess = null; - - if (errorCode) { - onErrorCallback(fileName, '(code ' + errorCode + ')'); - } - }); - - _childProcess.on('error', function (error) { - onErrorCallback(fileName, error.message); - }); -} - -var launchEditor_1 = launchEditor; - -const url = require$$0__default$6; -const path$1 = path__default; -const launch = launchEditor_1; - -var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => { - if (typeof specifiedEditor === 'function') { - onErrorCallback = specifiedEditor; - specifiedEditor = undefined; - } - - if (typeof srcRoot === 'function') { - onErrorCallback = srcRoot; - srcRoot = undefined; - } - - srcRoot = srcRoot || process.cwd(); - - return function launchEditorMiddleware (req, res, next) { - const { file } = url.parse(req.url, true).query || {}; - if (!file) { - res.statusCode = 500; - res.end(`launch-editor-middleware: required query param "file" is missing.`); - } else { - launch(path$1.resolve(srcRoot, file), specifiedEditor, onErrorCallback); - res.end(); - } - } -}; - -const externalTypes = [ - 'css', - // supported pre-processor types - 'less', - 'sass', - 'scss', - 'styl', - 'stylus', - 'pcss', - 'postcss', - // known SFC types - 'vue', - 'svelte', - 'marko', - 'astro', - // JSX/TSX may be configured to be compiled differently from how esbuild - // handles it by default, so exclude them as well - 'jsx', - 'tsx', - ...KNOWN_ASSET_TYPES -]; -function esbuildDepPlugin(qualified, exportsData, config, ssr) { - // default resolver which prefers ESM - const _resolve = config.createResolver({ asSrc: false }); - // cjs resolver that prefers Node - const _resolveRequire = config.createResolver({ - asSrc: false, - isRequire: true - }); - const resolve = (id, importer, kind, resolveDir) => { - let _importer; - // explicit resolveDir - this is passed only during yarn pnp resolve for - // entries - if (resolveDir) { - _importer = normalizePath$4(path__default.join(resolveDir, '*')); - } - else { - // map importer ids to file paths for correct resolution - _importer = importer in qualified ? qualified[importer] : importer; - } - const resolver = kind.startsWith('require') ? _resolveRequire : _resolve; - return resolver(id, _importer, undefined, ssr); - }; - return { - name: 'vite:dep-pre-bundle', - setup(build) { - // externalize assets and commonly known non-js file types - build.onResolve({ - filter: new RegExp(`\\.(` + externalTypes.join('|') + `)(\\?.*)?$`) - }, async ({ path: id, importer, kind }) => { - const resolved = await resolve(id, importer, kind); - if (resolved) { - return { - path: resolved, - external: true - }; - } - }); - function resolveEntry(id) { - const flatId = flattenId(id); - if (flatId in qualified) { - return { - path: flatId, - namespace: 'dep' - }; - } - } - build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => { - // ensure esbuild uses our resolved entries - let entry; - // if this is an entry, return entry namespace resolve result - if (!importer) { - if ((entry = resolveEntry(id))) - return entry; - // check if this is aliased to an entry - also return entry namespace - const aliased = await _resolve(id, undefined, true); - if (aliased && (entry = resolveEntry(aliased))) { - return entry; - } - } - // use vite's own resolver - const resolved = await resolve(id, importer, kind); - if (resolved) { - if (resolved.startsWith(browserExternalId)) { - return { - path: id, - namespace: 'browser-external' - }; - } - if (isExternalUrl(resolved)) { - return { - path: resolved, - external: true - }; - } - return { - path: path__default.resolve(resolved) - }; - } - }); - // For entry files, we'll read it ourselves and construct a proxy module - // to retain the entry's raw id instead of file path so that esbuild - // outputs desired output file structure. - // It is necessary to do the re-exporting to separate the virtual proxy - // module from the actual module since the actual module may get - // referenced via relative imports - if we don't separate the proxy and - // the actual module, esbuild will create duplicated copies of the same - // module! - const root = path__default.resolve(config.root); - build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => { - const entryFile = qualified[id]; - let relativePath = normalizePath$4(path__default.relative(root, entryFile)); - if (!relativePath.startsWith('./') && - !relativePath.startsWith('../') && - relativePath !== '.') { - relativePath = `./${relativePath}`; - } - let contents = ''; - const data = exportsData[id]; - const [imports, exports] = data; - if (!imports.length && !exports.length) { - // cjs - contents += `export default require("${relativePath}");`; - } - else { - if (exports.includes('default')) { - contents += `import d from "${relativePath}";export default d;`; - } - if (data.hasReExports || - exports.length > 1 || - exports[0] !== 'default') { - contents += `\nexport * from "${relativePath}"`; - } - } - let ext = path__default.extname(entryFile).slice(1); - if (ext === 'mjs') - ext = 'js'; - return { - loader: ext, - contents, - resolveDir: root - }; - }); - build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path: id }) => { - return { - contents: `export default new Proxy({}, { - get() { - throw new Error('Module "${id}" has been externalized for ` + - `browser compatibility and cannot be accessed in client code.') - } -})` - }; - }); - // yarn 2 pnp compat - if (isRunningWithYarnPnp) { - build.onResolve({ filter: /.*/ }, async ({ path, importer, kind, resolveDir }) => ({ - // pass along resolveDir for entries - path: await resolve(path, importer, kind, resolveDir) - })); - build.onLoad({ filter: /.*/ }, async (args) => ({ - contents: await require('fs').promises.readFile(args.path), - loader: 'default' - })); - } - } - }; -} - -const debug$3 = createDebugger('vite:deps'); -async function optimizeDeps(config, force = config.server.force, asCommand = false, newDeps, // missing imports encountered after server has started -ssr) { - var _a, _b, _c, _d; - config = { - ...config, - command: 'build' - }; - const { root, logger, cacheDir } = config; - const log = asCommand ? logger.info : debug$3; - if (!cacheDir) { - log(`No cache directory. Skipping.`); - return null; - } - const dataPath = path__default.join(cacheDir, '_metadata.json'); - const mainHash = getDepHash(root, config); - const data = { - hash: mainHash, - browserHash: mainHash, - optimized: {} - }; - if (!force) { - let prevData; - try { - prevData = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8')); - } - catch (e) { } - // hash is consistent, no need to re-bundle - if (prevData && prevData.hash === data.hash) { - log('Hash is consistent. Skipping. Use --force to override.'); - return prevData; - } - } - if (fs__default.existsSync(cacheDir)) { - emptyDir(cacheDir); - } - else { - fs__default.mkdirSync(cacheDir, { recursive: true }); - } - // a hint for Node.js - // all files in the cache directory should be recognized as ES modules - writeFile(path__default.resolve(cacheDir, 'package.json'), JSON.stringify({ type: 'module' })); - let deps, missing; - if (!newDeps) { - ({ deps, missing } = await scanImports(config)); - } - else { - deps = newDeps; - missing = {}; - } - // update browser hash - data.browserHash = require$$1.createHash('sha256') - .update(data.hash + JSON.stringify(deps)) - .digest('hex') - .substr(0, 8); - const missingIds = Object.keys(missing); - if (missingIds.length) { - throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds - .map((id) => `${source.cyan(id)} ${source.white.dim(`(imported by ${missing[id]})`)}`) - .join(`\n `)}\n\nAre they installed?`); - } - const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include; - if (include) { - const resolve = config.createResolver({ asSrc: false }); - for (const id of include) { - // normalize 'foo >bar` as 'foo > bar' to prevent same id being added - // and for pretty printing - const normalizedId = normalizeId$1(id); - if (!deps[normalizedId]) { - const entry = await resolve(id); - if (entry) { - deps[normalizedId] = entry; - } - else { - throw new Error(`Failed to resolve force included dependency: ${source.cyan(id)}`); - } - } - } - } - const qualifiedIds = Object.keys(deps); - if (!qualifiedIds.length) { - writeFile(dataPath, JSON.stringify(data, null, 2)); - log(`No dependencies to bundle. Skipping.\n\n\n`); - return data; - } - const total = qualifiedIds.length; - const maxListed = 5; - const listed = Math.min(total, maxListed); - const extra = Math.max(0, total - maxListed); - const depsString = source.yellow(qualifiedIds.slice(0, listed).join(`\n `) + - (extra > 0 ? `\n (...and ${extra} more)` : ``)); - if (!asCommand) { - if (!newDeps) { - // This is auto run on server start - let the user know that we are - // pre-optimizing deps - logger.info(source.greenBright(`Pre-bundling dependencies:\n ${depsString}`)); - logger.info(`(this will be run only when your dependencies or config have changed)`); - } - } - else { - logger.info(source.greenBright(`Optimizing dependencies:\n ${depsString}`)); - } - // esbuild generates nested directory output with lowest common ancestor base - // this is unpredictable and makes it difficult to analyze entry / output - // mapping. So what we do here is: - // 1. flatten all ids to eliminate slash - // 2. in the plugin, read the entry ourselves as virtual files to retain the - // path. - const flatIdDeps = {}; - const idToExports = {}; - const flatIdToExports = {}; - const { plugins = [], ...esbuildOptions } = (_c = (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.esbuildOptions) !== null && _c !== void 0 ? _c : {}; - await init; - for (const id in deps) { - const flatId = flattenId(id); - const filePath = (flatIdDeps[flatId] = deps[id]); - const entryContent = fs__default.readFileSync(filePath, 'utf-8'); - let exportsData; - try { - exportsData = parse$f(entryContent); - } - catch { - debug$3(`Unable to parse dependency: ${id}. Trying again with a JSX transform.`); - const transformed = await transformWithEsbuild(entryContent, filePath, { - loader: 'jsx' - }); - // Ensure that optimization won't fail by defaulting '.js' to the JSX parser. - // This is useful for packages such as Gatsby. - esbuildOptions.loader = { - '.js': 'jsx', - ...esbuildOptions.loader - }; - exportsData = parse$f(transformed.code); - } - for (const { ss, se } of exportsData[0]) { - const exp = entryContent.slice(ss, se); - if (/export\s+\*\s+from/.test(exp)) { - exportsData.hasReExports = true; - } - } - idToExports[id] = exportsData; - flatIdToExports[flatId] = exportsData; - } - const define = { - 'process.env.NODE_ENV': JSON.stringify(config.mode) - }; - for (const key in config.define) { - const value = config.define[key]; - define[key] = typeof value === 'string' ? value : JSON.stringify(value); - } - const start = perf_hooks.performance.now(); - const result = await esbuild.build({ - absWorkingDir: process.cwd(), - entryPoints: Object.keys(flatIdDeps), - bundle: true, - format: 'esm', - target: config.build.target || undefined, - external: (_d = config.optimizeDeps) === null || _d === void 0 ? void 0 : _d.exclude, - logLevel: 'error', - splitting: true, - sourcemap: true, - outdir: cacheDir, - ignoreAnnotations: true, - metafile: true, - define, - plugins: [ - ...plugins, - esbuildDepPlugin(flatIdDeps, flatIdToExports, config, ssr) - ], - ...esbuildOptions - }); - const meta = result.metafile; - // the paths in `meta.outputs` are relative to `process.cwd()` - const cacheDirOutputPath = path__default.relative(process.cwd(), cacheDir); - for (const id in deps) { - const entry = deps[id]; - data.optimized[id] = { - file: normalizePath$4(path__default.resolve(cacheDir, flattenId(id) + '.js')), - src: entry, - needsInterop: needsInterop(id, idToExports[id], meta.outputs, cacheDirOutputPath) - }; - } - writeFile(dataPath, JSON.stringify(data, null, 2)); - debug$3(`deps bundled in ${(perf_hooks.performance.now() - start).toFixed(2)}ms`); - return data; -} -// https://github.com/vitejs/vite/issues/1724#issuecomment-767619642 -// a list of modules that pretends to be ESM but still uses `require`. -// this causes esbuild to wrap them as CJS even when its entry appears to be ESM. -const KNOWN_INTEROP_IDS = new Set(['moment']); -function needsInterop(id, exportsData, outputs, cacheDirOutputPath) { - if (KNOWN_INTEROP_IDS.has(id)) { - return true; - } - const [imports, exports] = exportsData; - // entry has no ESM syntax - likely CJS or UMD - if (!exports.length && !imports.length) { - return true; - } - // if a peer dependency used require() on a ESM dependency, esbuild turns the - // ESM dependency's entry chunk into a single default export... detect - // such cases by checking exports mismatch, and force interop. - const flatId = flattenId(id) + '.js'; - let generatedExports; - for (const output in outputs) { - if (normalizePath$4(output) === - normalizePath$4(path__default.join(cacheDirOutputPath, flatId))) { - generatedExports = outputs[output].exports; - break; - } - } - if (!generatedExports || - (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))) { - return true; - } - return false; -} -function isSingleDefaultExport(exports) { - return exports.length === 1 && exports[0] === 'default'; -} -const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']; -function getDepHash(root, config) { - var _a, _b; - let content = lookupFile(root, lockfileFormats) || ''; - // also take config into account - // only a subset of config options that can affect dep optimization - content += JSON.stringify({ - mode: config.mode, - root: config.root, - resolve: config.resolve, - assetsInclude: config.assetsInclude, - plugins: config.plugins.map((p) => p.name), - optimizeDeps: { - include: (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include, - exclude: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude - } - }, (_, value) => { - if (typeof value === 'function' || value instanceof RegExp) { - return value.toString(); - } - return value; - }); - return require$$1.createHash('sha256').update(content).digest('hex').substr(0, 8); -} - -var index$1 = { - __proto__: null, - optimizeDeps: optimizeDeps -}; - -var sourceMapGenerator = {}; - -var base64Vlq = {}; - -var base64$1 = {}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - -/** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ -base64$1.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); -}; - -/** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ -base64$1.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -var base64 = base64$1; - -// A single base 64 digit can contain 6 bits of data. For the base 64 variable -// length quantities we use in the source map spec, the first bit is the sign, -// the next four bits are the actual value, and the 6th bit is the -// continuation bit. The continuation bit tells us whether there are more -// digits in this value following this digit. -// -// Continuation -// | Sign -// | | -// V V -// 101011 - -var VLQ_BASE_SHIFT = 5; - -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; - -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; - -/** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ -function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; -} - -/** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ -function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; -} - -/** - * Returns the base 64 VLQ encoded value. - */ -base64Vlq.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; -}; - -/** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ -base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; -}; - -var util$5 = {}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -(function (exports) { -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -/** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ -function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } -} -exports.getArg = getArg; - -var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; -var dataUrlRegexp = /^data:.+\,.+$/; - -function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; -} -exports.urlParse = urlParse; - -function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port; - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; -} -exports.urlGenerate = urlGenerate; - -/** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ -function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); - - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; -} -exports.normalize = normalize; - -/** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. - */ -function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } - - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } - - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; -} -exports.join = join; - -exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || urlRegexp.test(aPath); -}; - -/** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ -function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); -} -exports.relative = relative; - -var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); -}()); - -function identity (s) { - return s; -} - -/** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ -function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; -} -exports.toSetString = supportsNullProto ? identity : toSetString; - -function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; -} -exports.fromSetString = supportsNullProto ? identity : fromSetString; - -function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; -} - -/** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ -function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByOriginalPositions = compareByOriginalPositions; - -/** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ -function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - -function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 === null) { - return 1; // aStr2 !== null - } - - if (aStr2 === null) { - return -1; // aStr1 !== null - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; -} - -/** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ -function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - -/** - * Strip any JSON XSSI avoidance prefix from the string (as documented - * in the source maps specification), and then parse the string as - * JSON. - */ -function parseSourceMapInput(str) { - return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); -} -exports.parseSourceMapInput = parseSourceMapInput; - -/** - * Compute the URL of a source given the the source root, the source's - * URL, and the source map's URL. - */ -function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { - sourceURL = sourceURL || ''; - - if (sourceRoot) { - // This follows what Chrome does. - if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { - sourceRoot += '/'; - } - // The spec says: - // Line 4: An optional source root, useful for relocating source - // files on a server or removing repeated values in the - // “sources” entry. This value is prepended to the individual - // entries in the “source” field. - sourceURL = sourceRoot + sourceURL; - } - - // Historically, SourceMapConsumer did not take the sourceMapURL as - // a parameter. This mode is still somewhat supported, which is why - // this code block is conditional. However, it's preferable to pass - // the source map URL to SourceMapConsumer, so that this function - // can implement the source URL resolution algorithm as outlined in - // the spec. This block is basically the equivalent of: - // new URL(sourceURL, sourceMapURL).toString() - // ... except it avoids using URL, which wasn't available in the - // older releases of node still supported by this library. - // - // The spec says: - // If the sources are not absolute URLs after prepending of the - // “sourceRoot”, the sources are resolved relative to the - // SourceMap (like resolving script src in a html document). - if (sourceMapURL) { - var parsed = urlParse(sourceMapURL); - if (!parsed) { - throw new Error("sourceMapURL could not be parsed"); - } - if (parsed.path) { - // Strip the last path component, but keep the "/". - var index = parsed.path.lastIndexOf('/'); - if (index >= 0) { - parsed.path = parsed.path.substring(0, index + 1); - } - } - sourceURL = join(urlGenerate(parsed), sourceURL); - } - - return normalize(sourceURL); -} -exports.computeSourceURL = computeSourceURL; -}(util$5)); - -var arraySet = {}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util$4 = util$5; -var has = Object.prototype.hasOwnProperty; -var hasNativeMap = typeof Map !== "undefined"; - -/** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ -function ArraySet$2() { - this._array = []; - this._set = hasNativeMap ? new Map() : Object.create(null); -} - -/** - * Static method for creating ArraySet instances from an existing array. - */ -ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet$2(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; -}; - -/** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number - */ -ArraySet$2.prototype.size = function ArraySet_size() { - return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; -}; - -/** - * Add the given string to this set. - * - * @param String aStr - */ -ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr); - var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - if (hasNativeMap) { - this._set.set(aStr, idx); - } else { - this._set[sStr] = idx; - } - } -}; - -/** - * Is the given string a member of this set? - * - * @param String aStr - */ -ArraySet$2.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap) { - return this._set.has(aStr); - } else { - var sStr = util$4.toSetString(aStr); - return has.call(this._set, sStr); - } -}; - -/** - * What is the index of the given string in the array? - * - * @param String aStr - */ -ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; - } - } else { - var sStr = util$4.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - } - - throw new Error('"' + aStr + '" is not in the set.'); -}; - -/** - * What is the element at the given index? - * - * @param Number aIdx - */ -ArraySet$2.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); -}; - -/** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ -ArraySet$2.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); -}; - -arraySet.ArraySet = ArraySet$2; - -var mappingList = {}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util$3 = util$5; - -/** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ -function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; -} - -/** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ -function MappingList$1() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; -} - -/** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ -MappingList$1.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - -/** - * Add the given source mapping. - * - * @param Object aMapping - */ -MappingList$1.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } -}; - -/** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ -MappingList$1.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util$3.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; -}; - -mappingList.MappingList = MappingList$1; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var base64VLQ$1 = base64Vlq; -var util$2 = util$5; -var ArraySet$1 = arraySet.ArraySet; -var MappingList = mappingList.MappingList; - -/** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ -function SourceMapGenerator$1(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util$2.getArg(aArgs, 'file', null); - this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet$1(); - this._names = new ArraySet$1(); - this._mappings = new MappingList(); - this._sourcesContents = null; -} - -SourceMapGenerator$1.prototype._version = 3; - -/** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ -SourceMapGenerator$1.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator$1({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util$2.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var sourceRelative = sourceFile; - if (sourceRoot !== null) { - sourceRelative = util$2.relative(sourceRoot, sourceFile); - } - - if (!generator._sources.has(sourceRelative)) { - generator._sources.add(sourceRelative); - } - - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - -/** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ -SourceMapGenerator$1.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util$2.getArg(aArgs, 'generated'); - var original = util$2.getArg(aArgs, 'original', null); - var source = util$2.getArg(aArgs, 'source', null); - var name = util$2.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - -/** - * Set the source content for a source file. - */ -SourceMapGenerator$1.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util$2.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util$2.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util$2.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - -/** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ -SourceMapGenerator$1.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util$2.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet$1(); - var newNames = new ArraySet$1(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util$2.join(aSourceMapPath, mapping.source); - } - if (sourceRoot != null) { - mapping.source = util$2.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util$2.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util$2.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - -/** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ -SourceMapGenerator$1.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - -/** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ -SourceMapGenerator$1.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = ''; - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64VLQ$1.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ$1.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ$1.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64VLQ$1.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ$1.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - -SourceMapGenerator$1.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util$2.relative(aSourceRoot, source); - } - var key = util$2.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - -/** - * Externalize the source map. - */ -SourceMapGenerator$1.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - -/** - * Render the source map being generated to a string. - */ -SourceMapGenerator$1.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - -sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$1; - -var sourceMapConsumer = {}; - -var binarySearch$1 = {}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -(function (exports) { -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -exports.GREATEST_LOWER_BOUND = 1; -exports.LEAST_UPPER_BOUND = 2; - -/** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ -function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } -} - -/** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ -exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; -}; -}(binarySearch$1)); - -var quickSort$1 = {}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -// It turns out that some (most?) JavaScript engines don't self-host -// `Array.prototype.sort`. This makes sense because C++ will likely remain -// faster than JS when doing raw CPU-intensive sorting. However, when using a -// custom comparator function, calling back and forth between the VM's C++ and -// JIT'd JS is rather slow *and* loses JIT type information, resulting in -// worse generated code for the comparator function than would be optimal. In -// fact, when sorting with a comparator, these costs outweigh the benefits of -// sorting in C++. By using our own JS-implemented Quick Sort (below), we get -// a ~3500ms mean speed-up in `bench/bench.html`. - -/** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ -function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; -} - -/** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ -function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); -} - -/** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ -function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } -} - -/** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ -quickSort$1.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util$1 = util$5; -var binarySearch = binarySearch$1; -var ArraySet = arraySet.ArraySet; -var base64VLQ = base64Vlq; -var quickSort = quickSort$1.quickSort; - -function SourceMapConsumer$1(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util$1.parseSourceMapInput(aSourceMap); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) - : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); -} - -SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); -}; - -/** - * The version of the source mapping spec that we are consuming. - */ -SourceMapConsumer$1.prototype._version = 3; - -// `__generatedMappings` and `__originalMappings` are arrays that hold the -// parsed mapping coordinates from the source map's "mappings" attribute. They -// are lazily instantiated, accessed via the `_generatedMappings` and -// `_originalMappings` getters respectively, and we only parse the mappings -// and create these arrays once queried for a source location. We jump through -// these hoops because there can be many thousands of mappings, and parsing -// them is expensive, so we only want to do it if we must. -// -// Each object in the arrays is of the form: -// -// { -// generatedLine: The line number in the generated code, -// generatedColumn: The column number in the generated code, -// source: The path to the original source file that generated this -// chunk of code, -// originalLine: The line number in the original source that -// corresponds to this chunk of generated code, -// originalColumn: The column number in the original source that -// corresponds to this chunk of generated code, -// name: The name of the original symbol which generated this chunk of -// code. -// } -// -// All properties except for `generatedLine` and `generatedColumn` can be -// `null`. -// -// `_generatedMappings` is ordered by the generated positions. -// -// `_originalMappings` is ordered by the original positions. - -SourceMapConsumer$1.prototype.__generatedMappings = null; -Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } -}); - -SourceMapConsumer$1.prototype.__originalMappings = null; -Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } -}); - -SourceMapConsumer$1.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -SourceMapConsumer$1.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - -SourceMapConsumer$1.GENERATED_ORDER = 1; -SourceMapConsumer$1.ORIGINAL_ORDER = 2; - -SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer$1.LEAST_UPPER_BOUND = 2; - -/** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ -SourceMapConsumer$1.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer$1.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer$1.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL); - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; - -/** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number is 1-based. - * - column: Optional. the column number in the original source. - * The column number is 0-based. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -SourceMapConsumer$1.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util$1.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util$1.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util$1.getArg(aArgs, 'column', 0) - }; - - needle.source = this._findSourceIndex(needle.source); - if (needle.source < 0) { - return []; - } - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util$1.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util$1.getArg(mapping, 'generatedLine', null), - column: util$1.getArg(mapping, 'generatedColumn', null), - lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util$1.getArg(mapping, 'generatedLine', null), - column: util$1.getArg(mapping, 'generatedColumn', null), - lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - -sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1; - -/** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The first parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ -function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util$1.parseSourceMapInput(aSourceMap); - } - - var version = util$1.getArg(sourceMap, 'version'); - var sources = util$1.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util$1.getArg(sourceMap, 'names', []); - var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null); - var mappings = util$1.getArg(sourceMap, 'mappings'); - var file = util$1.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - if (sourceRoot) { - sourceRoot = util$1.normalize(sourceRoot); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util$1.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source) - ? util$1.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - - this._absoluteSources = this._sources.toArray().map(function (s) { - return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL); - }); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this._sourceMapURL = aSourceMapURL; - this.file = file; -} - -BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1; - -/** - * Utility function to find the index of a source. Returns -1 if not - * found. - */ -BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util$1.relative(this.sourceRoot, relativeSource); - } - - if (this._sources.has(relativeSource)) { - return this._sources.indexOf(relativeSource); - } - - // Maybe aSource is an absolute URL as returned by |sources|. In - // this case we can't simply undo the transform. - var i; - for (i = 0; i < this._absoluteSources.length; ++i) { - if (this._absoluteSources[i] == aSource) { - return i; - } - } - - return -1; -}; - -/** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @param String aSourceMapURL - * The URL at which the source map can be found (optional) - * @returns BasicSourceMapConsumer - */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - smc._sourceMapURL = aSourceMapURL; - smc._absoluteSources = smc._sources.toArray().map(function (s) { - return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); - }); - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort(smc.__originalMappings, util$1.compareByOriginalPositions); - - return smc; - }; - -/** - * The version of the source mapping spec that we are consuming. - */ -BasicSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._absoluteSources.slice(); - } -}); - -/** - * Provide the JIT with a nice shape / hidden class. - */ -function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; -} - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } - - quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; - - quickSort(originalMappings, util$1.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; - -/** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; - -/** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util$1.getArg(aArgs, 'line'), - generatedColumn: util$1.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util$1.compareByGeneratedPositionsDeflated, - util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util$1.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); - } - var name = util$1.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util$1.getArg(mapping, 'originalLine', null), - column: util$1.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - var index = this._findSourceIndex(aSource); - if (index >= 0) { - return this.sourcesContent[index]; - } - - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util$1.relative(this.sourceRoot, relativeSource); - } - - var url; - if (this.sourceRoot != null - && (url = util$1.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + relativeSource)) { - return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + relativeSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util$1.getArg(aArgs, 'source'); - source = this._findSourceIndex(source); - if (source < 0) { - return { - line: null, - column: null, - lastColumn: null - }; - } - - var needle = { - source: source, - originalLine: util$1.getArg(aArgs, 'line'), - originalColumn: util$1.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util$1.compareByOriginalPositions, - util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util$1.getArg(mapping, 'generatedLine', null), - column: util$1.getArg(mapping, 'generatedColumn', null), - lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - -sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer; - -/** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The first parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ -function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util$1.parseSourceMapInput(aSourceMap); - } - - var version = util$1.getArg(sourceMap, 'version'); - var sections = util$1.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util$1.getArg(s, 'offset'); - var offsetLine = util$1.getArg(offset, 'line'); - var offsetColumn = util$1.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL) - } - }); -} - -IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); -IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1; - -/** - * The version of the source mapping spec that we are consuming. - */ -IndexedSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } -}); - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util$1.getArg(aArgs, 'line'), - generatedColumn: util$1.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = null; - if (mapping.name) { - name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - } - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util$1.compareByOriginalPositions); - }; - -sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var SourceMapGenerator = sourceMapGenerator.SourceMapGenerator; -var util = util$5; - -// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other -// operating systems these days (capturing the result). -var REGEX_NEWLINE = /(\r?\n)/; - -// Newline character code for charCodeAt() comparisons -var NEWLINE_CODE = 10; - -// Private symbol for identifying `SourceNode`s when multiple versions of -// the source-map library are loaded. This MUST NOT CHANGE across -// versions! -var isSourceNode = "$$$isSourceNode$$$"; - -/** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ -function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); -} - -/** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ -SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex] || ''; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex] || ''; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - -/** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } -}; - -/** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ -SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; -}; - -/** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ -SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; -}; - -/** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ -SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - -/** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - -/** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ -SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; -}; - -/** - * Returns the string representation of this source node along with a source - * map. - */ -SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; -}; - -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ -var SourceMapConsumer = sourceMapConsumer.SourceMapConsumer; - -let offset; -try { - new Function('throw new Error(1)')(); -} -catch (e) { - // in Node 12, stack traces account for the function wrapper. - // in Node 13 and later, the function wrapper adds two lines, - // which must be subtracted to generate a valid mapping - const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]); - offset = match ? +match[1] - 1 : 0; -} -function ssrRewriteStacktrace(stack, moduleGraph) { - return stack - .split('\n') - .map((line) => { - return line.replace(/^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/, (input, varName, url, line, column) => { - var _a; - if (!url) - return input; - const mod = moduleGraph.urlToModuleMap.get(url); - const rawSourceMap = (_a = mod === null || mod === void 0 ? void 0 : mod.ssrTransformResult) === null || _a === void 0 ? void 0 : _a.map; - if (!rawSourceMap) { - return input; - } - const consumer = new SourceMapConsumer(rawSourceMap); - const pos = consumer.originalPositionFor({ - line: Number(line) - offset, - column: Number(column), - bias: SourceMapConsumer.LEAST_UPPER_BOUND - }); - if (!pos.source) { - return input; - } - const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}`; - if (!varName || varName === 'eval') { - return ` at ${source}`; - } - else { - return ` at ${varName} (${source})`; - } - }); - }) - .join('\n'); -} -function rebindErrorStacktrace(e, stacktrace) { - const { configurable, writable } = Object.getOwnPropertyDescriptor(e, 'stack'); - if (configurable) { - Object.defineProperty(e, 'stack', { - value: stacktrace, - enumerable: true, - configurable: true, - writable: true - }); - } - else if (writable) { - e.stack = stacktrace; - } -} - -const pendingModules = new Map(); -const pendingImports = new Map(); -async function ssrLoadModule(url, server, context = { global }, urlStack = []) { - url = unwrapId$1(url); - // when we instantiate multiple dependency modules in parallel, they may - // point to shared modules. We need to avoid duplicate instantiation attempts - // by register every module as pending synchronously so that all subsequent - // request to that module are simply waiting on the same promise. - const pending = pendingModules.get(url); - if (pending) { - return pending; - } - const modulePromise = instantiateModule(url, server, context, urlStack); - pendingModules.set(url, modulePromise); - modulePromise - .catch(() => { - pendingImports.delete(url); - }) - .finally(() => { - pendingModules.delete(url); - }); - return modulePromise; -} -async function instantiateModule(url, server, context = { global }, urlStack = []) { - const { moduleGraph } = server; - const mod = await moduleGraph.ensureEntryFromUrl(url); - if (mod.ssrModule) { - return mod.ssrModule; - } - const result = mod.ssrTransformResult || - (await transformRequest(url, server, { ssr: true })); - if (!result) { - // TODO more info? is this even necessary? - throw new Error(`failed to load module for ssr: ${url}`); - } - const ssrModule = { - [Symbol.toStringTag]: 'Module' - }; - Object.defineProperty(ssrModule, '__esModule', { value: true }); - // Tolerate circular imports by ensuring the module can be - // referenced before it's been instantiated. - mod.ssrModule = ssrModule; - const ssrImportMeta = { - // The filesystem URL, matching native Node.js modules - url: require$$0$8.pathToFileURL(mod.file).toString() - }; - urlStack = urlStack.concat(url); - const isCircular = (url) => urlStack.includes(url); - // Since dynamic imports can happen in parallel, we need to - // account for multiple pending deps and duplicate imports. - const pendingDeps = []; - const ssrImport = async (dep) => { - var _a, _b; - if (dep[0] !== '.' && dep[0] !== '/') { - return nodeImport(dep, mod.file, server.config); - } - dep = unwrapId$1(dep); - if (!isCircular(dep) && !((_a = pendingImports.get(dep)) === null || _a === void 0 ? void 0 : _a.some(isCircular))) { - pendingDeps.push(dep); - if (pendingDeps.length === 1) { - pendingImports.set(url, pendingDeps); - } - let val = await ssrLoadModule(dep, server, context, urlStack); - if (pendingDeps.length === 1) { - pendingImports.delete(url); - } - else { - pendingDeps.splice(pendingDeps.indexOf(dep), 1); - } - return val; - } - return (_b = moduleGraph.urlToModuleMap.get(dep)) === null || _b === void 0 ? void 0 : _b.ssrModule; - }; - const ssrDynamicImport = (dep) => { - // #3087 dynamic import vars is ignored at rewrite import path, - // so here need process relative path - if (dep[0] === '.') { - dep = path__default.posix.resolve(path__default.dirname(url), dep); - } - return ssrImport(dep); - }; - function ssrExportAll(sourceModule) { - for (const key in sourceModule) { - if (key !== 'default') { - Object.defineProperty(ssrModule, key, { - enumerable: true, - configurable: true, - get() { - return sourceModule[key]; - } - }); - } - } - } - try { - // eslint-disable-next-line @typescript-eslint/no-empty-function - const AsyncFunction = async function () { }.constructor; - const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, result.code + `\n//# sourceURL=${mod.url}`); - await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll); - } - catch (e) { - const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph); - rebindErrorStacktrace(e, stacktrace); - server.config.logger.error(`Error when evaluating SSR module ${url}:\n${stacktrace}`, { - timestamp: true, - clear: server.config.clearScreen, - error: e - }); - throw e; - } - return Object.freeze(ssrModule); -} -// In node@12+ we can use dynamic import to load CJS and ESM -async function nodeImport(id, importer, config) { - let url; - // `resolve` doesn't handle `node:` builtins, so handle them directly - if (id.startsWith('node:') || isBuiltin(id)) { - url = id; - } - else { - url = resolve(id, importer, config.root, !!config.resolve.preserveSymlinks); - if (usingDynamicImport) { - url = require$$0$8.pathToFileURL(url).toString(); - } - } - const mod = await dynamicImport(url); - return proxyESM(id, mod); -} -// rollup-style default import interop for cjs -function proxyESM(id, mod) { - const defaultExport = mod.__esModule - ? mod.default - : mod.default - ? mod.default - : mod; - return new Proxy(mod, { - get(mod, prop) { - if (prop === 'default') - return defaultExport; - return mod[prop]; - } - }); -} -const resolveCache = new Map(); -function resolve(id, importer, root, preserveSymlinks) { - const key = id + importer + root; - const cached = resolveCache.get(key); - if (cached) { - return cached; - } - const resolveDir = importer && fs__default.existsSync(cleanUrl(importer)) - ? path__default.dirname(importer) - : root; - const resolved = resolveFrom$3(id, resolveDir, preserveSymlinks, true); - resolveCache.set(key, resolved); - return resolved; -} - -/** - * The amount to wait for requests to register newly found dependencies before triggering - * a re-bundle + page reload - */ -const debounceMs = 100; -function createMissingImporterRegisterFn(server) { - const { logger } = server.config; - let knownOptimized = server._optimizeDepsMetadata.optimized; - let currentMissing = {}; - let handle; - let pendingResolve = null; - async function rerun(ssr) { - const newDeps = currentMissing; - currentMissing = {}; - logger.info(source.yellow(`new dependencies found: ${Object.keys(newDeps).join(', ')}, updating...`), { - timestamp: true - }); - for (const id in knownOptimized) { - newDeps[id] = knownOptimized[id].src; - } - try { - // Nullify previous metadata so that the resolver won't - // resolve to optimized files during the optimizer re-run - server._isRunningOptimizer = true; - server._optimizeDepsMetadata = null; - const newData = (server._optimizeDepsMetadata = await optimizeDeps(server.config, true, false, newDeps, ssr)); - knownOptimized = newData.optimized; - // update ssr externals - server._ssrExternals = resolveSSRExternal(server.config, Object.keys(knownOptimized)); - logger.info(source.greenBright(`✨ dependencies updated, reloading page...`), { timestamp: true }); - } - catch (e) { - logger.error(source.red(`error while updating dependencies:\n${e.stack}`), { timestamp: true, error: e }); - } - finally { - server._isRunningOptimizer = false; - pendingResolve && pendingResolve(); - server._pendingReload = pendingResolve = null; - } - // Cached transform results have stale imports (resolved to - // old locations) so they need to be invalidated before the page is - // reloaded. - server.moduleGraph.invalidateAll(); - server.ws.send({ - type: 'full-reload', - path: '*' - }); - } - return function registerMissingImport(id, resolved, ssr) { - if (!knownOptimized[id]) { - currentMissing[id] = resolved; - if (handle) - clearTimeout(handle); - handle = setTimeout(() => rerun(ssr), debounceMs); - server._pendingReload = new Promise((r) => { - pendingResolve = r; - }); - } - }; -} - -// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079 -const ROOT_FILES = [ - // '.git', - // https://pnpm.js.org/workspaces/ - 'pnpm-workspace.yaml' - // https://rushjs.io/pages/advanced/config_files/ - // 'rush.json', - // https://nx.dev/latest/react/getting-started/nx-setup - // 'workspace.json', - // 'nx.json' -]; -// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces -// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it -function hasWorkspacePackageJSON(root) { - const path = path$t.join(root, 'package.json'); - try { - fs__default.accessSync(path, fs__default.constants.R_OK); - } - catch { - return false; - } - const content = JSON.parse(fs__default.readFileSync(path, 'utf-8')) || {}; - return !!content.workspaces; -} -function hasRootFile(root) { - return ROOT_FILES.some((file) => fs__default.existsSync(path$t.join(root, file))); -} -function hasPackageJSON(root) { - const path = path$t.join(root, 'package.json'); - return fs__default.existsSync(path); -} -/** - * Search up for the nearest `package.json` - */ -function searchForPackageRoot(current, root = current) { - if (hasPackageJSON(current)) - return current; - const dir = path$t.dirname(current); - // reach the fs root - if (!dir || dir === current) - return root; - return searchForPackageRoot(dir, root); -} -/** - * Search up for the nearest workspace root - */ -function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) { - if (hasRootFile(current)) - return current; - if (hasWorkspacePackageJSON(current)) - return current; - const dir = path$t.dirname(current); - // reach the fs root - if (!dir || dir === current) - return root; - return searchForWorkspaceRoot(dir, root); -} - -async function createServer(inlineConfig = {}) { - const config = await resolveConfig(inlineConfig, 'serve', 'development'); - const root = config.root; - const serverConfig = config.server; - const httpsOptions = await resolveHttpsConfig(config); - let { middlewareMode } = serverConfig; - if (middlewareMode === true) { - middlewareMode = 'ssr'; - } - const middlewares = connect(); - const httpServer = middlewareMode - ? null - : await resolveHttpServer(serverConfig, middlewares, httpsOptions); - const ws = createWebSocketServer(httpServer, config, httpsOptions); - const { ignored = [], ...watchOptions } = serverConfig.watch || {}; - const watcher = chokidar.watch(path__default.resolve(root), { - ignored: [ - '**/node_modules/**', - '**/.git/**', - ...(Array.isArray(ignored) ? ignored : [ignored]) - ], - ignoreInitial: true, - ignorePermissionErrors: true, - disableGlobbing: true, - ...watchOptions - }); - const plugins = config.plugins; - const container = await createPluginContainer(config, watcher); - const moduleGraph = new ModuleGraph(container); - const closeHttpServer = createServerCloseFn(httpServer); - // eslint-disable-next-line prefer-const - let exitProcess; - const server = { - config, - middlewares, - get app() { - config.logger.warn(`ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`); - return middlewares; - }, - httpServer, - watcher, - pluginContainer: container, - ws, - moduleGraph, - transformWithEsbuild, - transformRequest(url, options) { - return transformRequest(url, server, options); - }, - transformIndexHtml: null, - ssrLoadModule(url) { - if (!server._ssrExternals) { - server._ssrExternals = resolveSSRExternal(config, server._optimizeDepsMetadata - ? Object.keys(server._optimizeDepsMetadata.optimized) - : []); - } - return ssrLoadModule(url, server); - }, - ssrFixStacktrace(e) { - if (e.stack) { - const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph); - rebindErrorStacktrace(e, stacktrace); - } - }, - listen(port, isRestart) { - return startServer(server, port, isRestart); - }, - async close() { - process.off('SIGTERM', exitProcess); - if (!middlewareMode && process.env.CI !== 'true') { - process.stdin.off('end', exitProcess); - } - await Promise.all([ - watcher.close(), - ws.close(), - container.close(), - closeHttpServer() - ]); - }, - printUrls() { - if (httpServer) { - printHttpServerUrls(httpServer, config); - } - else { - throw new Error('cannot print server URLs in middleware mode.'); - } - }, - _optimizeDepsMetadata: null, - _ssrExternals: null, - _globImporters: Object.create(null), - _isRunningOptimizer: false, - _registerMissingImport: null, - _pendingReload: null, - _pendingRequests: Object.create(null) - }; - server.transformIndexHtml = createDevHtmlTransformFn(server); - exitProcess = async () => { - try { - await server.close(); - } - finally { - process.exit(0); - } - }; - process.once('SIGTERM', exitProcess); - if (!middlewareMode && process.env.CI !== 'true') { - process.stdin.on('end', exitProcess); - } - watcher.on('change', async (file) => { - file = normalizePath$4(file); - // invalidate module graph cache on file change - moduleGraph.onFileChange(file); - if (serverConfig.hmr !== false) { - try { - await handleHMRUpdate(file, server); - } - catch (err) { - ws.send({ - type: 'error', - err: prepareError(err) - }); - } - } - }); - watcher.on('add', (file) => { - handleFileAddUnlink(normalizePath$4(file), server); - }); - watcher.on('unlink', (file) => { - handleFileAddUnlink(normalizePath$4(file), server, true); - }); - if (!middlewareMode && httpServer) { - httpServer.once('listening', () => { - // update actual port since this may be different from initial value - serverConfig.port = httpServer.address().port; - }); - } - // apply server configuration hooks from plugins - const postHooks = []; - for (const plugin of plugins) { - if (plugin.configureServer) { - postHooks.push(await plugin.configureServer(server)); - } - } - // Internal middlewares ------------------------------------------------------ - // request timer - if (process.env.DEBUG) { - middlewares.use(timeMiddleware(root)); - } - // cors (enabled by default) - const { cors } = serverConfig; - if (cors !== false) { - middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors)); - } - // proxy - const { proxy } = serverConfig; - if (proxy) { - middlewares.use(proxyMiddleware(httpServer, config)); - } - // base - if (config.base !== '/') { - middlewares.use(baseMiddleware(server)); - } - // open in editor support - middlewares.use('/__open-in-editor', launchEditorMiddleware()); - // hmr reconnect ping - // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` - middlewares.use('/__vite_ping', function viteHMRPingMiddleware(_, res) { - res.end('pong'); - }); - // serve static files under /public - // this applies before the transform middleware so that these files are served - // as-is without transforms. - if (config.publicDir) { - middlewares.use(servePublicMiddleware(config.publicDir)); - } - // main transform middleware - middlewares.use(transformMiddleware(server)); - // serve static files - middlewares.use(serveRawFsMiddleware(server)); - middlewares.use(serveStaticMiddleware(root, config)); - // spa fallback - if (!middlewareMode || middlewareMode === 'html') { - middlewares.use(spaFallbackMiddleware(root)); - } - // run post config hooks - // This is applied before the html middleware so that user middleware can - // serve custom content instead of index.html. - postHooks.forEach((fn) => fn && fn()); - if (!middlewareMode || middlewareMode === 'html') { - // transform index.html - middlewares.use(indexHtmlMiddleware(server)); - // handle 404s - // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` - middlewares.use(function vite404Middleware(_, res) { - res.statusCode = 404; - res.end(); - }); - } - // error handler - middlewares.use(errorMiddleware(server, !!middlewareMode)); - const runOptimize = async () => { - if (config.cacheDir) { - server._isRunningOptimizer = true; - try { - server._optimizeDepsMetadata = await optimizeDeps(config); - } - finally { - server._isRunningOptimizer = false; - } - server._registerMissingImport = createMissingImporterRegisterFn(server); - } - }; - if (!middlewareMode && httpServer) { - let isOptimized = false; - // overwrite listen to run optimizer before server start - const listen = httpServer.listen.bind(httpServer); - httpServer.listen = (async (port, ...args) => { - if (!isOptimized) { - try { - await container.buildStart({}); - await runOptimize(); - isOptimized = true; - } - catch (e) { - httpServer.emit('error', e); - return; - } - } - return listen(port, ...args); - }); - } - else { - await container.buildStart({}); - await runOptimize(); - } - return server; -} -async function startServer(server, inlinePort, isRestart = false) { - const httpServer = server.httpServer; - if (!httpServer) { - throw new Error('Cannot call server.listen in middleware mode.'); - } - const options = server.config.server; - const port = inlinePort || options.port || 3000; - const hostname = resolveHostname(options.host); - const protocol = options.https ? 'https' : 'http'; - const info = server.config.logger.info; - const base = server.config.base; - const serverPort = await httpServerStart(httpServer, { - port, - strictPort: options.strictPort, - host: hostname.host, - logger: server.config.logger - }); - // @ts-ignore - const profileSession = global.__vite_profile_session; - if (profileSession) { - profileSession.post('Profiler.stop', (err, { profile }) => { - // Write profile to disk, upload, etc. - if (!err) { - const outPath = path__default.resolve('./vite-profile.cpuprofile'); - fs__default.writeFileSync(outPath, JSON.stringify(profile)); - info(source.yellow(` CPU profile written to ${source.white.dim(outPath)}\n`)); - } - else { - throw err; - } - }); - } - if (options.open && !isRestart) { - const path = typeof options.open === 'string' ? options.open : base; - openBrowser(path.startsWith('http') - ? path - : `${protocol}://${hostname.name}:${serverPort}${path}`, true, server.config.logger); - } - return server; -} -function createServerCloseFn(server) { - if (!server) { - return () => { }; - } - let hasListened = false; - const openSockets = new Set(); - server.on('connection', (socket) => { - openSockets.add(socket); - socket.on('close', () => { - openSockets.delete(socket); - }); - }); - server.once('listening', () => { - hasListened = true; - }); - return () => new Promise((resolve, reject) => { - openSockets.forEach((s) => s.destroy()); - if (hasListened) { - server.close((err) => { - if (err) { - reject(err); - } - else { - resolve(); - } - }); - } - else { - resolve(); - } - }); -} -function resolvedAllowDir(root, dir) { - return ensureLeadingSlash(normalizePath$4(path__default.resolve(root, dir))); -} -function resolveServerOptions(root, raw) { - var _a, _b; - const server = raw || {}; - let allowDirs = (_a = server.fs) === null || _a === void 0 ? void 0 : _a.allow; - if (!allowDirs) { - allowDirs = [searchForWorkspaceRoot(root)]; - } - allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i)); - // only push client dir when vite itself is outside-of-root - const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR); - if (!allowDirs.some((i) => resolvedClientDir.startsWith(i))) { - allowDirs.push(resolvedClientDir); - } - server.fs = { - // TODO: make strict by default - strict: (_b = server.fs) === null || _b === void 0 ? void 0 : _b.strict, - allow: allowDirs - }; - return server; -} - -var index = { - __proto__: null, - createServer: createServer, - resolveServerOptions: resolveServerOptions, - searchForWorkspaceRoot: searchForWorkspaceRoot -}; - -const noop = () => null; -function matches(pattern, importee) { - if (pattern instanceof RegExp) { - return pattern.test(importee); - } - if (importee.length < pattern.length) { - return false; - } - if (importee === pattern) { - return true; - } - const importeeStartsWithKey = importee.indexOf(pattern) === 0; - const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/'; - return importeeStartsWithKey && importeeHasSlashAfterKey; -} -function normalizeId(id) { - return id; -} -function getEntries({ entries }) { - if (!entries) { - return []; - } - if (Array.isArray(entries)) { - return entries; - } - return Object.entries(entries).map(([key, value]) => { - return { find: key, replacement: value }; - }); -} -function getCustomResolver({ customResolver }, options) { - if (typeof customResolver === 'function') { - return customResolver; - } - if (customResolver && typeof customResolver.resolveId === 'function') { - return customResolver.resolveId; - } - if (typeof options.customResolver === 'function') { - return options.customResolver; - } - if (options.customResolver && typeof options.customResolver.resolveId === 'function') { - return options.customResolver.resolveId; - } - return null; -} -function alias(options = {}) { - const entries = getEntries(options); - if (entries.length === 0) { - return { - name: 'alias', - resolveId: noop - }; - } - return { - name: 'alias', - buildStart(inputOptions) { - return Promise.all([...entries, options].map(({ customResolver }) => customResolver && - typeof customResolver === 'object' && - typeof customResolver.buildStart === 'function' && - customResolver.buildStart.call(this, inputOptions))).then(() => { - // enforce void return value - }); - }, - resolveId(importee, importer) { - const importeeId = normalizeId(importee); - const importerId = normalizeId(importer); - // First match is supposed to be the correct one - const matchedEntry = entries.find((entry) => matches(entry.find, importeeId)); - if (!matchedEntry || !importerId) { - return null; - } - const updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement)); - const customResolver = getCustomResolver(matchedEntry, options); - if (customResolver) { - return customResolver.call(this, updatedId, importerId, {}); - } - return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => { - let finalResult = resolved; - if (!finalResult) { - finalResult = { id: updatedId }; - } - return finalResult; - }); - } - }; -} - -/** - * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js - * - * This source code is licensed under the MIT license found in the - * LICENSE file at - * https://github.com/rollup/plugins/blob/master/LICENSE - */ -// Custom json filter for vite -const jsonExtRE = /\.json($|\?)(?!commonjs-(proxy|external))/; -function jsonPlugin(options = {}, isBuild) { - return { - name: 'vite:json', - transform(json, id) { - if (!jsonExtRE.test(id)) - return null; - if (SPECIAL_QUERY_RE.test(id)) - return null; - try { - if (options.stringify) { - if (isBuild) { - return { - // during build, parse then double-stringify to remove all - // unnecessary whitespaces to reduce bundle size. - code: `export default JSON.parse(${JSON.stringify(JSON.stringify(JSON.parse(json)))})`, - map: { mappings: '' } - }; - } - else { - return `export default JSON.parse(${JSON.stringify(json)})`; - } - } - const parsed = JSON.parse(json); - return { - code: dataToEsm(parsed, { - preferConst: true, - namedExports: options.namedExports - }), - map: { mappings: '' } - }; - } - catch (e) { - const errorMessageList = /[\d]+/.exec(e.message); - const position = errorMessageList && parseInt(errorMessageList[0], 10); - const msg = position - ? `, invalid JSON syntax found at line ${position}` - : `.`; - this.error(`Failed to parse JSON file` + msg, e.idx); - } - } - }; -} - -const isDebug = !!process.env.DEBUG; -const debug$2 = createDebugger('vite:import-analysis'); -const clientDir = normalizePath$4(CLIENT_DIR); -const skipRE = /\.(map|json)$/; -const canSkip = (id) => skipRE.test(id) || isDirectCSSRequest(id); -function isExplicitImportRequired(url) { - return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url); -} -function markExplicitImport(url) { - if (isExplicitImportRequired(url)) { - return injectQuery(url, 'import'); - } - return url; -} -/** - * Server-only plugin that lexes, resolves, rewrites and analyzes url imports. - * - * - Imports are resolved to ensure they exist on disk - * - * - Lexes HMR accept calls and updates import relationships in the module graph - * - * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to - * absolute file paths, e.g. - * - * ```js - * import 'foo' - * ``` - * is rewritten to - * ```js - * import '/@fs//project/node_modules/foo/dist/foo.js' - * ``` - * - * - CSS imports are appended with `.js` since both the js module and the actual - * css (referenced via ) may go through the transform pipeline: - * - * ```js - * import './style.css' - * ``` - * is rewritten to - * ```js - * import './style.css.js' - * ``` - */ -function importAnalysisPlugin(config) { - const { root, base } = config; - const clientPublicPath = path__default.posix.join(base, CLIENT_PUBLIC_PATH); - let server; - return { - name: 'vite:import-analysis', - configureServer(_server) { - server = _server; - }, - async transform(source$1, importer, ssr) { - const prettyImporter = prettifyUrl(importer, root); - if (canSkip(importer)) { - isDebug && debug$2(source.dim(`[skipped] ${prettyImporter}`)); - return null; - } - const start = perf_hooks.performance.now(); - await init; - let imports = []; - // strip UTF-8 BOM - if (source$1.charCodeAt(0) === 0xfeff) { - source$1 = source$1.slice(1); - } - try { - imports = parse$f(source$1)[0]; - } - catch (e) { - const isVue = importer.endsWith('.vue'); - const maybeJSX = !isVue && isJSRequest(importer); - const msg = isVue - ? `Install @vitejs/plugin-vue to handle .vue files.` - : maybeJSX - ? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.` - : `You may need to install appropriate plugins to handle the ${path__default.extname(importer)} file format.`; - this.error(`Failed to parse source for import analysis because the content ` + - `contains invalid JS syntax. ` + - msg, e.idx); - } - if (!imports.length) { - isDebug && - debug$2(`${timeFrom(start)} ${source.dim(`[no imports] ${prettyImporter}`)}`); - return source$1; - } - let hasHMR = false; - let isSelfAccepting = false; - let hasEnv = false; - let needQueryInjectHelper = false; - let s; - const str = () => s || (s = new MagicString(source$1)); - // vite-only server context - const { moduleGraph } = server; - // since we are already in the transform phase of the importer, it must - // have been loaded so its entry is guaranteed in the module graph. - const importerModule = moduleGraph.getModuleById(importer); - const importedUrls = new Set(); - const staticImportedUrls = new Set(); - const acceptedUrls = new Set(); - const toAbsoluteUrl = (url) => path__default.posix.resolve(path__default.posix.dirname(importerModule.url), url); - const normalizeUrl = async (url, pos) => { - if (base !== '/' && url.startsWith(base)) { - url = url.replace(base, '/'); - } - const resolved = await this.resolve(url, importer); - if (!resolved) { - this.error(`Failed to resolve import "${url}" from "${path__default.relative(process.cwd(), importer)}". Does the file exist?`, pos); - } - const isRelative = url.startsWith('.'); - const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer); - // normalize all imports into resolved URLs - // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js` - if (resolved.id.startsWith(root + '/')) { - // in root: infer short absolute path from root - url = resolved.id.slice(root.length); - } - else if (fs__default.existsSync(cleanUrl(resolved.id))) { - // exists but out of root: rewrite to absolute /@fs/ paths - url = path__default.posix.join(FS_PREFIX + resolved.id); - } - else { - url = resolved.id; - } - if (isExternalUrl(url)) { - return [url, url]; - } - // if the resolved id is not a valid browser import specifier, - // prefix it to make it valid. We will strip this before feeding it - // back into the transform pipeline - if (!url.startsWith('.') && !url.startsWith('/')) { - url = - VALID_ID_PREFIX + resolved.id.replace('\0', NULL_BYTE_PLACEHOLDER); - } - // make the URL browser-valid if not SSR - if (!ssr) { - // mark non-js/css imports with `?import` - url = markExplicitImport(url); - // for relative js/css imports, or self-module virtual imports - // (e.g. vue blocks), inherit importer's version query - // do not do this for unknown type imports, otherwise the appended - // query can break 3rd party plugin's extension checks. - if ((isRelative || isSelfImport) && !/[\?&]import=?\b/.test(url)) { - const versionMatch = importer.match(DEP_VERSION_RE); - if (versionMatch) { - url = injectQuery(url, versionMatch[1]); - } - } - // check if the dep has been hmr updated. If yes, we need to attach - // its last updated timestamp to force the browser to fetch the most - // up-to-date version of this module. - try { - const depModule = await moduleGraph.ensureEntryFromUrl(url); - if (depModule.lastHMRTimestamp > 0) { - url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`); - } - } - catch (e) { - // it's possible that the dep fails to resolve (non-existent import) - // attach location to the missing import - e.pos = pos; - throw e; - } - // prepend base (dev base is guaranteed to have ending slash) - url = base + url.replace(/^\//, ''); - } - return [url, resolved.id]; - }; - for (let index = 0; index < imports.length; index++) { - const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, - // #2083 User may use escape path, - // so use imports[index].n to get the unescaped string - // @ts-ignore - n: specifier } = imports[index]; - const rawUrl = source$1.slice(start, end); - // check import.meta usage - if (rawUrl === 'import.meta') { - const prop = source$1.slice(end, end + 4); - if (prop === '.hot') { - hasHMR = true; - if (source$1.slice(end + 4, end + 11) === '.accept') { - // further analyze accepted modules - if (lexAcceptedHmrDeps(source$1, source$1.indexOf('(', end + 11) + 1, acceptedUrls)) { - isSelfAccepting = true; - } - } - } - else if (prop === '.env') { - hasEnv = true; - } - else if (prop === '.glo' && source$1[end + 4] === 'b') { - // transform import.meta.glob() - // e.g. `import.meta.glob('glob:./dir/*.js')` - const { imports, importsString, exp, endIndex, base, pattern, isEager } = await transformImportGlob(source$1, start, importer, index, root, normalizeUrl); - str().prepend(importsString); - str().overwrite(expStart, endIndex, exp); - imports.forEach((url) => { - url = url.replace(base, '/'); - importedUrls.add(url); - if (isEager) - staticImportedUrls.add(url); - }); - if (!(importerModule.file in server._globImporters)) { - server._globImporters[importerModule.file] = { - module: importerModule, - importGlobs: [] - }; - } - server._globImporters[importerModule.file].importGlobs.push({ - base, - pattern - }); - } - continue; - } - const isDynamicImport = dynamicIndex >= 0; - // static import or valid string in dynamic import - // If resolvable, let's resolve it - if (specifier) { - // skip external / data uri - if (isExternalUrl(specifier) || isDataUrl(specifier)) { - continue; - } - // skip ssr external - if (ssr) { - if (server._ssrExternals && - shouldExternalizeForSSR(specifier, server._ssrExternals)) { - continue; - } - if (isBuiltin(specifier)) { - continue; - } - } - // skip client - if (specifier === clientPublicPath) { - continue; - } - // warn imports to non-asset /public files - if (specifier.startsWith('/') && - !config.assetsInclude(cleanUrl(specifier)) && - !specifier.endsWith('.json') && - checkPublicFile(specifier, config)) { - throw new Error(`Cannot import non-asset file ${specifier} which is inside /public.` + - `JS/CSS files inside /public are copied as-is on build and ` + - `can only be referenced via \n const filePath = id.replace(config.root, '')\n addToHTMLProxyCache(\n config,\n filePath,\n inlineModuleIndex,\n contents\n )\n js += `\\nimport \"${id}?html-proxy&index=${inlineModuleIndex}.js\"`\n shouldRemove = true\n }\n\n everyScriptIsAsync &&= isAsync\n someScriptsAreAsync ||= isAsync\n someScriptsAreDefer ||= !isAsync\n }\n }\n\n // For asset references in index.html, also generate an import\n // statement for each - this will be handled by the asset plugin\n const assetAttrs = assetAttrsConfig[node.tag]\n if (assetAttrs) {\n for (const p of node.props) {\n if (\n p.type === NodeTypes.ATTRIBUTE &&\n p.value &&\n assetAttrs.includes(p.name)\n ) {\n const url = p.value.content\n if (!isExcludedUrl(url)) {\n if (node.tag === 'link' && isCSSRequest(url)) {\n // CSS references, convert to import\n js += `\\nimport ${JSON.stringify(url)}`\n shouldRemove = true\n } else {\n assetUrls.push(p)\n }\n } else if (checkPublicFile(url, config)) {\n s.overwrite(\n p.value.loc.start.offset,\n p.value.loc.end.offset,\n `\"${config.base + url.slice(1)}\"`\n )\n }\n }\n }\n }\n\n if (shouldRemove) {\n // remove the script tag from the html. we are going to inject new\n // ones in the end.\n s.remove(node.loc.start.offset, node.loc.end.offset)\n }\n })\n\n isAsyncScriptMap.get(config)!.set(id, everyScriptIsAsync)\n\n if (someScriptsAreAsync && someScriptsAreDefer) {\n config.logger.warn(\n `\\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`\n )\n }\n\n // for each encountered asset url, rewrite original html so that it\n // references the post-build location.\n for (const attr of assetUrls) {\n const value = attr.value!\n try {\n const url =\n attr.name === 'srcset'\n ? await processSrcSet(value.content, ({ url }) =>\n urlToBuiltUrl(url, id, config, this)\n )\n : await urlToBuiltUrl(value.content, id, config, this)\n\n s.overwrite(\n value.loc.start.offset,\n value.loc.end.offset,\n `\"${url}\"`\n )\n } catch (e) {\n // #1885 preload may be pointing to urls that do not exist\n // locally on disk\n if (e.code !== 'ENOENT') {\n throw e\n }\n }\n }\n\n processedHtml.set(id, s.toString())\n\n // inject module preload polyfill only when configured and needed\n if (\n config.build.polyfillModulePreload &&\n (someScriptsAreAsync || someScriptsAreDefer)\n ) {\n js = `import \"${modulePreloadPolyfillId}\";\\n${js}`\n }\n\n return js\n }\n },\n\n async generateBundle(options, bundle) {\n const analyzedChunk: Map = new Map()\n const getImportedChunks = (\n chunk: OutputChunk,\n seen: Set = new Set()\n ): OutputChunk[] => {\n const chunks: OutputChunk[] = []\n chunk.imports.forEach((file) => {\n const importee = bundle[file]\n if (importee?.type === 'chunk' && !seen.has(file)) {\n seen.add(file)\n\n // post-order traversal\n chunks.push(...getImportedChunks(importee, seen))\n chunks.push(importee)\n }\n })\n return chunks\n }\n\n const toScriptTag = (\n chunk: OutputChunk,\n isAsync: boolean\n ): HtmlTagDescriptor => ({\n tag: 'script',\n attrs: {\n ...(isAsync ? { async: true } : {}),\n type: 'module',\n crossorigin: true,\n src: toPublicPath(chunk.fileName, config)\n }\n })\n\n const toPreloadTag = (chunk: OutputChunk): HtmlTagDescriptor => ({\n tag: 'link',\n attrs: {\n rel: 'modulepreload',\n href: toPublicPath(chunk.fileName, config)\n }\n })\n\n const getCssTagsForChunk = (\n chunk: OutputChunk,\n seen: Set = new Set()\n ): HtmlTagDescriptor[] => {\n const tags: HtmlTagDescriptor[] = []\n if (!analyzedChunk.has(chunk)) {\n analyzedChunk.set(chunk, 1)\n chunk.imports.forEach((file) => {\n const importee = bundle[file]\n if (importee?.type === 'chunk') {\n tags.push(...getCssTagsForChunk(importee, seen))\n }\n })\n }\n\n const cssFiles = chunkToEmittedCssFileMap.get(chunk)\n if (cssFiles) {\n cssFiles.forEach((file) => {\n if (!seen.has(file)) {\n seen.add(file)\n tags.push({\n tag: 'link',\n attrs: {\n rel: 'stylesheet',\n href: toPublicPath(file, config)\n }\n })\n }\n })\n }\n return tags\n }\n\n for (const [id, html] of processedHtml) {\n const isAsync = isAsyncScriptMap.get(config)!.get(id)!\n\n // resolve asset url references\n let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => {\n return config.base + getAssetFilename(fileHash, config) + postfix\n })\n\n // find corresponding entry chunk\n const chunk = Object.values(bundle).find(\n (chunk) =>\n chunk.type === 'chunk' &&\n chunk.isEntry &&\n chunk.facadeModuleId === id\n ) as OutputChunk | undefined\n\n let canInlineEntry = false\n\n // inject chunk asset links\n if (chunk) {\n // an entry chunk can be inlined if\n // - it's an ES module (e.g. not generated by the legacy plugin)\n // - it contains no meaningful code other than import statements\n if (options.format === 'es' && isEntirelyImport(chunk.code)) {\n canInlineEntry = true\n }\n\n // when not inlined, inject `\n )\n }\n }\n\n // elements with [href/src] attrs\n const assetAttrs = assetAttrsConfig[node.tag]\n if (assetAttrs) {\n for (const p of node.props) {\n if (\n p.type === NodeTypes.ATTRIBUTE &&\n p.value &&\n assetAttrs.includes(p.name)\n ) {\n processNodeUrl(p, s, config, htmlPath, originalUrl)\n }\n }\n }\n })\n\n html = s.toString()\n\n return {\n html,\n tags: [\n {\n tag: 'script',\n attrs: {\n type: 'module',\n src: path.posix.join(base, CLIENT_PUBLIC_PATH)\n },\n injectTo: 'head-prepend'\n }\n ]\n }\n}\n\nexport function indexHtmlMiddleware(\n server: ViteDevServer\n): Connect.NextHandleFunction {\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return async function viteIndexHtmlMiddleware(req, res, next) {\n if (res.writableEnded) {\n return next()\n }\n\n const url = req.url && cleanUrl(req.url)\n // spa-fallback always redirects to /index.html\n if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') {\n const filename = getHtmlFilename(url, server)\n if (fs.existsSync(filename)) {\n try {\n let html = fs.readFileSync(filename, 'utf-8')\n html = await server.transformIndexHtml(url, html, req.originalUrl)\n return send(req, res, html, 'html')\n } catch (e) {\n return next(e)\n }\n }\n }\n next()\n }\n}\n","import { performance } from 'perf_hooks'\nimport { Connect } from 'types/connect'\nimport { createDebugger, prettifyUrl, timeFrom } from '../../utils'\n\nconst logTime = createDebugger('vite:time')\n\nexport function timeMiddleware(root: string): Connect.NextHandleFunction {\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return function viteTimeMiddleware(req, res, next) {\n const start = performance.now()\n const end = res.end\n res.end = (...args: any[]) => {\n logTime(`${timeFrom(start)} ${prettifyUrl(req.url!, root)}`)\n // @ts-ignore\n return end.call(res, ...args)\n }\n next()\n }\n}\n","import { extname } from 'path'\nimport { isDirectCSSRequest } from '../plugins/css'\nimport {\n cleanUrl,\n normalizePath,\n removeImportQuery,\n removeTimestampQuery\n} from '../utils'\nimport { FS_PREFIX } from '../constants'\nimport { TransformResult } from './transformRequest'\nimport { PluginContainer } from './pluginContainer'\nimport { parse as parseUrl } from 'url'\n\nexport class ModuleNode {\n /**\n * Public served url path, starts with /\n */\n url: string\n /**\n * Resolved file system path + query\n */\n id: string | null = null\n file: string | null = null\n type: 'js' | 'css'\n importers = new Set()\n importedModules = new Set()\n acceptedHmrDeps = new Set()\n isSelfAccepting = false\n transformResult: TransformResult | null = null\n ssrTransformResult: TransformResult | null = null\n ssrModule: Record | null = null\n lastHMRTimestamp = 0\n\n constructor(url: string) {\n this.url = url\n this.type = isDirectCSSRequest(url) ? 'css' : 'js'\n }\n}\n\nfunction invalidateSSRModule(mod: ModuleNode, seen: Set) {\n if (seen.has(mod)) {\n return\n }\n seen.add(mod)\n mod.ssrModule = null\n mod.importers.forEach((importer) => invalidateSSRModule(importer, seen))\n}\nexport class ModuleGraph {\n urlToModuleMap = new Map()\n idToModuleMap = new Map()\n // a single file may corresponds to multiple modules with different queries\n fileToModulesMap = new Map>()\n safeModulesPath = new Set()\n container: PluginContainer\n\n constructor(container: PluginContainer) {\n this.container = container\n }\n\n async getModuleByUrl(rawUrl: string): Promise {\n const [url] = await this.resolveUrl(rawUrl)\n return this.urlToModuleMap.get(url)\n }\n\n getModuleById(id: string): ModuleNode | undefined {\n return this.idToModuleMap.get(removeTimestampQuery(id))\n }\n\n getModulesByFile(file: string): Set | undefined {\n return this.fileToModulesMap.get(file)\n }\n\n onFileChange(file: string): void {\n const mods = this.getModulesByFile(file)\n if (mods) {\n const seen = new Set()\n mods.forEach((mod) => {\n this.invalidateModule(mod, seen)\n })\n }\n }\n\n invalidateModule(mod: ModuleNode, seen: Set = new Set()): void {\n mod.transformResult = null\n mod.ssrTransformResult = null\n invalidateSSRModule(mod, seen)\n }\n\n invalidateAll(): void {\n const seen = new Set()\n this.idToModuleMap.forEach((mod) => {\n this.invalidateModule(mod, seen)\n })\n }\n\n /**\n * Update the module graph based on a module's updated imports information\n * If there are dependencies that no longer have any importers, they are\n * returned as a Set.\n */\n async updateModuleInfo(\n mod: ModuleNode,\n importedModules: Set,\n acceptedModules: Set,\n isSelfAccepting: boolean\n ): Promise | undefined> {\n mod.isSelfAccepting = isSelfAccepting\n const prevImports = mod.importedModules\n const nextImports = (mod.importedModules = new Set())\n let noLongerImported: Set | undefined\n // update import graph\n for (const imported of importedModules) {\n const dep =\n typeof imported === 'string'\n ? await this.ensureEntryFromUrl(imported)\n : imported\n dep.importers.add(mod)\n nextImports.add(dep)\n }\n // remove the importer from deps that were imported but no longer are.\n prevImports.forEach((dep) => {\n if (!nextImports.has(dep)) {\n dep.importers.delete(mod)\n if (!dep.importers.size) {\n // dependency no longer imported\n ;(noLongerImported || (noLongerImported = new Set())).add(dep)\n }\n }\n })\n // update accepted hmr deps\n const deps = (mod.acceptedHmrDeps = new Set())\n for (const accepted of acceptedModules) {\n const dep =\n typeof accepted === 'string'\n ? await this.ensureEntryFromUrl(accepted)\n : accepted\n deps.add(dep)\n }\n return noLongerImported\n }\n\n async ensureEntryFromUrl(rawUrl: string): Promise {\n const [url, resolvedId] = await this.resolveUrl(rawUrl)\n let mod = this.urlToModuleMap.get(url)\n if (!mod) {\n mod = new ModuleNode(url)\n this.urlToModuleMap.set(url, mod)\n mod.id = resolvedId\n this.idToModuleMap.set(resolvedId, mod)\n const file = (mod.file = cleanUrl(resolvedId))\n let fileMappedModules = this.fileToModulesMap.get(file)\n if (!fileMappedModules) {\n fileMappedModules = new Set()\n this.fileToModulesMap.set(file, fileMappedModules)\n }\n fileMappedModules.add(mod)\n }\n return mod\n }\n\n // some deps, like a css file referenced via @import, don't have its own\n // url because they are inlined into the main css import. But they still\n // need to be represented in the module graph so that they can trigger\n // hmr in the importing css file.\n createFileOnlyEntry(file: string): ModuleNode {\n file = normalizePath(file)\n let fileMappedModules = this.fileToModulesMap.get(file)\n if (!fileMappedModules) {\n fileMappedModules = new Set()\n this.fileToModulesMap.set(file, fileMappedModules)\n }\n\n const url = `${FS_PREFIX}${file}`\n for (const m of fileMappedModules) {\n if (m.url === url || m.id === file) {\n return m\n }\n }\n\n const mod = new ModuleNode(url)\n mod.file = file\n fileMappedModules.add(mod)\n return mod\n }\n\n // for incoming urls, it is important to:\n // 1. remove the HMR timestamp query (?t=xxxx)\n // 2. resolve its extension so that urls with or without extension all map to\n // the same module\n async resolveUrl(url: string): Promise<[string, string]> {\n url = removeImportQuery(removeTimestampQuery(url))\n const resolvedId = (await this.container.resolveId(url))?.id || url\n const ext = extname(cleanUrl(resolvedId))\n const { pathname, search, hash } = parseUrl(url)\n if (ext && !pathname!.endsWith(ext)) {\n url = pathname + ext + (search || '') + (hash || '')\n }\n return [url, resolvedId]\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport chalk from 'chalk'\nimport { createServer, ViteDevServer } from '..'\nimport { createDebugger, normalizePath } from '../utils'\nimport { ModuleNode } from './moduleGraph'\nimport { Update } from 'types/hmrPayload'\nimport { CLIENT_DIR } from '../constants'\nimport { RollupError } from 'rollup'\nimport match from 'minimatch'\nimport { Server } from 'http'\nimport { isCSSRequest } from '../plugins/css'\nimport { performance } from 'perf_hooks'\n\nexport const debugHmr = createDebugger('vite:hmr')\n\nconst normalizedClientDir = normalizePath(CLIENT_DIR)\n\nexport interface HmrOptions {\n protocol?: string\n host?: string\n port?: number\n clientPort?: number\n path?: string\n timeout?: number\n overlay?: boolean\n server?: Server\n}\n\nexport interface HmrContext {\n file: string\n timestamp: number\n modules: Array\n read: () => string | Promise\n server: ViteDevServer\n}\n\nfunction getShortName(file: string, root: string) {\n return file.startsWith(root + '/') ? path.posix.relative(root, file) : file\n}\n\nexport async function handleHMRUpdate(\n file: string,\n server: ViteDevServer\n): Promise {\n const { ws, config, moduleGraph } = server\n const shortFile = getShortName(file, config.root)\n\n const isConfig = file === config.configFile\n const isConfigDependency = config.configFileDependencies.some(\n (name) => file === path.resolve(name)\n )\n const isEnv = config.inlineConfig.envFile !== false && file.endsWith('.env')\n if (isConfig || isConfigDependency || isEnv) {\n // auto restart server\n debugHmr(`[config change] ${chalk.dim(shortFile)}`)\n config.logger.info(\n chalk.green(\n `${path.relative(process.cwd(), file)} changed, restarting server...`\n ),\n { clear: true, timestamp: true }\n )\n await restartServer(server)\n return\n }\n\n debugHmr(`[file change] ${chalk.dim(shortFile)}`)\n\n // (dev only) the client itself cannot be hot updated.\n if (file.startsWith(normalizedClientDir)) {\n ws.send({\n type: 'full-reload',\n path: '*'\n })\n return\n }\n\n const mods = moduleGraph.getModulesByFile(file)\n\n // check if any plugin wants to perform custom HMR handling\n const timestamp = Date.now()\n const hmrContext: HmrContext = {\n file,\n timestamp,\n modules: mods ? [...mods] : [],\n read: () => readModifiedFile(file),\n server\n }\n\n for (const plugin of config.plugins) {\n if (plugin.handleHotUpdate) {\n const filteredModules = await plugin.handleHotUpdate(hmrContext)\n if (filteredModules) {\n hmrContext.modules = filteredModules\n break\n }\n }\n }\n\n if (!hmrContext.modules.length) {\n // html file cannot be hot updated\n if (file.endsWith('.html')) {\n config.logger.info(chalk.green(`page reload `) + chalk.dim(shortFile), {\n clear: true,\n timestamp: true\n })\n ws.send({\n type: 'full-reload',\n path: config.server.middlewareMode\n ? '*'\n : '/' + normalizePath(path.relative(config.root, file))\n })\n } else {\n // loaded but not in the module graph, probably not js\n debugHmr(`[no modules matched] ${chalk.dim(shortFile)}`)\n }\n return\n }\n\n updateModules(shortFile, hmrContext.modules, timestamp, server)\n}\n\nfunction updateModules(\n file: string,\n modules: ModuleNode[],\n timestamp: number,\n { config, ws }: ViteDevServer\n) {\n const updates: Update[] = []\n const invalidatedModules = new Set()\n let needFullReload = false\n\n for (const mod of modules) {\n invalidate(mod, timestamp, invalidatedModules)\n if (needFullReload) {\n continue\n }\n\n const boundaries = new Set<{\n boundary: ModuleNode\n acceptedVia: ModuleNode\n }>()\n const hasDeadEnd = propagateUpdate(mod, boundaries)\n if (hasDeadEnd) {\n needFullReload = true\n continue\n }\n\n updates.push(\n ...[...boundaries].map(({ boundary, acceptedVia }) => ({\n type: `${boundary.type}-update` as Update['type'],\n timestamp,\n path: boundary.url,\n acceptedPath: acceptedVia.url\n }))\n )\n }\n\n if (needFullReload) {\n config.logger.info(chalk.green(`page reload `) + chalk.dim(file), {\n clear: true,\n timestamp: true\n })\n ws.send({\n type: 'full-reload'\n })\n } else {\n config.logger.info(\n updates\n .map(({ path }) => chalk.green(`hmr update `) + chalk.dim(path))\n .join('\\n'),\n { clear: true, timestamp: true }\n )\n ws.send({\n type: 'update',\n updates\n })\n }\n}\n\nexport async function handleFileAddUnlink(\n file: string,\n server: ViteDevServer,\n isUnlink = false\n): Promise {\n const modules = [...(server.moduleGraph.getModulesByFile(file) ?? [])]\n if (isUnlink && file in server._globImporters) {\n delete server._globImporters[file]\n } else {\n for (const i in server._globImporters) {\n const { module, importGlobs } = server._globImporters[i]\n for (const { base, pattern } of importGlobs) {\n if (match(file, pattern) || match(path.relative(base, file), pattern)) {\n modules.push(module)\n // We use `onFileChange` to invalidate `module.file` so that subsequent `ssrLoadModule()`\n // calls get fresh glob import results with(out) the newly added(/removed) `file`.\n server.moduleGraph.onFileChange(module.file!)\n break\n }\n }\n }\n }\n if (modules.length > 0) {\n updateModules(\n getShortName(file, server.config.root),\n modules,\n Date.now(),\n server\n )\n }\n}\n\nfunction propagateUpdate(\n node: ModuleNode,\n boundaries: Set<{\n boundary: ModuleNode\n acceptedVia: ModuleNode\n }>,\n currentChain: ModuleNode[] = [node]\n): boolean /* hasDeadEnd */ {\n if (node.isSelfAccepting) {\n boundaries.add({\n boundary: node,\n acceptedVia: node\n })\n\n // additionally check for CSS importers, since a PostCSS plugin like\n // Tailwind JIT may register any file as a dependency to a CSS file.\n for (const importer of node.importers) {\n if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {\n propagateUpdate(importer, boundaries, currentChain.concat(importer))\n }\n }\n\n return false\n }\n\n if (!node.importers.size) {\n return true\n }\n\n // #3716, #3913\n // For a non-CSS file, if all of its importers are CSS files (registered via\n // PostCSS plugins) it should be considered a dead end and force full reload.\n if (\n !isCSSRequest(node.url) &&\n [...node.importers].every((i) => isCSSRequest(i.url))\n ) {\n return true\n }\n\n for (const importer of node.importers) {\n const subChain = currentChain.concat(importer)\n if (importer.acceptedHmrDeps.has(node)) {\n boundaries.add({\n boundary: importer,\n acceptedVia: node\n })\n continue\n }\n\n if (currentChain.includes(importer)) {\n // circular deps is considered dead end\n return true\n }\n\n if (propagateUpdate(importer, boundaries, subChain)) {\n return true\n }\n }\n return false\n}\n\nfunction invalidate(mod: ModuleNode, timestamp: number, seen: Set) {\n if (seen.has(mod)) {\n return\n }\n seen.add(mod)\n mod.lastHMRTimestamp = timestamp\n mod.transformResult = null\n mod.ssrModule = null\n mod.ssrTransformResult = null\n mod.importers.forEach((importer) => {\n if (!importer.acceptedHmrDeps.has(mod)) {\n invalidate(importer, timestamp, seen)\n }\n })\n}\n\nexport function handlePrunedModules(\n mods: Set,\n { ws }: ViteDevServer\n): void {\n // update the disposed modules' hmr timestamp\n // since if it's re-imported, it should re-apply side effects\n // and without the timestamp the browser will not re-import it!\n const t = Date.now()\n mods.forEach((mod) => {\n mod.lastHMRTimestamp = t\n debugHmr(`[dispose] ${chalk.dim(mod.file)}`)\n })\n ws.send({\n type: 'prune',\n paths: [...mods].map((m) => m.url)\n })\n}\n\nconst enum LexerState {\n inCall,\n inSingleQuoteString,\n inDoubleQuoteString,\n inTemplateString,\n inArray\n}\n\n/**\n * Lex import.meta.hot.accept() for accepted deps.\n * Since hot.accept() can only accept string literals or array of string\n * literals, we don't really need a heavy @babel/parse call on the entire source.\n *\n * @returns selfAccepts\n */\nexport function lexAcceptedHmrDeps(\n code: string,\n start: number,\n urls: Set<{ url: string; start: number; end: number }>\n): boolean {\n let state: LexerState = LexerState.inCall\n // the state can only be 2 levels deep so no need for a stack\n let prevState: LexerState = LexerState.inCall\n let currentDep: string = ''\n\n function addDep(index: number) {\n urls.add({\n url: currentDep,\n start: index - currentDep.length - 1,\n end: index + 1\n })\n currentDep = ''\n }\n\n for (let i = start; i < code.length; i++) {\n const char = code.charAt(i)\n switch (state) {\n case LexerState.inCall:\n case LexerState.inArray:\n if (char === `'`) {\n prevState = state\n state = LexerState.inSingleQuoteString\n } else if (char === `\"`) {\n prevState = state\n state = LexerState.inDoubleQuoteString\n } else if (char === '`') {\n prevState = state\n state = LexerState.inTemplateString\n } else if (/\\s/.test(char)) {\n continue\n } else {\n if (state === LexerState.inCall) {\n if (char === `[`) {\n state = LexerState.inArray\n } else {\n // reaching here means the first arg is neither a string literal\n // nor an Array literal (direct callback) or there is no arg\n // in both case this indicates a self-accepting module\n return true // done\n }\n } else if (state === LexerState.inArray) {\n if (char === `]`) {\n return false // done\n } else if (char === ',') {\n continue\n } else {\n error(i)\n }\n }\n }\n break\n case LexerState.inSingleQuoteString:\n if (char === `'`) {\n addDep(i)\n if (prevState === LexerState.inCall) {\n // accept('foo', ...)\n return false\n } else {\n state = prevState\n }\n } else {\n currentDep += char\n }\n break\n case LexerState.inDoubleQuoteString:\n if (char === `\"`) {\n addDep(i)\n if (prevState === LexerState.inCall) {\n // accept('foo', ...)\n return false\n } else {\n state = prevState\n }\n } else {\n currentDep += char\n }\n break\n case LexerState.inTemplateString:\n if (char === '`') {\n addDep(i)\n if (prevState === LexerState.inCall) {\n // accept('foo', ...)\n return false\n } else {\n state = prevState\n }\n } else if (char === '$' && code.charAt(i + 1) === '{') {\n error(i)\n } else {\n currentDep += char\n }\n break\n default:\n throw new Error('unknown import.meta.hot lexer state')\n }\n }\n return false\n}\n\nfunction error(pos: number) {\n const err = new Error(\n `import.meta.accept() can only accept string literals or an ` +\n `Array of string literals.`\n ) as RollupError\n err.pos = pos\n throw err\n}\n\n// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file\n// change event and sometimes this can be too early and get an empty buffer.\n// Poll until the file's modified time has changed before reading again.\nasync function readModifiedFile(file: string): Promise {\n const content = fs.readFileSync(file, 'utf-8')\n if (!content) {\n const mtime = fs.statSync(file).mtimeMs\n await new Promise((r) => {\n let n = 0\n const poll = async () => {\n n++\n const newMtime = fs.statSync(file).mtimeMs\n if (newMtime !== mtime || n > 10) {\n r(0)\n } else {\n setTimeout(poll, 10)\n }\n }\n setTimeout(poll, 10)\n })\n return fs.readFileSync(file, 'utf-8')\n } else {\n return content\n }\n}\n\nasync function restartServer(server: ViteDevServer) {\n // @ts-ignore\n global.__vite_start_time = performance.now()\n const { port } = server.config.server\n\n await server.close()\n\n let newServer = null\n try {\n newServer = await createServer(server.config.inlineConfig)\n } catch (err: any) {\n server.config.logger.error(err.message, {\n timestamp: true\n })\n return\n }\n\n for (const key in newServer) {\n if (key !== 'app') {\n // @ts-ignore\n server[key] = newServer[key]\n }\n }\n if (!server.config.server.middlewareMode) {\n await server.listen(port, true)\n } else {\n server.config.logger.info('server restarted.', { timestamp: true })\n }\n}\n","'use strict';\nconst fs = require('fs');\n\nlet isDocker;\n\nfunction hasDockerEnv() {\n\ttry {\n\t\tfs.statSync('/.dockerenv');\n\t\treturn true;\n\t} catch (_) {\n\t\treturn false;\n\t}\n}\n\nfunction hasDockerCGroup() {\n\ttry {\n\t\treturn fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');\n\t} catch (_) {\n\t\treturn false;\n\t}\n}\n\nmodule.exports = () => {\n\tif (isDocker === undefined) {\n\t\tisDocker = hasDockerEnv() || hasDockerCGroup();\n\t}\n\n\treturn isDocker;\n};\n","'use strict';\nconst os = require('os');\nconst fs = require('fs');\nconst isDocker = require('is-docker');\n\nconst isWsl = () => {\n\tif (process.platform !== 'linux') {\n\t\treturn false;\n\t}\n\n\tif (os.release().toLowerCase().includes('microsoft')) {\n\t\tif (isDocker()) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\ttry {\n\t\treturn fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?\n\t\t\t!isDocker() : false;\n\t} catch (_) {\n\t\treturn false;\n\t}\n};\n\nif (process.env.__IS_WSL_TEST__) {\n\tmodule.exports = isWsl;\n} else {\n\tmodule.exports = isWsl();\n}\n","'use strict';\nmodule.exports = (object, propertyName, fn) => {\n\tconst define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});\n\n\tObject.defineProperty(object, propertyName, {\n\t\tconfigurable: true,\n\t\tenumerable: true,\n\t\tget() {\n\t\t\tconst result = fn();\n\t\t\tdefine(result);\n\t\t\treturn result;\n\t\t},\n\t\tset(value) {\n\t\t\tdefine(value);\n\t\t}\n\t});\n\n\treturn object;\n};\n","const path = require('path');\nconst childProcess = require('child_process');\nconst {promises: fs, constants: fsConstants} = require('fs');\nconst isWsl = require('is-wsl');\nconst isDocker = require('is-docker');\nconst defineLazyProperty = require('define-lazy-prop');\n\n// Path to included `xdg-open`.\nconst localXdgOpenPath = path.join(__dirname, 'xdg-open');\n\nconst {platform, arch} = process;\n\n/**\nGet the mount point for fixed drives in WSL.\n\n@inner\n@returns {string} The mount point.\n*/\nconst getWslDrivesMountPoint = (() => {\n\t// Default value for \"root\" param\n\t// according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config\n\tconst defaultMountPoint = '/mnt/';\n\n\tlet mountPoint;\n\n\treturn async function () {\n\t\tif (mountPoint) {\n\t\t\t// Return memoized mount point value\n\t\t\treturn mountPoint;\n\t\t}\n\n\t\tconst configFilePath = '/etc/wsl.conf';\n\n\t\tlet isConfigFileExists = false;\n\t\ttry {\n\t\t\tawait fs.access(configFilePath, fsConstants.F_OK);\n\t\t\tisConfigFileExists = true;\n\t\t} catch {}\n\n\t\tif (!isConfigFileExists) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tconst configContent = await fs.readFile(configFilePath, {encoding: 'utf8'});\n\t\tconst configMountPoint = /(?.*)/g.exec(configContent);\n\n\t\tif (!configMountPoint) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tmountPoint = configMountPoint.groups.mountPoint.trim();\n\t\tmountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;\n\n\t\treturn mountPoint;\n\t};\n})();\n\nconst pTryEach = async (array, mapper) => {\n\tlet latestError;\n\n\tfor (const item of array) {\n\t\ttry {\n\t\t\treturn await mapper(item); // eslint-disable-line no-await-in-loop\n\t\t} catch (error) {\n\t\t\tlatestError = error;\n\t\t}\n\t}\n\n\tthrow latestError;\n};\n\nconst open = async (target, options) => {\n\tif (typeof target !== 'string') {\n\t\tthrow new TypeError('Expected a `target`');\n\t}\n\n\toptions = {\n\t\twait: false,\n\t\tbackground: false,\n\t\tnewInstance: false,\n\t\tallowNonzeroExitCode: false,\n\t\t...options\n\t};\n\n\tif (Array.isArray(options.app)) {\n\t\treturn pTryEach(options.app, singleApp => open(target, {\n\t\t\t...options,\n\t\t\tapp: singleApp\n\t\t}));\n\t}\n\n\tlet {name: app, arguments: appArguments = []} = options.app || {};\n\tappArguments = [...appArguments];\n\n\tif (Array.isArray(app)) {\n\t\treturn pTryEach(app, appName => open(target, {\n\t\t\t...options,\n\t\t\tapp: {\n\t\t\t\tname: appName,\n\t\t\t\targuments: appArguments\n\t\t\t}\n\t\t}));\n\t}\n\n\tlet command;\n\tconst cliArguments = [];\n\tconst childProcessOptions = {};\n\n\tif (platform === 'darwin') {\n\t\tcommand = 'open';\n\n\t\tif (options.wait) {\n\t\t\tcliArguments.push('--wait-apps');\n\t\t}\n\n\t\tif (options.background) {\n\t\t\tcliArguments.push('--background');\n\t\t}\n\n\t\tif (options.newInstance) {\n\t\t\tcliArguments.push('--new');\n\t\t}\n\n\t\tif (app) {\n\t\t\tcliArguments.push('-a', app);\n\t\t}\n\t} else if (platform === 'win32' || (isWsl && !isDocker())) {\n\t\tconst mountPoint = await getWslDrivesMountPoint();\n\n\t\tcommand = isWsl ?\n\t\t\t`${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :\n\t\t\t`${process.env.SYSTEMROOT}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell`;\n\n\t\tcliArguments.push(\n\t\t\t'-NoProfile',\n\t\t\t'-NonInteractive',\n\t\t\t'–ExecutionPolicy',\n\t\t\t'Bypass',\n\t\t\t'-EncodedCommand'\n\t\t);\n\n\t\tif (!isWsl) {\n\t\t\tchildProcessOptions.windowsVerbatimArguments = true;\n\t\t}\n\n\t\tconst encodedArguments = ['Start'];\n\n\t\tif (options.wait) {\n\t\t\tencodedArguments.push('-Wait');\n\t\t}\n\n\t\tif (app) {\n\t\t\t// Double quote with double quotes to ensure the inner quotes are passed through.\n\t\t\t// Inner quotes are delimited for PowerShell interpretation with backticks.\n\t\t\tencodedArguments.push(`\"\\`\"${app}\\`\"\"`, '-ArgumentList');\n\t\t\tappArguments.unshift(target);\n\t\t} else {\n\t\t\tencodedArguments.push(`\"${target}\"`);\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tappArguments = appArguments.map(arg => `\"\\`\"${arg}\\`\"\"`);\n\t\t\tencodedArguments.push(appArguments.join(','));\n\t\t}\n\n\t\t// Using Base64-encoded command, accepted by PowerShell, to allow special characters.\n\t\ttarget = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');\n\t} else {\n\t\tif (app) {\n\t\t\tcommand = app;\n\t\t} else {\n\t\t\t// When bundled by Webpack, there's no actual package file path and no local `xdg-open`.\n\t\t\tconst isBundled = !__dirname || __dirname === '/';\n\n\t\t\t// Check if local `xdg-open` exists and is executable.\n\t\t\tlet exeLocalXdgOpen = false;\n\t\t\ttry {\n\t\t\t\tawait fs.access(localXdgOpenPath, fsConstants.X_OK);\n\t\t\t\texeLocalXdgOpen = true;\n\t\t\t} catch {}\n\n\t\t\tconst useSystemXdgOpen = process.versions.electron ||\n\t\t\t\tplatform === 'android' || isBundled || !exeLocalXdgOpen;\n\t\t\tcommand = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tcliArguments.push(...appArguments);\n\t\t}\n\n\t\tif (!options.wait) {\n\t\t\t// `xdg-open` will block the process unless stdio is ignored\n\t\t\t// and it's detached from the parent even if it's unref'd.\n\t\t\tchildProcessOptions.stdio = 'ignore';\n\t\t\tchildProcessOptions.detached = true;\n\t\t}\n\t}\n\n\tcliArguments.push(target);\n\n\tif (platform === 'darwin' && appArguments.length > 0) {\n\t\tcliArguments.push('--args', ...appArguments);\n\t}\n\n\tconst subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);\n\n\tif (options.wait) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tsubprocess.once('error', reject);\n\n\t\t\tsubprocess.once('close', exitCode => {\n\t\t\t\tif (options.allowNonzeroExitCode && exitCode > 0) {\n\t\t\t\t\treject(new Error(`Exited with code ${exitCode}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresolve(subprocess);\n\t\t\t});\n\t\t});\n\t}\n\n\tsubprocess.unref();\n\n\treturn subprocess;\n};\n\nfunction detectArchBinary(binary) {\n\tif (typeof binary === 'string' || Array.isArray(binary)) {\n\t\treturn binary;\n\t}\n\n\tconst {[arch]: archBinary} = binary;\n\n\tif (!archBinary) {\n\t\tthrow new Error(`${arch} is not supported`);\n\t}\n\n\treturn archBinary;\n}\n\nfunction detectPlatformBinary({[platform]: platformBinary}, {wsl}) {\n\tif (wsl && isWsl) {\n\t\treturn detectArchBinary(wsl);\n\t}\n\n\tif (!platformBinary) {\n\t\tthrow new Error(`${platform} is not supported`);\n\t}\n\n\treturn detectArchBinary(platformBinary);\n}\n\nconst apps = {};\n\ndefineLazyProperty(apps, 'chrome', () => detectPlatformBinary({\n\tdarwin: 'google chrome',\n\twin32: 'chrome',\n\tlinux: ['google-chrome', 'google-chrome-stable']\n}, {\n\twsl: {\n\t\tia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',\n\t\tx64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']\n\t}\n}));\n\ndefineLazyProperty(apps, 'firefox', () => detectPlatformBinary({\n\tdarwin: 'firefox',\n\twin32: 'C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe',\n\tlinux: 'firefox'\n}, {\n\twsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'\n}));\n\ndefineLazyProperty(apps, 'edge', () => detectPlatformBinary({\n\tdarwin: 'microsoft edge',\n\twin32: 'msedge',\n\tlinux: 'microsoft-edge'\n}, {\n\twsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'\n}));\n\nopen.apps = apps;\n\nmodule.exports = open;\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n","const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(\\\\*)\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(\\\\*)$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed, 'spawn');\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","'use strict';\n\nmodule.exports = input => {\n\tconst LF = typeof input === 'string' ? '\\n' : '\\n'.charCodeAt();\n\tconst CR = typeof input === 'string' ? '\\r' : '\\r'.charCodeAt();\n\n\tif (input[input.length - 1] === LF) {\n\t\tinput = input.slice(0, input.length - 1);\n\t}\n\n\tif (input[input.length - 1] === CR) {\n\t\tinput = input.slice(0, input.length - 1);\n\t}\n\n\treturn input;\n};\n","'use strict';\nconst path = require('path');\nconst pathKey = require('path-key');\n\nconst npmRunPath = options => {\n\toptions = {\n\t\tcwd: process.cwd(),\n\t\tpath: process.env[pathKey()],\n\t\texecPath: process.execPath,\n\t\t...options\n\t};\n\n\tlet previous;\n\tlet cwdPath = path.resolve(options.cwd);\n\tconst result = [];\n\n\twhile (previous !== cwdPath) {\n\t\tresult.push(path.join(cwdPath, 'node_modules/.bin'));\n\t\tprevious = cwdPath;\n\t\tcwdPath = path.resolve(cwdPath, '..');\n\t}\n\n\t// Ensure the running `node` binary is used\n\tconst execPathDir = path.resolve(options.cwd, options.execPath, '..');\n\tresult.push(execPathDir);\n\n\treturn result.concat(options.path).join(path.delimiter);\n};\n\nmodule.exports = npmRunPath;\n// TODO: Remove this for the next major release\nmodule.exports.default = npmRunPath;\n\nmodule.exports.env = options => {\n\toptions = {\n\t\tenv: process.env,\n\t\t...options\n\t};\n\n\tconst env = {...options.env};\n\tconst path = pathKey({env});\n\n\toptions.path = env[path];\n\tenv[path] = module.exports(options);\n\n\treturn env;\n};\n","'use strict';\n\nconst mimicFn = (to, from) => {\n\tfor (const prop of Reflect.ownKeys(from)) {\n\t\tObject.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));\n\t}\n\n\treturn to;\n};\n\nmodule.exports = mimicFn;\n// TODO: Remove this for the next major release\nmodule.exports.default = mimicFn;\n","'use strict';\nconst mimicFn = require('mimic-fn');\n\nconst calledFunctions = new WeakMap();\n\nconst onetime = (function_, options = {}) => {\n\tif (typeof function_ !== 'function') {\n\t\tthrow new TypeError('Expected a function');\n\t}\n\n\tlet returnValue;\n\tlet callCount = 0;\n\tconst functionName = function_.displayName || function_.name || '';\n\n\tconst onetime = function (...arguments_) {\n\t\tcalledFunctions.set(onetime, ++callCount);\n\n\t\tif (callCount === 1) {\n\t\t\treturnValue = function_.apply(this, arguments_);\n\t\t\tfunction_ = null;\n\t\t} else if (options.throw === true) {\n\t\t\tthrow new Error(`Function \\`${functionName}\\` can only be called once`);\n\t\t}\n\n\t\treturn returnValue;\n\t};\n\n\tmimicFn(onetime, function_);\n\tcalledFunctions.set(onetime, callCount);\n\n\treturn onetime;\n};\n\nmodule.exports = onetime;\n// TODO: Remove this for the next major release\nmodule.exports.default = onetime;\n\nmodule.exports.callCount = function_ => {\n\tif (!calledFunctions.has(function_)) {\n\t\tthrow new Error(`The given function \\`${function_.name}\\` is not wrapped by the \\`onetime\\` package`);\n\t}\n\n\treturn calledFunctions.get(function_);\n};\n","\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:true});exports.SIGNALS=void 0;\n\nconst SIGNALS=[\n{\nname:\"SIGHUP\",\nnumber:1,\naction:\"terminate\",\ndescription:\"Terminal closed\",\nstandard:\"posix\"},\n\n{\nname:\"SIGINT\",\nnumber:2,\naction:\"terminate\",\ndescription:\"User interruption with CTRL-C\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGQUIT\",\nnumber:3,\naction:\"core\",\ndescription:\"User interruption with CTRL-\\\\\",\nstandard:\"posix\"},\n\n{\nname:\"SIGILL\",\nnumber:4,\naction:\"core\",\ndescription:\"Invalid machine instruction\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGTRAP\",\nnumber:5,\naction:\"core\",\ndescription:\"Debugger breakpoint\",\nstandard:\"posix\"},\n\n{\nname:\"SIGABRT\",\nnumber:6,\naction:\"core\",\ndescription:\"Aborted\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGIOT\",\nnumber:6,\naction:\"core\",\ndescription:\"Aborted\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGBUS\",\nnumber:7,\naction:\"core\",\ndescription:\n\"Bus error due to misaligned, non-existing address or paging error\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGEMT\",\nnumber:7,\naction:\"terminate\",\ndescription:\"Command should be emulated but is not implemented\",\nstandard:\"other\"},\n\n{\nname:\"SIGFPE\",\nnumber:8,\naction:\"core\",\ndescription:\"Floating point arithmetic error\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGKILL\",\nnumber:9,\naction:\"terminate\",\ndescription:\"Forced termination\",\nstandard:\"posix\",\nforced:true},\n\n{\nname:\"SIGUSR1\",\nnumber:10,\naction:\"terminate\",\ndescription:\"Application-specific signal\",\nstandard:\"posix\"},\n\n{\nname:\"SIGSEGV\",\nnumber:11,\naction:\"core\",\ndescription:\"Segmentation fault\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGUSR2\",\nnumber:12,\naction:\"terminate\",\ndescription:\"Application-specific signal\",\nstandard:\"posix\"},\n\n{\nname:\"SIGPIPE\",\nnumber:13,\naction:\"terminate\",\ndescription:\"Broken pipe or socket\",\nstandard:\"posix\"},\n\n{\nname:\"SIGALRM\",\nnumber:14,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"posix\"},\n\n{\nname:\"SIGTERM\",\nnumber:15,\naction:\"terminate\",\ndescription:\"Termination\",\nstandard:\"ansi\"},\n\n{\nname:\"SIGSTKFLT\",\nnumber:16,\naction:\"terminate\",\ndescription:\"Stack is empty or overflowed\",\nstandard:\"other\"},\n\n{\nname:\"SIGCHLD\",\nnumber:17,\naction:\"ignore\",\ndescription:\"Child process terminated, paused or unpaused\",\nstandard:\"posix\"},\n\n{\nname:\"SIGCLD\",\nnumber:17,\naction:\"ignore\",\ndescription:\"Child process terminated, paused or unpaused\",\nstandard:\"other\"},\n\n{\nname:\"SIGCONT\",\nnumber:18,\naction:\"unpause\",\ndescription:\"Unpaused\",\nstandard:\"posix\",\nforced:true},\n\n{\nname:\"SIGSTOP\",\nnumber:19,\naction:\"pause\",\ndescription:\"Paused\",\nstandard:\"posix\",\nforced:true},\n\n{\nname:\"SIGTSTP\",\nnumber:20,\naction:\"pause\",\ndescription:\"Paused using CTRL-Z or \\\"suspend\\\"\",\nstandard:\"posix\"},\n\n{\nname:\"SIGTTIN\",\nnumber:21,\naction:\"pause\",\ndescription:\"Background process cannot read terminal input\",\nstandard:\"posix\"},\n\n{\nname:\"SIGBREAK\",\nnumber:21,\naction:\"terminate\",\ndescription:\"User interruption with CTRL-BREAK\",\nstandard:\"other\"},\n\n{\nname:\"SIGTTOU\",\nnumber:22,\naction:\"pause\",\ndescription:\"Background process cannot write to terminal output\",\nstandard:\"posix\"},\n\n{\nname:\"SIGURG\",\nnumber:23,\naction:\"ignore\",\ndescription:\"Socket received out-of-band data\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGXCPU\",\nnumber:24,\naction:\"core\",\ndescription:\"Process timed out\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGXFSZ\",\nnumber:25,\naction:\"core\",\ndescription:\"File too big\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGVTALRM\",\nnumber:26,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGPROF\",\nnumber:27,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGWINCH\",\nnumber:28,\naction:\"ignore\",\ndescription:\"Terminal window size changed\",\nstandard:\"bsd\"},\n\n{\nname:\"SIGIO\",\nnumber:29,\naction:\"terminate\",\ndescription:\"I/O is available\",\nstandard:\"other\"},\n\n{\nname:\"SIGPOLL\",\nnumber:29,\naction:\"terminate\",\ndescription:\"Watched event\",\nstandard:\"other\"},\n\n{\nname:\"SIGINFO\",\nnumber:29,\naction:\"ignore\",\ndescription:\"Request for process information\",\nstandard:\"other\"},\n\n{\nname:\"SIGPWR\",\nnumber:30,\naction:\"terminate\",\ndescription:\"Device running out of power\",\nstandard:\"systemv\"},\n\n{\nname:\"SIGSYS\",\nnumber:31,\naction:\"core\",\ndescription:\"Invalid system call\",\nstandard:\"other\"},\n\n{\nname:\"SIGUNUSED\",\nnumber:31,\naction:\"terminate\",\ndescription:\"Invalid system call\",\nstandard:\"other\"}];exports.SIGNALS=SIGNALS;\n//# sourceMappingURL=core.js.map","\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:true});exports.SIGRTMAX=exports.getRealtimeSignals=void 0;\nconst getRealtimeSignals=function(){\nconst length=SIGRTMAX-SIGRTMIN+1;\nreturn Array.from({length},getRealtimeSignal);\n};exports.getRealtimeSignals=getRealtimeSignals;\n\nconst getRealtimeSignal=function(value,index){\nreturn{\nname:`SIGRT${index+1}`,\nnumber:SIGRTMIN+index,\naction:\"terminate\",\ndescription:\"Application-specific signal (realtime)\",\nstandard:\"posix\"};\n\n};\n\nconst SIGRTMIN=34;\nconst SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX;\n//# sourceMappingURL=realtime.js.map","\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:true});exports.getSignals=void 0;var _os=require(\"os\");\n\nvar _core=require(\"./core.js\");\nvar _realtime=require(\"./realtime.js\");\n\n\n\nconst getSignals=function(){\nconst realtimeSignals=(0,_realtime.getRealtimeSignals)();\nconst signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal);\nreturn signals;\n};exports.getSignals=getSignals;\n\n\n\n\n\n\n\nconst normalizeSignal=function({\nname,\nnumber:defaultNumber,\ndescription,\naction,\nforced=false,\nstandard})\n{\nconst{\nsignals:{[name]:constantSignal}}=\n_os.constants;\nconst supported=constantSignal!==undefined;\nconst number=supported?constantSignal:defaultNumber;\nreturn{name,number,description,supported,action,forced,standard};\n};\n//# sourceMappingURL=signals.js.map","\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:true});exports.signalsByNumber=exports.signalsByName=void 0;var _os=require(\"os\");\n\nvar _signals=require(\"./signals.js\");\nvar _realtime=require(\"./realtime.js\");\n\n\n\nconst getSignalsByName=function(){\nconst signals=(0,_signals.getSignals)();\nreturn signals.reduce(getSignalByName,{});\n};\n\nconst getSignalByName=function(\nsignalByNameMemo,\n{name,number,description,supported,action,forced,standard})\n{\nreturn{\n...signalByNameMemo,\n[name]:{name,number,description,supported,action,forced,standard}};\n\n};\n\nconst signalsByName=getSignalsByName();exports.signalsByName=signalsByName;\n\n\n\n\nconst getSignalsByNumber=function(){\nconst signals=(0,_signals.getSignals)();\nconst length=_realtime.SIGRTMAX+1;\nconst signalsA=Array.from({length},(value,number)=>\ngetSignalByNumber(number,signals));\n\nreturn Object.assign({},...signalsA);\n};\n\nconst getSignalByNumber=function(number,signals){\nconst signal=findSignalByNumber(number,signals);\n\nif(signal===undefined){\nreturn{};\n}\n\nconst{name,description,supported,action,forced,standard}=signal;\nreturn{\n[number]:{\nname,\nnumber,\ndescription,\nsupported,\naction,\nforced,\nstandard}};\n\n\n};\n\n\n\nconst findSignalByNumber=function(number,signals){\nconst signal=signals.find(({name})=>_os.constants.signals[name]===number);\n\nif(signal!==undefined){\nreturn signal;\n}\n\nreturn signals.find(signalA=>signalA.number===number);\n};\n\nconst signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber;\n//# sourceMappingURL=main.js.map","'use strict';\nconst {signalsByName} = require('human-signals');\n\nconst getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {\n\tif (timedOut) {\n\t\treturn `timed out after ${timeout} milliseconds`;\n\t}\n\n\tif (isCanceled) {\n\t\treturn 'was canceled';\n\t}\n\n\tif (errorCode !== undefined) {\n\t\treturn `failed with ${errorCode}`;\n\t}\n\n\tif (signal !== undefined) {\n\t\treturn `was killed with ${signal} (${signalDescription})`;\n\t}\n\n\tif (exitCode !== undefined) {\n\t\treturn `failed with exit code ${exitCode}`;\n\t}\n\n\treturn 'failed';\n};\n\nconst makeError = ({\n\tstdout,\n\tstderr,\n\tall,\n\terror,\n\tsignal,\n\texitCode,\n\tcommand,\n\tescapedCommand,\n\ttimedOut,\n\tisCanceled,\n\tkilled,\n\tparsed: {options: {timeout}}\n}) => {\n\t// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.\n\t// We normalize them to `undefined`\n\texitCode = exitCode === null ? undefined : exitCode;\n\tsignal = signal === null ? undefined : signal;\n\tconst signalDescription = signal === undefined ? undefined : signalsByName[signal].description;\n\n\tconst errorCode = error && error.code;\n\n\tconst prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});\n\tconst execaMessage = `Command ${prefix}: ${command}`;\n\tconst isError = Object.prototype.toString.call(error) === '[object Error]';\n\tconst shortMessage = isError ? `${execaMessage}\\n${error.message}` : execaMessage;\n\tconst message = [shortMessage, stderr, stdout].filter(Boolean).join('\\n');\n\n\tif (isError) {\n\t\terror.originalMessage = error.message;\n\t\terror.message = message;\n\t} else {\n\t\terror = new Error(message);\n\t}\n\n\terror.shortMessage = shortMessage;\n\terror.command = command;\n\terror.escapedCommand = escapedCommand;\n\terror.exitCode = exitCode;\n\terror.signal = signal;\n\terror.signalDescription = signalDescription;\n\terror.stdout = stdout;\n\terror.stderr = stderr;\n\n\tif (all !== undefined) {\n\t\terror.all = all;\n\t}\n\n\tif ('bufferedData' in error) {\n\t\tdelete error.bufferedData;\n\t}\n\n\terror.failed = true;\n\terror.timedOut = Boolean(timedOut);\n\terror.isCanceled = isCanceled;\n\terror.killed = killed && !timedOut;\n\n\treturn error;\n};\n\nmodule.exports = makeError;\n","'use strict';\nconst aliases = ['stdin', 'stdout', 'stderr'];\n\nconst hasAlias = options => aliases.some(alias => options[alias] !== undefined);\n\nconst normalizeStdio = options => {\n\tif (!options) {\n\t\treturn;\n\t}\n\n\tconst {stdio} = options;\n\n\tif (stdio === undefined) {\n\t\treturn aliases.map(alias => options[alias]);\n\t}\n\n\tif (hasAlias(options)) {\n\t\tthrow new Error(`It's not possible to provide \\`stdio\\` in combination with one of ${aliases.map(alias => `\\`${alias}\\``).join(', ')}`);\n\t}\n\n\tif (typeof stdio === 'string') {\n\t\treturn stdio;\n\t}\n\n\tif (!Array.isArray(stdio)) {\n\t\tthrow new TypeError(`Expected \\`stdio\\` to be of type \\`string\\` or \\`Array\\`, got \\`${typeof stdio}\\``);\n\t}\n\n\tconst length = Math.max(stdio.length, aliases.length);\n\treturn Array.from({length}, (value, index) => stdio[index]);\n};\n\nmodule.exports = normalizeStdio;\n\n// `ipc` is pushed unless it is already present\nmodule.exports.node = options => {\n\tconst stdio = normalizeStdio(options);\n\n\tif (stdio === 'ipc') {\n\t\treturn 'ipc';\n\t}\n\n\tif (stdio === undefined || typeof stdio === 'string') {\n\t\treturn [stdio, stdio, stdio, 'ipc'];\n\t}\n\n\tif (stdio.includes('ipc')) {\n\t\treturn stdio;\n\t}\n\n\treturn [...stdio, 'ipc'];\n};\n","// This is not the set of all possible signals.\n//\n// It IS, however, the set of all signals that trigger\n// an exit on either Linux or BSD systems. Linux is a\n// superset of the signal names supported on BSD, and\n// the unknown signals just fail to register, so we can\n// catch that easily enough.\n//\n// Don't bother with SIGKILL. It's uncatchable, which\n// means that we can't fire any callbacks anyway.\n//\n// If a user does happen to register a handler on a non-\n// fatal signal like SIGWINCH or something, and then\n// exit, it'll end up firing `process.emit('exit')`, so\n// the handler will be fired anyway.\n//\n// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n// artificially, inherently leave the process in a\n// state from which it is not safe to try and enter JS\n// listeners.\nmodule.exports = [\n 'SIGABRT',\n 'SIGALRM',\n 'SIGHUP',\n 'SIGINT',\n 'SIGTERM'\n]\n\nif (process.platform !== 'win32') {\n module.exports.push(\n 'SIGVTALRM',\n 'SIGXCPU',\n 'SIGXFSZ',\n 'SIGUSR2',\n 'SIGTRAP',\n 'SIGSYS',\n 'SIGQUIT',\n 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n )\n}\n\nif (process.platform === 'linux') {\n module.exports.push(\n 'SIGIO',\n 'SIGPOLL',\n 'SIGPWR',\n 'SIGSTKFLT',\n 'SIGUNUSED'\n )\n}\n","// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nvar process = global.process\n// some kind of non-node environment, just no-op\nif (typeof process !== 'object' || !process) {\n module.exports = () => {}\n} else {\n var assert = require('assert')\n var signals = require('./signals.js')\n var isWin = /^win/i.test(process.platform)\n\n var EE = require('events')\n /* istanbul ignore if */\n if (typeof EE !== 'function') {\n EE = EE.EventEmitter\n }\n\n var emitter\n if (process.__signal_exit_emitter__) {\n emitter = process.__signal_exit_emitter__\n } else {\n emitter = process.__signal_exit_emitter__ = new EE()\n emitter.count = 0\n emitter.emitted = {}\n }\n\n // Because this emitter is a global, we have to check to see if a\n // previous version of this library failed to enable infinite listeners.\n // I know what you're about to say. But literally everything about\n // signal-exit is a compromise with evil. Get used to it.\n if (!emitter.infinite) {\n emitter.setMaxListeners(Infinity)\n emitter.infinite = true\n }\n\n module.exports = function (cb, opts) {\n if (global.process !== process) {\n return\n }\n assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler')\n\n if (loaded === false) {\n load()\n }\n\n var ev = 'exit'\n if (opts && opts.alwaysLast) {\n ev = 'afterexit'\n }\n\n var remove = function () {\n emitter.removeListener(ev, cb)\n if (emitter.listeners('exit').length === 0 &&\n emitter.listeners('afterexit').length === 0) {\n unload()\n }\n }\n emitter.on(ev, cb)\n\n return remove\n }\n\n var unload = function unload () {\n if (!loaded || global.process !== process) {\n return\n }\n loaded = false\n\n signals.forEach(function (sig) {\n try {\n process.removeListener(sig, sigListeners[sig])\n } catch (er) {}\n })\n process.emit = originalProcessEmit\n process.reallyExit = originalProcessReallyExit\n emitter.count -= 1\n }\n module.exports.unload = unload\n\n var emit = function emit (event, code, signal) {\n if (emitter.emitted[event]) {\n return\n }\n emitter.emitted[event] = true\n emitter.emit(event, code, signal)\n }\n\n // { : , ... }\n var sigListeners = {}\n signals.forEach(function (sig) {\n sigListeners[sig] = function listener () {\n if (process !== global.process) {\n return\n }\n // If there are no other listeners, an exit is coming!\n // Simplest way: remove us and then re-send the signal.\n // We know that this will kill the process, so we can\n // safely emit now.\n var listeners = process.listeners(sig)\n if (listeners.length === emitter.count) {\n unload()\n emit('exit', null, sig)\n /* istanbul ignore next */\n emit('afterexit', null, sig)\n /* istanbul ignore next */\n if (isWin && sig === 'SIGHUP') {\n // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n // so use a supported signal instead\n sig = 'SIGINT'\n }\n process.kill(process.pid, sig)\n }\n }\n })\n\n module.exports.signals = function () {\n return signals\n }\n\n var loaded = false\n\n var load = function load () {\n if (loaded || process !== global.process) {\n return\n }\n loaded = true\n\n // This is the number of onSignalExit's that are in play.\n // It's important so that we can count the correct number of\n // listeners on signals, and don't wait for the other one to\n // handle it instead of us.\n emitter.count += 1\n\n signals = signals.filter(function (sig) {\n try {\n process.on(sig, sigListeners[sig])\n return true\n } catch (er) {\n return false\n }\n })\n\n process.emit = processEmit\n process.reallyExit = processReallyExit\n }\n module.exports.load = load\n\n var originalProcessReallyExit = process.reallyExit\n var processReallyExit = function processReallyExit (code) {\n if (process !== global.process) {\n return\n }\n process.exitCode = code || 0\n emit('exit', process.exitCode, null)\n /* istanbul ignore next */\n emit('afterexit', process.exitCode, null)\n /* istanbul ignore next */\n originalProcessReallyExit.call(process, process.exitCode)\n }\n\n var originalProcessEmit = process.emit\n var processEmit = function processEmit (ev, arg) {\n if (ev === 'exit' && process === global.process) {\n if (arg !== undefined) {\n process.exitCode = arg\n }\n var ret = originalProcessEmit.apply(this, arguments)\n emit('exit', process.exitCode, null)\n /* istanbul ignore next */\n emit('afterexit', process.exitCode, null)\n return ret\n } else {\n return originalProcessEmit.apply(this, arguments)\n }\n }\n}\n","'use strict';\nconst os = require('os');\nconst onExit = require('signal-exit');\n\nconst DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;\n\n// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior\nconst spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {\n\tconst killResult = kill(signal);\n\tsetKillTimeout(kill, signal, options, killResult);\n\treturn killResult;\n};\n\nconst setKillTimeout = (kill, signal, options, killResult) => {\n\tif (!shouldForceKill(signal, options, killResult)) {\n\t\treturn;\n\t}\n\n\tconst timeout = getForceKillAfterTimeout(options);\n\tconst t = setTimeout(() => {\n\t\tkill('SIGKILL');\n\t}, timeout);\n\n\t// Guarded because there's no `.unref()` when `execa` is used in the renderer\n\t// process in Electron. This cannot be tested since we don't run tests in\n\t// Electron.\n\t// istanbul ignore else\n\tif (t.unref) {\n\t\tt.unref();\n\t}\n};\n\nconst shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {\n\treturn isSigterm(signal) && forceKillAfterTimeout !== false && killResult;\n};\n\nconst isSigterm = signal => {\n\treturn signal === os.constants.signals.SIGTERM ||\n\t\t(typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');\n};\n\nconst getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {\n\tif (forceKillAfterTimeout === true) {\n\t\treturn DEFAULT_FORCE_KILL_TIMEOUT;\n\t}\n\n\tif (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {\n\t\tthrow new TypeError(`Expected the \\`forceKillAfterTimeout\\` option to be a non-negative integer, got \\`${forceKillAfterTimeout}\\` (${typeof forceKillAfterTimeout})`);\n\t}\n\n\treturn forceKillAfterTimeout;\n};\n\n// `childProcess.cancel()`\nconst spawnedCancel = (spawned, context) => {\n\tconst killResult = spawned.kill();\n\n\tif (killResult) {\n\t\tcontext.isCanceled = true;\n\t}\n};\n\nconst timeoutKill = (spawned, signal, reject) => {\n\tspawned.kill(signal);\n\treject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));\n};\n\n// `timeout` option handling\nconst setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {\n\tif (timeout === 0 || timeout === undefined) {\n\t\treturn spawnedPromise;\n\t}\n\n\tlet timeoutId;\n\tconst timeoutPromise = new Promise((resolve, reject) => {\n\t\ttimeoutId = setTimeout(() => {\n\t\t\ttimeoutKill(spawned, killSignal, reject);\n\t\t}, timeout);\n\t});\n\n\tconst safeSpawnedPromise = spawnedPromise.finally(() => {\n\t\tclearTimeout(timeoutId);\n\t});\n\n\treturn Promise.race([timeoutPromise, safeSpawnedPromise]);\n};\n\nconst validateTimeout = ({timeout}) => {\n\tif (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {\n\t\tthrow new TypeError(`Expected the \\`timeout\\` option to be a non-negative integer, got \\`${timeout}\\` (${typeof timeout})`);\n\t}\n};\n\n// `cleanup` option handling\nconst setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {\n\tif (!cleanup || detached) {\n\t\treturn timedPromise;\n\t}\n\n\tconst removeExitHandler = onExit(() => {\n\t\tspawned.kill();\n\t});\n\n\treturn timedPromise.finally(() => {\n\t\tremoveExitHandler();\n\t});\n};\n\nmodule.exports = {\n\tspawnedKill,\n\tspawnedCancel,\n\tsetupTimeout,\n\tvalidateTimeout,\n\tsetExitHandler\n};\n","'use strict';\n\nconst isStream = stream =>\n\tstream !== null &&\n\ttypeof stream === 'object' &&\n\ttypeof stream.pipe === 'function';\n\nisStream.writable = stream =>\n\tisStream(stream) &&\n\tstream.writable !== false &&\n\ttypeof stream._write === 'function' &&\n\ttypeof stream._writableState === 'object';\n\nisStream.readable = stream =>\n\tisStream(stream) &&\n\tstream.readable !== false &&\n\ttypeof stream._read === 'function' &&\n\ttypeof stream._readableState === 'object';\n\nisStream.duplex = stream =>\n\tisStream.writable(stream) &&\n\tisStream.readable(stream);\n\nisStream.transform = stream =>\n\tisStream.duplex(stream) &&\n\ttypeof stream._transform === 'function';\n\nmodule.exports = isStream;\n","'use strict';\nconst {PassThrough: PassThroughStream} = require('stream');\n\nmodule.exports = options => {\n\toptions = {...options};\n\n\tconst {array} = options;\n\tlet {encoding} = options;\n\tconst isBuffer = encoding === 'buffer';\n\tlet objectMode = false;\n\n\tif (array) {\n\t\tobjectMode = !(encoding || isBuffer);\n\t} else {\n\t\tencoding = encoding || 'utf8';\n\t}\n\n\tif (isBuffer) {\n\t\tencoding = null;\n\t}\n\n\tconst stream = new PassThroughStream({objectMode});\n\n\tif (encoding) {\n\t\tstream.setEncoding(encoding);\n\t}\n\n\tlet length = 0;\n\tconst chunks = [];\n\n\tstream.on('data', chunk => {\n\t\tchunks.push(chunk);\n\n\t\tif (objectMode) {\n\t\t\tlength = chunks.length;\n\t\t} else {\n\t\t\tlength += chunk.length;\n\t\t}\n\t});\n\n\tstream.getBufferedValue = () => {\n\t\tif (array) {\n\t\t\treturn chunks;\n\t\t}\n\n\t\treturn isBuffer ? Buffer.concat(chunks, length) : chunks.join('');\n\t};\n\n\tstream.getBufferedLength = () => length;\n\n\treturn stream;\n};\n","'use strict';\nconst {constants: BufferConstants} = require('buffer');\nconst stream = require('stream');\nconst {promisify} = require('util');\nconst bufferStream = require('./buffer-stream');\n\nconst streamPipelinePromisified = promisify(stream.pipeline);\n\nclass MaxBufferError extends Error {\n\tconstructor() {\n\t\tsuper('maxBuffer exceeded');\n\t\tthis.name = 'MaxBufferError';\n\t}\n}\n\nasync function getStream(inputStream, options) {\n\tif (!inputStream) {\n\t\tthrow new Error('Expected a stream');\n\t}\n\n\toptions = {\n\t\tmaxBuffer: Infinity,\n\t\t...options\n\t};\n\n\tconst {maxBuffer} = options;\n\tconst stream = bufferStream(options);\n\n\tawait new Promise((resolve, reject) => {\n\t\tconst rejectPromise = error => {\n\t\t\t// Don't retrieve an oversized buffer.\n\t\t\tif (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {\n\t\t\t\terror.bufferedData = stream.getBufferedValue();\n\t\t\t}\n\n\t\t\treject(error);\n\t\t};\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tawait streamPipelinePromisified(inputStream, stream);\n\t\t\t\tresolve();\n\t\t\t} catch (error) {\n\t\t\t\trejectPromise(error);\n\t\t\t}\n\t\t})();\n\n\t\tstream.on('data', () => {\n\t\t\tif (stream.getBufferedLength() > maxBuffer) {\n\t\t\t\trejectPromise(new MaxBufferError());\n\t\t\t}\n\t\t});\n\t});\n\n\treturn stream.getBufferedValue();\n}\n\nmodule.exports = getStream;\nmodule.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});\nmodule.exports.array = (stream, options) => getStream(stream, {...options, array: true});\nmodule.exports.MaxBufferError = MaxBufferError;\n","'use strict';\n\nconst { PassThrough } = require('stream');\n\nmodule.exports = function (/*streams...*/) {\n var sources = []\n var output = new PassThrough({objectMode: true})\n\n output.setMaxListeners(0)\n\n output.add = add\n output.isEmpty = isEmpty\n\n output.on('unpipe', remove)\n\n Array.prototype.slice.call(arguments).forEach(add)\n\n return output\n\n function add (source) {\n if (Array.isArray(source)) {\n source.forEach(add)\n return this\n }\n\n sources.push(source);\n source.once('end', remove.bind(null, source))\n source.once('error', output.emit.bind(output, 'error'))\n source.pipe(output, {end: false})\n return this\n }\n\n function isEmpty () {\n return sources.length == 0;\n }\n\n function remove (source) {\n sources = sources.filter(function (it) { return it !== source })\n if (!sources.length && output.readable) { output.end() }\n }\n}\n","'use strict';\nconst isStream = require('is-stream');\nconst getStream = require('get-stream');\nconst mergeStream = require('merge-stream');\n\n// `input` option\nconst handleInput = (spawned, input) => {\n\t// Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852\n\t// @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0\n\tif (input === undefined || spawned.stdin === undefined) {\n\t\treturn;\n\t}\n\n\tif (isStream(input)) {\n\t\tinput.pipe(spawned.stdin);\n\t} else {\n\t\tspawned.stdin.end(input);\n\t}\n};\n\n// `all` interleaves `stdout` and `stderr`\nconst makeAllStream = (spawned, {all}) => {\n\tif (!all || (!spawned.stdout && !spawned.stderr)) {\n\t\treturn;\n\t}\n\n\tconst mixed = mergeStream();\n\n\tif (spawned.stdout) {\n\t\tmixed.add(spawned.stdout);\n\t}\n\n\tif (spawned.stderr) {\n\t\tmixed.add(spawned.stderr);\n\t}\n\n\treturn mixed;\n};\n\n// On failure, `result.stdout|stderr|all` should contain the currently buffered stream\nconst getBufferedData = async (stream, streamPromise) => {\n\tif (!stream) {\n\t\treturn;\n\t}\n\n\tstream.destroy();\n\n\ttry {\n\t\treturn await streamPromise;\n\t} catch (error) {\n\t\treturn error.bufferedData;\n\t}\n};\n\nconst getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {\n\tif (!stream || !buffer) {\n\t\treturn;\n\t}\n\n\tif (encoding) {\n\t\treturn getStream(stream, {encoding, maxBuffer});\n\t}\n\n\treturn getStream.buffer(stream, {maxBuffer});\n};\n\n// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)\nconst getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {\n\tconst stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});\n\tconst stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});\n\tconst allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});\n\n\ttry {\n\t\treturn await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);\n\t} catch (error) {\n\t\treturn Promise.all([\n\t\t\t{error, signal: error.signal, timedOut: error.timedOut},\n\t\t\tgetBufferedData(stdout, stdoutPromise),\n\t\t\tgetBufferedData(stderr, stderrPromise),\n\t\t\tgetBufferedData(all, allPromise)\n\t\t]);\n\t}\n};\n\nconst validateInputSync = ({input}) => {\n\tif (isStream(input)) {\n\t\tthrow new TypeError('The `input` option cannot be a stream in sync mode');\n\t}\n};\n\nmodule.exports = {\n\thandleInput,\n\tmakeAllStream,\n\tgetSpawnedResult,\n\tvalidateInputSync\n};\n\n","'use strict';\n\nconst nativePromisePrototype = (async () => {})().constructor.prototype;\nconst descriptors = ['then', 'catch', 'finally'].map(property => [\n\tproperty,\n\tReflect.getOwnPropertyDescriptor(nativePromisePrototype, property)\n]);\n\n// The return value is a mixin of `childProcess` and `Promise`\nconst mergePromise = (spawned, promise) => {\n\tfor (const [property, descriptor] of descriptors) {\n\t\t// Starting the main `promise` is deferred to avoid consuming streams\n\t\tconst value = typeof promise === 'function' ?\n\t\t\t(...args) => Reflect.apply(descriptor.value, promise(), args) :\n\t\t\tdescriptor.value.bind(promise);\n\n\t\tReflect.defineProperty(spawned, property, {...descriptor, value});\n\t}\n\n\treturn spawned;\n};\n\n// Use promises instead of `child_process` events\nconst getSpawnedPromise = spawned => {\n\treturn new Promise((resolve, reject) => {\n\t\tspawned.on('exit', (exitCode, signal) => {\n\t\t\tresolve({exitCode, signal});\n\t\t});\n\n\t\tspawned.on('error', error => {\n\t\t\treject(error);\n\t\t});\n\n\t\tif (spawned.stdin) {\n\t\t\tspawned.stdin.on('error', error => {\n\t\t\t\treject(error);\n\t\t\t});\n\t\t}\n\t});\n};\n\nmodule.exports = {\n\tmergePromise,\n\tgetSpawnedPromise\n};\n\n","'use strict';\nconst normalizeArgs = (file, args = []) => {\n\tif (!Array.isArray(args)) {\n\t\treturn [file];\n\t}\n\n\treturn [file, ...args];\n};\n\nconst NO_ESCAPE_REGEXP = /^[\\w.-]+$/;\nconst DOUBLE_QUOTES_REGEXP = /\"/g;\n\nconst escapeArg = arg => {\n\tif (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) {\n\t\treturn arg;\n\t}\n\n\treturn `\"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\\\\"')}\"`;\n};\n\nconst joinCommand = (file, args) => {\n\treturn normalizeArgs(file, args).join(' ');\n};\n\nconst getEscapedCommand = (file, args) => {\n\treturn normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');\n};\n\nconst SPACES_REGEXP = / +/g;\n\n// Handle `execa.command()`\nconst parseCommand = command => {\n\tconst tokens = [];\n\tfor (const token of command.trim().split(SPACES_REGEXP)) {\n\t\t// Allow spaces to be escaped by a backslash if not meant as a delimiter\n\t\tconst previousToken = tokens[tokens.length - 1];\n\t\tif (previousToken && previousToken.endsWith('\\\\')) {\n\t\t\t// Merge previous token with current one\n\t\t\ttokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;\n\t\t} else {\n\t\t\ttokens.push(token);\n\t\t}\n\t}\n\n\treturn tokens;\n};\n\nmodule.exports = {\n\tjoinCommand,\n\tgetEscapedCommand,\n\tparseCommand\n};\n","'use strict';\nconst path = require('path');\nconst childProcess = require('child_process');\nconst crossSpawn = require('cross-spawn');\nconst stripFinalNewline = require('strip-final-newline');\nconst npmRunPath = require('npm-run-path');\nconst onetime = require('onetime');\nconst makeError = require('./lib/error');\nconst normalizeStdio = require('./lib/stdio');\nconst {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = require('./lib/kill');\nconst {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream');\nconst {mergePromise, getSpawnedPromise} = require('./lib/promise');\nconst {joinCommand, parseCommand, getEscapedCommand} = require('./lib/command');\n\nconst DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;\n\nconst getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {\n\tconst env = extendEnv ? {...process.env, ...envOption} : envOption;\n\n\tif (preferLocal) {\n\t\treturn npmRunPath.env({env, cwd: localDir, execPath});\n\t}\n\n\treturn env;\n};\n\nconst handleArguments = (file, args, options = {}) => {\n\tconst parsed = crossSpawn._parse(file, args, options);\n\tfile = parsed.command;\n\targs = parsed.args;\n\toptions = parsed.options;\n\n\toptions = {\n\t\tmaxBuffer: DEFAULT_MAX_BUFFER,\n\t\tbuffer: true,\n\t\tstripFinalNewline: true,\n\t\textendEnv: true,\n\t\tpreferLocal: false,\n\t\tlocalDir: options.cwd || process.cwd(),\n\t\texecPath: process.execPath,\n\t\tencoding: 'utf8',\n\t\treject: true,\n\t\tcleanup: true,\n\t\tall: false,\n\t\twindowsHide: true,\n\t\t...options\n\t};\n\n\toptions.env = getEnv(options);\n\n\toptions.stdio = normalizeStdio(options);\n\n\tif (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {\n\t\t// #116\n\t\targs.unshift('/q');\n\t}\n\n\treturn {file, args, options, parsed};\n};\n\nconst handleOutput = (options, value, error) => {\n\tif (typeof value !== 'string' && !Buffer.isBuffer(value)) {\n\t\t// When `execa.sync()` errors, we normalize it to '' to mimic `execa()`\n\t\treturn error === undefined ? undefined : '';\n\t}\n\n\tif (options.stripFinalNewline) {\n\t\treturn stripFinalNewline(value);\n\t}\n\n\treturn value;\n};\n\nconst execa = (file, args, options) => {\n\tconst parsed = handleArguments(file, args, options);\n\tconst command = joinCommand(file, args);\n\tconst escapedCommand = getEscapedCommand(file, args);\n\n\tvalidateTimeout(parsed.options);\n\n\tlet spawned;\n\ttry {\n\t\tspawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);\n\t} catch (error) {\n\t\t// Ensure the returned error is always both a promise and a child process\n\t\tconst dummySpawned = new childProcess.ChildProcess();\n\t\tconst errorPromise = Promise.reject(makeError({\n\t\t\terror,\n\t\t\tstdout: '',\n\t\t\tstderr: '',\n\t\t\tall: '',\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tparsed,\n\t\t\ttimedOut: false,\n\t\t\tisCanceled: false,\n\t\t\tkilled: false\n\t\t}));\n\t\treturn mergePromise(dummySpawned, errorPromise);\n\t}\n\n\tconst spawnedPromise = getSpawnedPromise(spawned);\n\tconst timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);\n\tconst processDone = setExitHandler(spawned, parsed.options, timedPromise);\n\n\tconst context = {isCanceled: false};\n\n\tspawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));\n\tspawned.cancel = spawnedCancel.bind(null, spawned, context);\n\n\tconst handlePromise = async () => {\n\t\tconst [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);\n\t\tconst stdout = handleOutput(parsed.options, stdoutResult);\n\t\tconst stderr = handleOutput(parsed.options, stderrResult);\n\t\tconst all = handleOutput(parsed.options, allResult);\n\n\t\tif (error || exitCode !== 0 || signal !== null) {\n\t\t\tconst returnedError = makeError({\n\t\t\t\terror,\n\t\t\t\texitCode,\n\t\t\t\tsignal,\n\t\t\t\tstdout,\n\t\t\t\tstderr,\n\t\t\t\tall,\n\t\t\t\tcommand,\n\t\t\t\tescapedCommand,\n\t\t\t\tparsed,\n\t\t\t\ttimedOut,\n\t\t\t\tisCanceled: context.isCanceled,\n\t\t\t\tkilled: spawned.killed\n\t\t\t});\n\n\t\t\tif (!parsed.options.reject) {\n\t\t\t\treturn returnedError;\n\t\t\t}\n\n\t\t\tthrow returnedError;\n\t\t}\n\n\t\treturn {\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\texitCode: 0,\n\t\t\tstdout,\n\t\t\tstderr,\n\t\t\tall,\n\t\t\tfailed: false,\n\t\t\ttimedOut: false,\n\t\t\tisCanceled: false,\n\t\t\tkilled: false\n\t\t};\n\t};\n\n\tconst handlePromiseOnce = onetime(handlePromise);\n\n\thandleInput(spawned, parsed.options.input);\n\n\tspawned.all = makeAllStream(spawned, parsed.options);\n\n\treturn mergePromise(spawned, handlePromiseOnce);\n};\n\nmodule.exports = execa;\n\nmodule.exports.sync = (file, args, options) => {\n\tconst parsed = handleArguments(file, args, options);\n\tconst command = joinCommand(file, args);\n\tconst escapedCommand = getEscapedCommand(file, args);\n\n\tvalidateInputSync(parsed.options);\n\n\tlet result;\n\ttry {\n\t\tresult = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);\n\t} catch (error) {\n\t\tthrow makeError({\n\t\t\terror,\n\t\t\tstdout: '',\n\t\t\tstderr: '',\n\t\t\tall: '',\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tparsed,\n\t\t\ttimedOut: false,\n\t\t\tisCanceled: false,\n\t\t\tkilled: false\n\t\t});\n\t}\n\n\tconst stdout = handleOutput(parsed.options, result.stdout, result.error);\n\tconst stderr = handleOutput(parsed.options, result.stderr, result.error);\n\n\tif (result.error || result.status !== 0 || result.signal !== null) {\n\t\tconst error = makeError({\n\t\t\tstdout,\n\t\t\tstderr,\n\t\t\terror: result.error,\n\t\t\tsignal: result.signal,\n\t\t\texitCode: result.status,\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tparsed,\n\t\t\ttimedOut: result.error && result.error.code === 'ETIMEDOUT',\n\t\t\tisCanceled: false,\n\t\t\tkilled: result.signal !== null\n\t\t});\n\n\t\tif (!parsed.options.reject) {\n\t\t\treturn error;\n\t\t}\n\n\t\tthrow error;\n\t}\n\n\treturn {\n\t\tcommand,\n\t\tescapedCommand,\n\t\texitCode: 0,\n\t\tstdout,\n\t\tstderr,\n\t\tfailed: false,\n\t\ttimedOut: false,\n\t\tisCanceled: false,\n\t\tkilled: false\n\t};\n};\n\nmodule.exports.command = (command, options) => {\n\tconst [file, ...args] = parseCommand(command);\n\treturn execa(file, args, options);\n};\n\nmodule.exports.commandSync = (command, options) => {\n\tconst [file, ...args] = parseCommand(command);\n\treturn execa.sync(file, args, options);\n};\n\nmodule.exports.node = (scriptPath, args, options = {}) => {\n\tif (args && !Array.isArray(args) && typeof args === 'object') {\n\t\toptions = args;\n\t\targs = [];\n\t}\n\n\tconst stdio = normalizeStdio.node(options);\n\tconst defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));\n\n\tconst {\n\t\tnodePath = process.execPath,\n\t\tnodeOptions = defaultExecArgv\n\t} = options;\n\n\treturn execa(\n\t\tnodePath,\n\t\t[\n\t\t\t...nodeOptions,\n\t\t\tscriptPath,\n\t\t\t...(Array.isArray(args) ? args : [])\n\t\t],\n\t\t{\n\t\t\t...options,\n\t\t\tstdin: undefined,\n\t\t\tstdout: undefined,\n\t\t\tstderr: undefined,\n\t\t\tstdio,\n\t\t\tshell: false\n\t\t}\n\t);\n};\n","/**\n * The following is modified based on source found in\n * https://github.com/facebook/create-react-app\n *\n * MIT Licensed\n * Copyright (c) 2015-present, Facebook, Inc.\n * https://github.com/facebook/create-react-app/blob/master/LICENSE\n *\n */\n\nimport path from 'path'\nimport open from 'open'\nimport execa from 'execa'\nimport chalk from 'chalk'\nimport { execSync } from 'child_process'\nimport { Logger } from '../logger'\n\n// https://github.com/sindresorhus/open#app\nconst OSX_CHROME = 'google chrome'\n\n/**\n * Reads the BROWSER environment variable and decides what to do with it.\n * Returns true if it opened a browser or ran a node.js script, otherwise false.\n */\nexport function openBrowser(\n url: string,\n opt: string | true,\n logger: Logger\n): boolean {\n // The browser executable to open.\n // See https://github.com/sindresorhus/open#app for documentation.\n const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''\n if (browser.toLowerCase().endsWith('.js')) {\n return executeNodeScript(browser, url, logger)\n } else if (browser.toLowerCase() !== 'none') {\n return startBrowserProcess(browser, url)\n }\n return false\n}\n\nfunction executeNodeScript(scriptPath: string, url: string, logger: Logger) {\n const extraArgs = process.argv.slice(2)\n const child = execa('node', [scriptPath, ...extraArgs, url], {\n stdio: 'inherit'\n })\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(\n chalk.red(\n `\\nThe script specified as BROWSER environment variable failed.\\n\\n${chalk.cyan(\n scriptPath\n )} exited with code ${code}.`\n ),\n { error: null }\n )\n }\n })\n return true\n}\n\nfunction startBrowserProcess(browser: string | undefined, url: string) {\n // If we're on OS X, the user hasn't specifically\n // requested a different browser, we can try opening\n // Chrome with AppleScript. This lets us reuse an\n // existing tab when possible instead of creating a new one.\n const shouldTryOpenChromeWithAppleScript =\n process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME)\n\n if (shouldTryOpenChromeWithAppleScript) {\n try {\n // Try our best to reuse existing tab\n // on OS X Google Chrome with AppleScript\n execSync('ps cax | grep \"Google Chrome\"')\n execSync('osascript openChrome.applescript \"' + encodeURI(url) + '\"', {\n cwd: path.dirname(require.resolve('vite/bin/openChrome.applescript')),\n stdio: 'ignore'\n })\n return true\n } catch (err) {\n // Ignore errors\n }\n }\n\n // Another special case: on OS X, check if BROWSER has been set to \"open\".\n // In this case, instead of passing the string `open` to `open` function (which won't work),\n // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):\n // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768\n if (process.platform === 'darwin' && browser === 'open') {\n browser = undefined\n }\n\n // Fallback to open\n // (It will always open new tab)\n try {\n const options: open.Options = browser ? { app: { name: browser } } : {}\n open(url, options).catch(() => {}) // Prevent `unhandledRejection` error.\n return true\n } catch (err) {\n return false\n }\n}\n","'use strict';\n\nvar matchOperatorsRe = /[|\\\\{}()[\\]^$+*?.]/g;\n\nmodule.exports = function (str) {\n\tif (typeof str !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\treturn str.replace(matchOperatorsRe, '\\\\$&');\n};\n","'use strict'\r\n\r\nmodule.exports = {\r\n\t\"aliceblue\": [240, 248, 255],\r\n\t\"antiquewhite\": [250, 235, 215],\r\n\t\"aqua\": [0, 255, 255],\r\n\t\"aquamarine\": [127, 255, 212],\r\n\t\"azure\": [240, 255, 255],\r\n\t\"beige\": [245, 245, 220],\r\n\t\"bisque\": [255, 228, 196],\r\n\t\"black\": [0, 0, 0],\r\n\t\"blanchedalmond\": [255, 235, 205],\r\n\t\"blue\": [0, 0, 255],\r\n\t\"blueviolet\": [138, 43, 226],\r\n\t\"brown\": [165, 42, 42],\r\n\t\"burlywood\": [222, 184, 135],\r\n\t\"cadetblue\": [95, 158, 160],\r\n\t\"chartreuse\": [127, 255, 0],\r\n\t\"chocolate\": [210, 105, 30],\r\n\t\"coral\": [255, 127, 80],\r\n\t\"cornflowerblue\": [100, 149, 237],\r\n\t\"cornsilk\": [255, 248, 220],\r\n\t\"crimson\": [220, 20, 60],\r\n\t\"cyan\": [0, 255, 255],\r\n\t\"darkblue\": [0, 0, 139],\r\n\t\"darkcyan\": [0, 139, 139],\r\n\t\"darkgoldenrod\": [184, 134, 11],\r\n\t\"darkgray\": [169, 169, 169],\r\n\t\"darkgreen\": [0, 100, 0],\r\n\t\"darkgrey\": [169, 169, 169],\r\n\t\"darkkhaki\": [189, 183, 107],\r\n\t\"darkmagenta\": [139, 0, 139],\r\n\t\"darkolivegreen\": [85, 107, 47],\r\n\t\"darkorange\": [255, 140, 0],\r\n\t\"darkorchid\": [153, 50, 204],\r\n\t\"darkred\": [139, 0, 0],\r\n\t\"darksalmon\": [233, 150, 122],\r\n\t\"darkseagreen\": [143, 188, 143],\r\n\t\"darkslateblue\": [72, 61, 139],\r\n\t\"darkslategray\": [47, 79, 79],\r\n\t\"darkslategrey\": [47, 79, 79],\r\n\t\"darkturquoise\": [0, 206, 209],\r\n\t\"darkviolet\": [148, 0, 211],\r\n\t\"deeppink\": [255, 20, 147],\r\n\t\"deepskyblue\": [0, 191, 255],\r\n\t\"dimgray\": [105, 105, 105],\r\n\t\"dimgrey\": [105, 105, 105],\r\n\t\"dodgerblue\": [30, 144, 255],\r\n\t\"firebrick\": [178, 34, 34],\r\n\t\"floralwhite\": [255, 250, 240],\r\n\t\"forestgreen\": [34, 139, 34],\r\n\t\"fuchsia\": [255, 0, 255],\r\n\t\"gainsboro\": [220, 220, 220],\r\n\t\"ghostwhite\": [248, 248, 255],\r\n\t\"gold\": [255, 215, 0],\r\n\t\"goldenrod\": [218, 165, 32],\r\n\t\"gray\": [128, 128, 128],\r\n\t\"green\": [0, 128, 0],\r\n\t\"greenyellow\": [173, 255, 47],\r\n\t\"grey\": [128, 128, 128],\r\n\t\"honeydew\": [240, 255, 240],\r\n\t\"hotpink\": [255, 105, 180],\r\n\t\"indianred\": [205, 92, 92],\r\n\t\"indigo\": [75, 0, 130],\r\n\t\"ivory\": [255, 255, 240],\r\n\t\"khaki\": [240, 230, 140],\r\n\t\"lavender\": [230, 230, 250],\r\n\t\"lavenderblush\": [255, 240, 245],\r\n\t\"lawngreen\": [124, 252, 0],\r\n\t\"lemonchiffon\": [255, 250, 205],\r\n\t\"lightblue\": [173, 216, 230],\r\n\t\"lightcoral\": [240, 128, 128],\r\n\t\"lightcyan\": [224, 255, 255],\r\n\t\"lightgoldenrodyellow\": [250, 250, 210],\r\n\t\"lightgray\": [211, 211, 211],\r\n\t\"lightgreen\": [144, 238, 144],\r\n\t\"lightgrey\": [211, 211, 211],\r\n\t\"lightpink\": [255, 182, 193],\r\n\t\"lightsalmon\": [255, 160, 122],\r\n\t\"lightseagreen\": [32, 178, 170],\r\n\t\"lightskyblue\": [135, 206, 250],\r\n\t\"lightslategray\": [119, 136, 153],\r\n\t\"lightslategrey\": [119, 136, 153],\r\n\t\"lightsteelblue\": [176, 196, 222],\r\n\t\"lightyellow\": [255, 255, 224],\r\n\t\"lime\": [0, 255, 0],\r\n\t\"limegreen\": [50, 205, 50],\r\n\t\"linen\": [250, 240, 230],\r\n\t\"magenta\": [255, 0, 255],\r\n\t\"maroon\": [128, 0, 0],\r\n\t\"mediumaquamarine\": [102, 205, 170],\r\n\t\"mediumblue\": [0, 0, 205],\r\n\t\"mediumorchid\": [186, 85, 211],\r\n\t\"mediumpurple\": [147, 112, 219],\r\n\t\"mediumseagreen\": [60, 179, 113],\r\n\t\"mediumslateblue\": [123, 104, 238],\r\n\t\"mediumspringgreen\": [0, 250, 154],\r\n\t\"mediumturquoise\": [72, 209, 204],\r\n\t\"mediumvioletred\": [199, 21, 133],\r\n\t\"midnightblue\": [25, 25, 112],\r\n\t\"mintcream\": [245, 255, 250],\r\n\t\"mistyrose\": [255, 228, 225],\r\n\t\"moccasin\": [255, 228, 181],\r\n\t\"navajowhite\": [255, 222, 173],\r\n\t\"navy\": [0, 0, 128],\r\n\t\"oldlace\": [253, 245, 230],\r\n\t\"olive\": [128, 128, 0],\r\n\t\"olivedrab\": [107, 142, 35],\r\n\t\"orange\": [255, 165, 0],\r\n\t\"orangered\": [255, 69, 0],\r\n\t\"orchid\": [218, 112, 214],\r\n\t\"palegoldenrod\": [238, 232, 170],\r\n\t\"palegreen\": [152, 251, 152],\r\n\t\"paleturquoise\": [175, 238, 238],\r\n\t\"palevioletred\": [219, 112, 147],\r\n\t\"papayawhip\": [255, 239, 213],\r\n\t\"peachpuff\": [255, 218, 185],\r\n\t\"peru\": [205, 133, 63],\r\n\t\"pink\": [255, 192, 203],\r\n\t\"plum\": [221, 160, 221],\r\n\t\"powderblue\": [176, 224, 230],\r\n\t\"purple\": [128, 0, 128],\r\n\t\"rebeccapurple\": [102, 51, 153],\r\n\t\"red\": [255, 0, 0],\r\n\t\"rosybrown\": [188, 143, 143],\r\n\t\"royalblue\": [65, 105, 225],\r\n\t\"saddlebrown\": [139, 69, 19],\r\n\t\"salmon\": [250, 128, 114],\r\n\t\"sandybrown\": [244, 164, 96],\r\n\t\"seagreen\": [46, 139, 87],\r\n\t\"seashell\": [255, 245, 238],\r\n\t\"sienna\": [160, 82, 45],\r\n\t\"silver\": [192, 192, 192],\r\n\t\"skyblue\": [135, 206, 235],\r\n\t\"slateblue\": [106, 90, 205],\r\n\t\"slategray\": [112, 128, 144],\r\n\t\"slategrey\": [112, 128, 144],\r\n\t\"snow\": [255, 250, 250],\r\n\t\"springgreen\": [0, 255, 127],\r\n\t\"steelblue\": [70, 130, 180],\r\n\t\"tan\": [210, 180, 140],\r\n\t\"teal\": [0, 128, 128],\r\n\t\"thistle\": [216, 191, 216],\r\n\t\"tomato\": [255, 99, 71],\r\n\t\"turquoise\": [64, 224, 208],\r\n\t\"violet\": [238, 130, 238],\r\n\t\"wheat\": [245, 222, 179],\r\n\t\"white\": [255, 255, 255],\r\n\t\"whitesmoke\": [245, 245, 245],\r\n\t\"yellow\": [255, 255, 0],\r\n\t\"yellowgreen\": [154, 205, 50]\r\n};\r\n","/* MIT license */\nvar cssKeywords = require('color-name');\n\n// NOTE: conversions should only return primitive values (i.e. arrays, or\n// values that give correct `typeof` results).\n// do not use box values types (i.e. Number(), String(), etc.)\n\nvar reverseKeywords = {};\nfor (var key in cssKeywords) {\n\tif (cssKeywords.hasOwnProperty(key)) {\n\t\treverseKeywords[cssKeywords[key]] = key;\n\t}\n}\n\nvar convert = module.exports = {\n\trgb: {channels: 3, labels: 'rgb'},\n\thsl: {channels: 3, labels: 'hsl'},\n\thsv: {channels: 3, labels: 'hsv'},\n\thwb: {channels: 3, labels: 'hwb'},\n\tcmyk: {channels: 4, labels: 'cmyk'},\n\txyz: {channels: 3, labels: 'xyz'},\n\tlab: {channels: 3, labels: 'lab'},\n\tlch: {channels: 3, labels: 'lch'},\n\thex: {channels: 1, labels: ['hex']},\n\tkeyword: {channels: 1, labels: ['keyword']},\n\tansi16: {channels: 1, labels: ['ansi16']},\n\tansi256: {channels: 1, labels: ['ansi256']},\n\thcg: {channels: 3, labels: ['h', 'c', 'g']},\n\tapple: {channels: 3, labels: ['r16', 'g16', 'b16']},\n\tgray: {channels: 1, labels: ['gray']}\n};\n\n// hide .channels and .labels properties\nfor (var model in convert) {\n\tif (convert.hasOwnProperty(model)) {\n\t\tif (!('channels' in convert[model])) {\n\t\t\tthrow new Error('missing channels property: ' + model);\n\t\t}\n\n\t\tif (!('labels' in convert[model])) {\n\t\t\tthrow new Error('missing channel labels property: ' + model);\n\t\t}\n\n\t\tif (convert[model].labels.length !== convert[model].channels) {\n\t\t\tthrow new Error('channel and label counts mismatch: ' + model);\n\t\t}\n\n\t\tvar channels = convert[model].channels;\n\t\tvar labels = convert[model].labels;\n\t\tdelete convert[model].channels;\n\t\tdelete convert[model].labels;\n\t\tObject.defineProperty(convert[model], 'channels', {value: channels});\n\t\tObject.defineProperty(convert[model], 'labels', {value: labels});\n\t}\n}\n\nconvert.rgb.hsl = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar min = Math.min(r, g, b);\n\tvar max = Math.max(r, g, b);\n\tvar delta = max - min;\n\tvar h;\n\tvar s;\n\tvar l;\n\n\tif (max === min) {\n\t\th = 0;\n\t} else if (r === max) {\n\t\th = (g - b) / delta;\n\t} else if (g === max) {\n\t\th = 2 + (b - r) / delta;\n\t} else if (b === max) {\n\t\th = 4 + (r - g) / delta;\n\t}\n\n\th = Math.min(h * 60, 360);\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tl = (min + max) / 2;\n\n\tif (max === min) {\n\t\ts = 0;\n\t} else if (l <= 0.5) {\n\t\ts = delta / (max + min);\n\t} else {\n\t\ts = delta / (2 - max - min);\n\t}\n\n\treturn [h, s * 100, l * 100];\n};\n\nconvert.rgb.hsv = function (rgb) {\n\tvar rdif;\n\tvar gdif;\n\tvar bdif;\n\tvar h;\n\tvar s;\n\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar v = Math.max(r, g, b);\n\tvar diff = v - Math.min(r, g, b);\n\tvar diffc = function (c) {\n\t\treturn (v - c) / 6 / diff + 1 / 2;\n\t};\n\n\tif (diff === 0) {\n\t\th = s = 0;\n\t} else {\n\t\ts = diff / v;\n\t\trdif = diffc(r);\n\t\tgdif = diffc(g);\n\t\tbdif = diffc(b);\n\n\t\tif (r === v) {\n\t\t\th = bdif - gdif;\n\t\t} else if (g === v) {\n\t\t\th = (1 / 3) + rdif - bdif;\n\t\t} else if (b === v) {\n\t\t\th = (2 / 3) + gdif - rdif;\n\t\t}\n\t\tif (h < 0) {\n\t\t\th += 1;\n\t\t} else if (h > 1) {\n\t\t\th -= 1;\n\t\t}\n\t}\n\n\treturn [\n\t\th * 360,\n\t\ts * 100,\n\t\tv * 100\n\t];\n};\n\nconvert.rgb.hwb = function (rgb) {\n\tvar r = rgb[0];\n\tvar g = rgb[1];\n\tvar b = rgb[2];\n\tvar h = convert.rgb.hsl(rgb)[0];\n\tvar w = 1 / 255 * Math.min(r, Math.min(g, b));\n\n\tb = 1 - 1 / 255 * Math.max(r, Math.max(g, b));\n\n\treturn [h, w * 100, b * 100];\n};\n\nconvert.rgb.cmyk = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar c;\n\tvar m;\n\tvar y;\n\tvar k;\n\n\tk = Math.min(1 - r, 1 - g, 1 - b);\n\tc = (1 - r - k) / (1 - k) || 0;\n\tm = (1 - g - k) / (1 - k) || 0;\n\ty = (1 - b - k) / (1 - k) || 0;\n\n\treturn [c * 100, m * 100, y * 100, k * 100];\n};\n\n/**\n * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance\n * */\nfunction comparativeDistance(x, y) {\n\treturn (\n\t\tMath.pow(x[0] - y[0], 2) +\n\t\tMath.pow(x[1] - y[1], 2) +\n\t\tMath.pow(x[2] - y[2], 2)\n\t);\n}\n\nconvert.rgb.keyword = function (rgb) {\n\tvar reversed = reverseKeywords[rgb];\n\tif (reversed) {\n\t\treturn reversed;\n\t}\n\n\tvar currentClosestDistance = Infinity;\n\tvar currentClosestKeyword;\n\n\tfor (var keyword in cssKeywords) {\n\t\tif (cssKeywords.hasOwnProperty(keyword)) {\n\t\t\tvar value = cssKeywords[keyword];\n\n\t\t\t// Compute comparative distance\n\t\t\tvar distance = comparativeDistance(rgb, value);\n\n\t\t\t// Check if its less, if so set as closest\n\t\t\tif (distance < currentClosestDistance) {\n\t\t\t\tcurrentClosestDistance = distance;\n\t\t\t\tcurrentClosestKeyword = keyword;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn currentClosestKeyword;\n};\n\nconvert.keyword.rgb = function (keyword) {\n\treturn cssKeywords[keyword];\n};\n\nconvert.rgb.xyz = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\n\t// assume sRGB\n\tr = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);\n\tg = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);\n\tb = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);\n\n\tvar x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);\n\tvar y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);\n\tvar z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);\n\n\treturn [x * 100, y * 100, z * 100];\n};\n\nconvert.rgb.lab = function (rgb) {\n\tvar xyz = convert.rgb.xyz(rgb);\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.hsl.rgb = function (hsl) {\n\tvar h = hsl[0] / 360;\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar t1;\n\tvar t2;\n\tvar t3;\n\tvar rgb;\n\tvar val;\n\n\tif (s === 0) {\n\t\tval = l * 255;\n\t\treturn [val, val, val];\n\t}\n\n\tif (l < 0.5) {\n\t\tt2 = l * (1 + s);\n\t} else {\n\t\tt2 = l + s - l * s;\n\t}\n\n\tt1 = 2 * l - t2;\n\n\trgb = [0, 0, 0];\n\tfor (var i = 0; i < 3; i++) {\n\t\tt3 = h + 1 / 3 * -(i - 1);\n\t\tif (t3 < 0) {\n\t\t\tt3++;\n\t\t}\n\t\tif (t3 > 1) {\n\t\t\tt3--;\n\t\t}\n\n\t\tif (6 * t3 < 1) {\n\t\t\tval = t1 + (t2 - t1) * 6 * t3;\n\t\t} else if (2 * t3 < 1) {\n\t\t\tval = t2;\n\t\t} else if (3 * t3 < 2) {\n\t\t\tval = t1 + (t2 - t1) * (2 / 3 - t3) * 6;\n\t\t} else {\n\t\t\tval = t1;\n\t\t}\n\n\t\trgb[i] = val * 255;\n\t}\n\n\treturn rgb;\n};\n\nconvert.hsl.hsv = function (hsl) {\n\tvar h = hsl[0];\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar smin = s;\n\tvar lmin = Math.max(l, 0.01);\n\tvar sv;\n\tvar v;\n\n\tl *= 2;\n\ts *= (l <= 1) ? l : 2 - l;\n\tsmin *= lmin <= 1 ? lmin : 2 - lmin;\n\tv = (l + s) / 2;\n\tsv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);\n\n\treturn [h, sv * 100, v * 100];\n};\n\nconvert.hsv.rgb = function (hsv) {\n\tvar h = hsv[0] / 60;\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar hi = Math.floor(h) % 6;\n\n\tvar f = h - Math.floor(h);\n\tvar p = 255 * v * (1 - s);\n\tvar q = 255 * v * (1 - (s * f));\n\tvar t = 255 * v * (1 - (s * (1 - f)));\n\tv *= 255;\n\n\tswitch (hi) {\n\t\tcase 0:\n\t\t\treturn [v, t, p];\n\t\tcase 1:\n\t\t\treturn [q, v, p];\n\t\tcase 2:\n\t\t\treturn [p, v, t];\n\t\tcase 3:\n\t\t\treturn [p, q, v];\n\t\tcase 4:\n\t\t\treturn [t, p, v];\n\t\tcase 5:\n\t\t\treturn [v, p, q];\n\t}\n};\n\nconvert.hsv.hsl = function (hsv) {\n\tvar h = hsv[0];\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar vmin = Math.max(v, 0.01);\n\tvar lmin;\n\tvar sl;\n\tvar l;\n\n\tl = (2 - s) * v;\n\tlmin = (2 - s) * vmin;\n\tsl = s * vmin;\n\tsl /= (lmin <= 1) ? lmin : 2 - lmin;\n\tsl = sl || 0;\n\tl /= 2;\n\n\treturn [h, sl * 100, l * 100];\n};\n\n// http://dev.w3.org/csswg/css-color/#hwb-to-rgb\nconvert.hwb.rgb = function (hwb) {\n\tvar h = hwb[0] / 360;\n\tvar wh = hwb[1] / 100;\n\tvar bl = hwb[2] / 100;\n\tvar ratio = wh + bl;\n\tvar i;\n\tvar v;\n\tvar f;\n\tvar n;\n\n\t// wh + bl cant be > 1\n\tif (ratio > 1) {\n\t\twh /= ratio;\n\t\tbl /= ratio;\n\t}\n\n\ti = Math.floor(6 * h);\n\tv = 1 - bl;\n\tf = 6 * h - i;\n\n\tif ((i & 0x01) !== 0) {\n\t\tf = 1 - f;\n\t}\n\n\tn = wh + f * (v - wh); // linear interpolation\n\n\tvar r;\n\tvar g;\n\tvar b;\n\tswitch (i) {\n\t\tdefault:\n\t\tcase 6:\n\t\tcase 0: r = v; g = n; b = wh; break;\n\t\tcase 1: r = n; g = v; b = wh; break;\n\t\tcase 2: r = wh; g = v; b = n; break;\n\t\tcase 3: r = wh; g = n; b = v; break;\n\t\tcase 4: r = n; g = wh; b = v; break;\n\t\tcase 5: r = v; g = wh; b = n; break;\n\t}\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.cmyk.rgb = function (cmyk) {\n\tvar c = cmyk[0] / 100;\n\tvar m = cmyk[1] / 100;\n\tvar y = cmyk[2] / 100;\n\tvar k = cmyk[3] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = 1 - Math.min(1, c * (1 - k) + k);\n\tg = 1 - Math.min(1, m * (1 - k) + k);\n\tb = 1 - Math.min(1, y * (1 - k) + k);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.rgb = function (xyz) {\n\tvar x = xyz[0] / 100;\n\tvar y = xyz[1] / 100;\n\tvar z = xyz[2] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);\n\tg = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);\n\tb = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);\n\n\t// assume sRGB\n\tr = r > 0.0031308\n\t\t? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)\n\t\t: r * 12.92;\n\n\tg = g > 0.0031308\n\t\t? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)\n\t\t: g * 12.92;\n\n\tb = b > 0.0031308\n\t\t? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)\n\t\t: b * 12.92;\n\n\tr = Math.min(Math.max(0, r), 1);\n\tg = Math.min(Math.max(0, g), 1);\n\tb = Math.min(Math.max(0, b), 1);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.lab = function (xyz) {\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.lab.xyz = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar x;\n\tvar y;\n\tvar z;\n\n\ty = (l + 16) / 116;\n\tx = a / 500 + y;\n\tz = y - b / 200;\n\n\tvar y2 = Math.pow(y, 3);\n\tvar x2 = Math.pow(x, 3);\n\tvar z2 = Math.pow(z, 3);\n\ty = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;\n\tx = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;\n\tz = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;\n\n\tx *= 95.047;\n\ty *= 100;\n\tz *= 108.883;\n\n\treturn [x, y, z];\n};\n\nconvert.lab.lch = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar hr;\n\tvar h;\n\tvar c;\n\n\thr = Math.atan2(b, a);\n\th = hr * 360 / 2 / Math.PI;\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tc = Math.sqrt(a * a + b * b);\n\n\treturn [l, c, h];\n};\n\nconvert.lch.lab = function (lch) {\n\tvar l = lch[0];\n\tvar c = lch[1];\n\tvar h = lch[2];\n\tvar a;\n\tvar b;\n\tvar hr;\n\n\thr = h / 360 * 2 * Math.PI;\n\ta = c * Math.cos(hr);\n\tb = c * Math.sin(hr);\n\n\treturn [l, a, b];\n};\n\nconvert.rgb.ansi16 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\tvar value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization\n\n\tvalue = Math.round(value / 50);\n\n\tif (value === 0) {\n\t\treturn 30;\n\t}\n\n\tvar ansi = 30\n\t\t+ ((Math.round(b / 255) << 2)\n\t\t| (Math.round(g / 255) << 1)\n\t\t| Math.round(r / 255));\n\n\tif (value === 2) {\n\t\tansi += 60;\n\t}\n\n\treturn ansi;\n};\n\nconvert.hsv.ansi16 = function (args) {\n\t// optimization here; we already know the value and don't need to get\n\t// it converted for us.\n\treturn convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);\n};\n\nconvert.rgb.ansi256 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\n\t// we use the extended greyscale palette here, with the exception of\n\t// black and white. normal palette only has 4 greyscale shades.\n\tif (r === g && g === b) {\n\t\tif (r < 8) {\n\t\t\treturn 16;\n\t\t}\n\n\t\tif (r > 248) {\n\t\t\treturn 231;\n\t\t}\n\n\t\treturn Math.round(((r - 8) / 247) * 24) + 232;\n\t}\n\n\tvar ansi = 16\n\t\t+ (36 * Math.round(r / 255 * 5))\n\t\t+ (6 * Math.round(g / 255 * 5))\n\t\t+ Math.round(b / 255 * 5);\n\n\treturn ansi;\n};\n\nconvert.ansi16.rgb = function (args) {\n\tvar color = args % 10;\n\n\t// handle greyscale\n\tif (color === 0 || color === 7) {\n\t\tif (args > 50) {\n\t\t\tcolor += 3.5;\n\t\t}\n\n\t\tcolor = color / 10.5 * 255;\n\n\t\treturn [color, color, color];\n\t}\n\n\tvar mult = (~~(args > 50) + 1) * 0.5;\n\tvar r = ((color & 1) * mult) * 255;\n\tvar g = (((color >> 1) & 1) * mult) * 255;\n\tvar b = (((color >> 2) & 1) * mult) * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.ansi256.rgb = function (args) {\n\t// handle greyscale\n\tif (args >= 232) {\n\t\tvar c = (args - 232) * 10 + 8;\n\t\treturn [c, c, c];\n\t}\n\n\targs -= 16;\n\n\tvar rem;\n\tvar r = Math.floor(args / 36) / 5 * 255;\n\tvar g = Math.floor((rem = args % 36) / 6) / 5 * 255;\n\tvar b = (rem % 6) / 5 * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hex = function (args) {\n\tvar integer = ((Math.round(args[0]) & 0xFF) << 16)\n\t\t+ ((Math.round(args[1]) & 0xFF) << 8)\n\t\t+ (Math.round(args[2]) & 0xFF);\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.hex.rgb = function (args) {\n\tvar match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);\n\tif (!match) {\n\t\treturn [0, 0, 0];\n\t}\n\n\tvar colorString = match[0];\n\n\tif (match[0].length === 3) {\n\t\tcolorString = colorString.split('').map(function (char) {\n\t\t\treturn char + char;\n\t\t}).join('');\n\t}\n\n\tvar integer = parseInt(colorString, 16);\n\tvar r = (integer >> 16) & 0xFF;\n\tvar g = (integer >> 8) & 0xFF;\n\tvar b = integer & 0xFF;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hcg = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar max = Math.max(Math.max(r, g), b);\n\tvar min = Math.min(Math.min(r, g), b);\n\tvar chroma = (max - min);\n\tvar grayscale;\n\tvar hue;\n\n\tif (chroma < 1) {\n\t\tgrayscale = min / (1 - chroma);\n\t} else {\n\t\tgrayscale = 0;\n\t}\n\n\tif (chroma <= 0) {\n\t\thue = 0;\n\t} else\n\tif (max === r) {\n\t\thue = ((g - b) / chroma) % 6;\n\t} else\n\tif (max === g) {\n\t\thue = 2 + (b - r) / chroma;\n\t} else {\n\t\thue = 4 + (r - g) / chroma + 4;\n\t}\n\n\thue /= 6;\n\thue %= 1;\n\n\treturn [hue * 360, chroma * 100, grayscale * 100];\n};\n\nconvert.hsl.hcg = function (hsl) {\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar c = 1;\n\tvar f = 0;\n\n\tif (l < 0.5) {\n\t\tc = 2.0 * s * l;\n\t} else {\n\t\tc = 2.0 * s * (1.0 - l);\n\t}\n\n\tif (c < 1.0) {\n\t\tf = (l - 0.5 * c) / (1.0 - c);\n\t}\n\n\treturn [hsl[0], c * 100, f * 100];\n};\n\nconvert.hsv.hcg = function (hsv) {\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\n\tvar c = s * v;\n\tvar f = 0;\n\n\tif (c < 1.0) {\n\t\tf = (v - c) / (1 - c);\n\t}\n\n\treturn [hsv[0], c * 100, f * 100];\n};\n\nconvert.hcg.rgb = function (hcg) {\n\tvar h = hcg[0] / 360;\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tif (c === 0.0) {\n\t\treturn [g * 255, g * 255, g * 255];\n\t}\n\n\tvar pure = [0, 0, 0];\n\tvar hi = (h % 1) * 6;\n\tvar v = hi % 1;\n\tvar w = 1 - v;\n\tvar mg = 0;\n\n\tswitch (Math.floor(hi)) {\n\t\tcase 0:\n\t\t\tpure[0] = 1; pure[1] = v; pure[2] = 0; break;\n\t\tcase 1:\n\t\t\tpure[0] = w; pure[1] = 1; pure[2] = 0; break;\n\t\tcase 2:\n\t\t\tpure[0] = 0; pure[1] = 1; pure[2] = v; break;\n\t\tcase 3:\n\t\t\tpure[0] = 0; pure[1] = w; pure[2] = 1; break;\n\t\tcase 4:\n\t\t\tpure[0] = v; pure[1] = 0; pure[2] = 1; break;\n\t\tdefault:\n\t\t\tpure[0] = 1; pure[1] = 0; pure[2] = w;\n\t}\n\n\tmg = (1.0 - c) * g;\n\n\treturn [\n\t\t(c * pure[0] + mg) * 255,\n\t\t(c * pure[1] + mg) * 255,\n\t\t(c * pure[2] + mg) * 255\n\t];\n};\n\nconvert.hcg.hsv = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar v = c + g * (1.0 - c);\n\tvar f = 0;\n\n\tif (v > 0.0) {\n\t\tf = c / v;\n\t}\n\n\treturn [hcg[0], f * 100, v * 100];\n};\n\nconvert.hcg.hsl = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar l = g * (1.0 - c) + 0.5 * c;\n\tvar s = 0;\n\n\tif (l > 0.0 && l < 0.5) {\n\t\ts = c / (2 * l);\n\t} else\n\tif (l >= 0.5 && l < 1.0) {\n\t\ts = c / (2 * (1 - l));\n\t}\n\n\treturn [hcg[0], s * 100, l * 100];\n};\n\nconvert.hcg.hwb = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\tvar v = c + g * (1.0 - c);\n\treturn [hcg[0], (v - c) * 100, (1 - v) * 100];\n};\n\nconvert.hwb.hcg = function (hwb) {\n\tvar w = hwb[1] / 100;\n\tvar b = hwb[2] / 100;\n\tvar v = 1 - b;\n\tvar c = v - w;\n\tvar g = 0;\n\n\tif (c < 1) {\n\t\tg = (v - c) / (1 - c);\n\t}\n\n\treturn [hwb[0], c * 100, g * 100];\n};\n\nconvert.apple.rgb = function (apple) {\n\treturn [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];\n};\n\nconvert.rgb.apple = function (rgb) {\n\treturn [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];\n};\n\nconvert.gray.rgb = function (args) {\n\treturn [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];\n};\n\nconvert.gray.hsl = convert.gray.hsv = function (args) {\n\treturn [0, 0, args[0]];\n};\n\nconvert.gray.hwb = function (gray) {\n\treturn [0, 100, gray[0]];\n};\n\nconvert.gray.cmyk = function (gray) {\n\treturn [0, 0, 0, gray[0]];\n};\n\nconvert.gray.lab = function (gray) {\n\treturn [gray[0], 0, 0];\n};\n\nconvert.gray.hex = function (gray) {\n\tvar val = Math.round(gray[0] / 100 * 255) & 0xFF;\n\tvar integer = (val << 16) + (val << 8) + val;\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.rgb.gray = function (rgb) {\n\tvar val = (rgb[0] + rgb[1] + rgb[2]) / 3;\n\treturn [val / 255 * 100];\n};\n","var conversions = require('./conversions');\n\n/*\n\tthis function routes a model to all other models.\n\n\tall functions that are routed have a property `.conversion` attached\n\tto the returned synthetic function. This property is an array\n\tof strings, each with the steps in between the 'from' and 'to'\n\tcolor models (inclusive).\n\n\tconversions that are not possible simply are not included.\n*/\n\nfunction buildGraph() {\n\tvar graph = {};\n\t// https://jsperf.com/object-keys-vs-for-in-with-closure/3\n\tvar models = Object.keys(conversions);\n\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tgraph[models[i]] = {\n\t\t\t// http://jsperf.com/1-vs-infinity\n\t\t\t// micro-opt, but this is simple.\n\t\t\tdistance: -1,\n\t\t\tparent: null\n\t\t};\n\t}\n\n\treturn graph;\n}\n\n// https://en.wikipedia.org/wiki/Breadth-first_search\nfunction deriveBFS(fromModel) {\n\tvar graph = buildGraph();\n\tvar queue = [fromModel]; // unshift -> queue -> pop\n\n\tgraph[fromModel].distance = 0;\n\n\twhile (queue.length) {\n\t\tvar current = queue.pop();\n\t\tvar adjacents = Object.keys(conversions[current]);\n\n\t\tfor (var len = adjacents.length, i = 0; i < len; i++) {\n\t\t\tvar adjacent = adjacents[i];\n\t\t\tvar node = graph[adjacent];\n\n\t\t\tif (node.distance === -1) {\n\t\t\t\tnode.distance = graph[current].distance + 1;\n\t\t\t\tnode.parent = current;\n\t\t\t\tqueue.unshift(adjacent);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn graph;\n}\n\nfunction link(from, to) {\n\treturn function (args) {\n\t\treturn to(from(args));\n\t};\n}\n\nfunction wrapConversion(toModel, graph) {\n\tvar path = [graph[toModel].parent, toModel];\n\tvar fn = conversions[graph[toModel].parent][toModel];\n\n\tvar cur = graph[toModel].parent;\n\twhile (graph[cur].parent) {\n\t\tpath.unshift(graph[cur].parent);\n\t\tfn = link(conversions[graph[cur].parent][cur], fn);\n\t\tcur = graph[cur].parent;\n\t}\n\n\tfn.conversion = path;\n\treturn fn;\n}\n\nmodule.exports = function (fromModel) {\n\tvar graph = deriveBFS(fromModel);\n\tvar conversion = {};\n\n\tvar models = Object.keys(graph);\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tvar toModel = models[i];\n\t\tvar node = graph[toModel];\n\n\t\tif (node.parent === null) {\n\t\t\t// no possible conversion, or this node is the source model.\n\t\t\tcontinue;\n\t\t}\n\n\t\tconversion[toModel] = wrapConversion(toModel, graph);\n\t}\n\n\treturn conversion;\n};\n\n","var conversions = require('./conversions');\nvar route = require('./route');\n\nvar convert = {};\n\nvar models = Object.keys(conversions);\n\nfunction wrapRaw(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\treturn fn(args);\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nfunction wrapRounded(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\tvar result = fn(args);\n\n\t\t// we're assuming the result is an array here.\n\t\t// see notice in conversions.js; don't use box types\n\t\t// in conversion functions.\n\t\tif (typeof result === 'object') {\n\t\t\tfor (var len = result.length, i = 0; i < len; i++) {\n\t\t\t\tresult[i] = Math.round(result[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nmodels.forEach(function (fromModel) {\n\tconvert[fromModel] = {};\n\n\tObject.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});\n\tObject.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});\n\n\tvar routes = route(fromModel);\n\tvar routeModels = Object.keys(routes);\n\n\trouteModels.forEach(function (toModel) {\n\t\tvar fn = routes[toModel];\n\n\t\tconvert[fromModel][toModel] = wrapRounded(fn);\n\t\tconvert[fromModel][toModel].raw = wrapRaw(fn);\n\t});\n});\n\nmodule.exports = convert;\n","'use strict';\nconst colorConvert = require('color-convert');\n\nconst wrapAnsi16 = (fn, offset) => function () {\n\tconst code = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${code + offset}m`;\n};\n\nconst wrapAnsi256 = (fn, offset) => function () {\n\tconst code = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${38 + offset};5;${code}m`;\n};\n\nconst wrapAnsi16m = (fn, offset) => function () {\n\tconst rgb = fn.apply(colorConvert, arguments);\n\treturn `\\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;\n};\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\tconst styles = {\n\t\tmodifier: {\n\t\t\treset: [0, 0],\n\t\t\t// 21 isn't widely supported and 22 does the same thing\n\t\t\tbold: [1, 22],\n\t\t\tdim: [2, 22],\n\t\t\titalic: [3, 23],\n\t\t\tunderline: [4, 24],\n\t\t\tinverse: [7, 27],\n\t\t\thidden: [8, 28],\n\t\t\tstrikethrough: [9, 29]\n\t\t},\n\t\tcolor: {\n\t\t\tblack: [30, 39],\n\t\t\tred: [31, 39],\n\t\t\tgreen: [32, 39],\n\t\t\tyellow: [33, 39],\n\t\t\tblue: [34, 39],\n\t\t\tmagenta: [35, 39],\n\t\t\tcyan: [36, 39],\n\t\t\twhite: [37, 39],\n\t\t\tgray: [90, 39],\n\n\t\t\t// Bright color\n\t\t\tredBright: [91, 39],\n\t\t\tgreenBright: [92, 39],\n\t\t\tyellowBright: [93, 39],\n\t\t\tblueBright: [94, 39],\n\t\t\tmagentaBright: [95, 39],\n\t\t\tcyanBright: [96, 39],\n\t\t\twhiteBright: [97, 39]\n\t\t},\n\t\tbgColor: {\n\t\t\tbgBlack: [40, 49],\n\t\t\tbgRed: [41, 49],\n\t\t\tbgGreen: [42, 49],\n\t\t\tbgYellow: [43, 49],\n\t\t\tbgBlue: [44, 49],\n\t\t\tbgMagenta: [45, 49],\n\t\t\tbgCyan: [46, 49],\n\t\t\tbgWhite: [47, 49],\n\n\t\t\t// Bright color\n\t\t\tbgBlackBright: [100, 49],\n\t\t\tbgRedBright: [101, 49],\n\t\t\tbgGreenBright: [102, 49],\n\t\t\tbgYellowBright: [103, 49],\n\t\t\tbgBlueBright: [104, 49],\n\t\t\tbgMagentaBright: [105, 49],\n\t\t\tbgCyanBright: [106, 49],\n\t\t\tbgWhiteBright: [107, 49]\n\t\t}\n\t};\n\n\t// Fix humans\n\tstyles.color.grey = styles.color.gray;\n\n\tfor (const groupName of Object.keys(styles)) {\n\t\tconst group = styles[groupName];\n\n\t\tfor (const styleName of Object.keys(group)) {\n\t\t\tconst style = group[styleName];\n\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false\n\t\t});\n\n\t\tObject.defineProperty(styles, 'codes', {\n\t\t\tvalue: codes,\n\t\t\tenumerable: false\n\t\t});\n\t}\n\n\tconst ansi2ansi = n => n;\n\tconst rgb2rgb = (r, g, b) => [r, g, b];\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = {\n\t\tansi: wrapAnsi16(ansi2ansi, 0)\n\t};\n\tstyles.color.ansi256 = {\n\t\tansi256: wrapAnsi256(ansi2ansi, 0)\n\t};\n\tstyles.color.ansi16m = {\n\t\trgb: wrapAnsi16m(rgb2rgb, 0)\n\t};\n\n\tstyles.bgColor.ansi = {\n\t\tansi: wrapAnsi16(ansi2ansi, 10)\n\t};\n\tstyles.bgColor.ansi256 = {\n\t\tansi256: wrapAnsi256(ansi2ansi, 10)\n\t};\n\tstyles.bgColor.ansi16m = {\n\t\trgb: wrapAnsi16m(rgb2rgb, 10)\n\t};\n\n\tfor (let key of Object.keys(colorConvert)) {\n\t\tif (typeof colorConvert[key] !== 'object') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst suite = colorConvert[key];\n\n\t\tif (key === 'ansi16') {\n\t\t\tkey = 'ansi';\n\t\t}\n\n\t\tif ('ansi16' in suite) {\n\t\t\tstyles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);\n\t\t\tstyles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);\n\t\t}\n\n\t\tif ('ansi256' in suite) {\n\t\t\tstyles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);\n\t\t\tstyles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);\n\t\t}\n\n\t\tif ('rgb' in suite) {\n\t\t\tstyles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);\n\t\t\tstyles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);\n\t\t}\n\t}\n\n\treturn styles;\n}\n\n// Make the export immutable\nObject.defineProperty(module, 'exports', {\n\tenumerable: true,\n\tget: assembleStyles\n});\n","'use strict';\nmodule.exports = (flag, argv) => {\n\targv = argv || process.argv;\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst pos = argv.indexOf(prefix + flag);\n\tconst terminatorPos = argv.indexOf('--');\n\treturn pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);\n};\n","'use strict';\nconst os = require('os');\nconst hasFlag = require('has-flag');\n\nconst env = process.env;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false')) {\n\tforceColor = false;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = true;\n}\nif ('FORCE_COLOR' in env) {\n\tforceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(stream) {\n\tif (forceColor === false) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (stream && !stream.isTTY && forceColor !== true) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor ? 1 : 0;\n\n\tif (process.platform === 'win32') {\n\t\t// Node.js 7.5.0 is the first version of Node.js to include a patch to\n\t\t// libuv that enables 256 color output on Windows. Anything earlier and it\n\t\t// won't work. However, here we target Node.js 8 at minimum as it is an LTS\n\t\t// release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows\n\t\t// release that supports 256 colors. Windows 10 build 14931 is the first release\n\t\t// that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(process.versions.node.split('.')[0]) >= 8 &&\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: getSupportLevel(process.stdout),\n\tstderr: getSupportLevel(process.stderr)\n};\n","'use strict';\nconst TEMPLATE_REGEX = /(?:\\\\(u[a-f\\d]{4}|x[a-f\\d]{2}|.))|(?:\\{(~)?(\\w+(?:\\([^)]*\\))?(?:\\.\\w+(?:\\([^)]*\\))?)*)(?:[ \\t]|(?=\\r?\\n)))|(\\})|((?:.|[\\r\\n\\f])+?)/gi;\nconst STYLE_REGEX = /(?:^|\\.)(\\w+)(?:\\(([^)]*)\\))?/g;\nconst STRING_REGEX = /^(['\"])((?:\\\\.|(?!\\1)[^\\\\])*)\\1$/;\nconst ESCAPE_REGEX = /\\\\(u[a-f\\d]{4}|x[a-f\\d]{2}|.)|([^\\\\])/gi;\n\nconst ESCAPES = new Map([\n\t['n', '\\n'],\n\t['r', '\\r'],\n\t['t', '\\t'],\n\t['b', '\\b'],\n\t['f', '\\f'],\n\t['v', '\\v'],\n\t['0', '\\0'],\n\t['\\\\', '\\\\'],\n\t['e', '\\u001B'],\n\t['a', '\\u0007']\n]);\n\nfunction unescape(c) {\n\tif ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {\n\t\treturn String.fromCharCode(parseInt(c.slice(1), 16));\n\t}\n\n\treturn ESCAPES.get(c) || c;\n}\n\nfunction parseArguments(name, args) {\n\tconst results = [];\n\tconst chunks = args.trim().split(/\\s*,\\s*/g);\n\tlet matches;\n\n\tfor (const chunk of chunks) {\n\t\tif (!isNaN(chunk)) {\n\t\t\tresults.push(Number(chunk));\n\t\t} else if ((matches = chunk.match(STRING_REGEX))) {\n\t\t\tresults.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));\n\t\t} else {\n\t\t\tthrow new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nfunction parseStyle(style) {\n\tSTYLE_REGEX.lastIndex = 0;\n\n\tconst results = [];\n\tlet matches;\n\n\twhile ((matches = STYLE_REGEX.exec(style)) !== null) {\n\t\tconst name = matches[1];\n\n\t\tif (matches[2]) {\n\t\t\tconst args = parseArguments(name, matches[2]);\n\t\t\tresults.push([name].concat(args));\n\t\t} else {\n\t\t\tresults.push([name]);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nfunction buildStyle(chalk, styles) {\n\tconst enabled = {};\n\n\tfor (const layer of styles) {\n\t\tfor (const style of layer.styles) {\n\t\t\tenabled[style[0]] = layer.inverse ? null : style.slice(1);\n\t\t}\n\t}\n\n\tlet current = chalk;\n\tfor (const styleName of Object.keys(enabled)) {\n\t\tif (Array.isArray(enabled[styleName])) {\n\t\t\tif (!(styleName in current)) {\n\t\t\t\tthrow new Error(`Unknown Chalk style: ${styleName}`);\n\t\t\t}\n\n\t\t\tif (enabled[styleName].length > 0) {\n\t\t\t\tcurrent = current[styleName].apply(current, enabled[styleName]);\n\t\t\t} else {\n\t\t\t\tcurrent = current[styleName];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn current;\n}\n\nmodule.exports = (chalk, tmp) => {\n\tconst styles = [];\n\tconst chunks = [];\n\tlet chunk = [];\n\n\t// eslint-disable-next-line max-params\n\ttmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {\n\t\tif (escapeChar) {\n\t\t\tchunk.push(unescape(escapeChar));\n\t\t} else if (style) {\n\t\t\tconst str = chunk.join('');\n\t\t\tchunk = [];\n\t\t\tchunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));\n\t\t\tstyles.push({inverse, styles: parseStyle(style)});\n\t\t} else if (close) {\n\t\t\tif (styles.length === 0) {\n\t\t\t\tthrow new Error('Found extraneous } in Chalk template literal');\n\t\t\t}\n\n\t\t\tchunks.push(buildStyle(chalk, styles)(chunk.join('')));\n\t\t\tchunk = [];\n\t\t\tstyles.pop();\n\t\t} else {\n\t\t\tchunk.push(chr);\n\t\t}\n\t});\n\n\tchunks.push(chunk.join(''));\n\n\tif (styles.length > 0) {\n\t\tconst errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\\`}\\`)`;\n\t\tthrow new Error(errMsg);\n\t}\n\n\treturn chunks.join('');\n};\n","'use strict';\nconst escapeStringRegexp = require('escape-string-regexp');\nconst ansiStyles = require('ansi-styles');\nconst stdoutColor = require('supports-color').stdout;\n\nconst template = require('./templates.js');\n\nconst isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');\n\n// `supportsColor.level` → `ansiStyles.color[name]` mapping\nconst levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];\n\n// `color-convert` models to exclude from the Chalk API due to conflicts and such\nconst skipModels = new Set(['gray']);\n\nconst styles = Object.create(null);\n\nfunction applyOptions(obj, options) {\n\toptions = options || {};\n\n\t// Detect level if not set manually\n\tconst scLevel = stdoutColor ? stdoutColor.level : 0;\n\tobj.level = options.level === undefined ? scLevel : options.level;\n\tobj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;\n}\n\nfunction Chalk(options) {\n\t// We check for this.template here since calling `chalk.constructor()`\n\t// by itself will have a `this` of a previously constructed chalk object\n\tif (!this || !(this instanceof Chalk) || this.template) {\n\t\tconst chalk = {};\n\t\tapplyOptions(chalk, options);\n\n\t\tchalk.template = function () {\n\t\t\tconst args = [].slice.call(arguments);\n\t\t\treturn chalkTag.apply(null, [chalk.template].concat(args));\n\t\t};\n\n\t\tObject.setPrototypeOf(chalk, Chalk.prototype);\n\t\tObject.setPrototypeOf(chalk.template, chalk);\n\n\t\tchalk.template.constructor = Chalk;\n\n\t\treturn chalk.template;\n\t}\n\n\tapplyOptions(this, options);\n}\n\n// Use bright blue on Windows as the normal blue color is illegible\nif (isSimpleWindowsTerm) {\n\tansiStyles.blue.open = '\\u001B[94m';\n}\n\nfor (const key of Object.keys(ansiStyles)) {\n\tansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');\n\n\tstyles[key] = {\n\t\tget() {\n\t\t\tconst codes = ansiStyles[key];\n\t\t\treturn build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);\n\t\t}\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\treturn build.call(this, this._styles || [], true, 'visible');\n\t}\n};\n\nansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');\nfor (const model of Object.keys(ansiStyles.color.ansi)) {\n\tif (skipModels.has(model)) {\n\t\tcontinue;\n\t}\n\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst level = this.level;\n\t\t\treturn function () {\n\t\t\t\tconst open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);\n\t\t\t\tconst codes = {\n\t\t\t\t\topen,\n\t\t\t\t\tclose: ansiStyles.color.close,\n\t\t\t\t\tcloseRe: ansiStyles.color.closeRe\n\t\t\t\t};\n\t\t\t\treturn build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);\n\t\t\t};\n\t\t}\n\t};\n}\n\nansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');\nfor (const model of Object.keys(ansiStyles.bgColor.ansi)) {\n\tif (skipModels.has(model)) {\n\t\tcontinue;\n\t}\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst level = this.level;\n\t\t\treturn function () {\n\t\t\t\tconst open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);\n\t\t\t\tconst codes = {\n\t\t\t\t\topen,\n\t\t\t\t\tclose: ansiStyles.bgColor.close,\n\t\t\t\t\tcloseRe: ansiStyles.bgColor.closeRe\n\t\t\t\t};\n\t\t\t\treturn build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);\n\t\t\t};\n\t\t}\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, styles);\n\nfunction build(_styles, _empty, key) {\n\tconst builder = function () {\n\t\treturn applyStyle.apply(builder, arguments);\n\t};\n\n\tbuilder._styles = _styles;\n\tbuilder._empty = _empty;\n\n\tconst self = this;\n\n\tObject.defineProperty(builder, 'level', {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn self.level;\n\t\t},\n\t\tset(level) {\n\t\t\tself.level = level;\n\t\t}\n\t});\n\n\tObject.defineProperty(builder, 'enabled', {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn self.enabled;\n\t\t},\n\t\tset(enabled) {\n\t\t\tself.enabled = enabled;\n\t\t}\n\t});\n\n\t// See below for fix regarding invisible grey/dim combination on Windows\n\tbuilder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';\n\n\t// `__proto__` is used because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tbuilder.__proto__ = proto; // eslint-disable-line no-proto\n\n\treturn builder;\n}\n\nfunction applyStyle() {\n\t// Support varags, but simply cast to string in case there's only one arg\n\tconst args = arguments;\n\tconst argsLen = args.length;\n\tlet str = String(arguments[0]);\n\n\tif (argsLen === 0) {\n\t\treturn '';\n\t}\n\n\tif (argsLen > 1) {\n\t\t// Don't slice `arguments`, it prevents V8 optimizations\n\t\tfor (let a = 1; a < argsLen; a++) {\n\t\t\tstr += ' ' + args[a];\n\t\t}\n\t}\n\n\tif (!this.enabled || this.level <= 0 || !str) {\n\t\treturn this._empty ? '' : str;\n\t}\n\n\t// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,\n\t// see https://github.com/chalk/chalk/issues/58\n\t// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.\n\tconst originalDim = ansiStyles.dim.open;\n\tif (isSimpleWindowsTerm && this.hasGrey) {\n\t\tansiStyles.dim.open = '';\n\t}\n\n\tfor (const code of this._styles.slice().reverse()) {\n\t\t// Replace any instances already present with a re-opening code\n\t\t// otherwise only the part of the string until said closing code\n\t\t// will be colored, and the rest will simply be 'plain'.\n\t\tstr = code.open + str.replace(code.closeRe, code.open) + code.close;\n\n\t\t// Close the styling before a linebreak and reopen\n\t\t// after next line to fix a bleed issue on macOS\n\t\t// https://github.com/chalk/chalk/pull/92\n\t\tstr = str.replace(/\\r?\\n/g, `${code.close}$&${code.open}`);\n\t}\n\n\t// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue\n\tansiStyles.dim.open = originalDim;\n\n\treturn str;\n}\n\nfunction chalkTag(chalk, strings) {\n\tif (!Array.isArray(strings)) {\n\t\t// If chalk() was called by itself or with a string,\n\t\t// return the string itself as a string.\n\t\treturn [].slice.call(arguments, 1).join(' ');\n\t}\n\n\tconst args = [].slice.call(arguments, 2);\n\tconst parts = [strings.raw[0]];\n\n\tfor (let i = 1; i < strings.length; i++) {\n\t\tparts.push(String(args[i - 1]).replace(/[{}\\\\]/g, '\\\\$&'));\n\t\tparts.push(String(strings.raw[i]));\n\t}\n\n\treturn template(chalk, parts.join(''));\n}\n\nObject.defineProperties(Chalk.prototype, styles);\n\nmodule.exports = Chalk(); // eslint-disable-line new-cap\nmodule.exports.supportsColor = stdoutColor;\nmodule.exports.default = module.exports; // For TypeScript\n","exports.quote = function (xs) {\n return xs.map(function (s) {\n if (s && typeof s === 'object') {\n return s.op.replace(/(.)/g, '\\\\$1');\n }\n else if (/[\"\\s]/.test(s) && !/'/.test(s)) {\n return \"'\" + s.replace(/(['\\\\])/g, '\\\\$1') + \"'\";\n }\n else if (/[\"'\\s]/.test(s)) {\n return '\"' + s.replace(/([\"\\\\$`!])/g, '\\\\$1') + '\"';\n }\n else {\n return String(s).replace(/([A-z]:)?([#!\"$&'()*,:;<=>?@\\[\\\\\\]^`{|}])/g, '$1\\\\$2');\n }\n }).join(' ');\n};\n\n// '<(' is process substitution operator and\n// can be parsed the same as control operator\nvar CONTROL = '(?:' + [\n '\\\\|\\\\|', '\\\\&\\\\&', ';;', '\\\\|\\\\&', '\\\\<\\\\(', '>>', '>\\\\&', '[&;()|<>]'\n].join('|') + ')';\nvar META = '|&;()<> \\\\t';\nvar BAREWORD = '(\\\\\\\\[\\'\"' + META + ']|[^\\\\s\\'\"' + META + '])+';\nvar SINGLE_QUOTE = '\"((\\\\\\\\\"|[^\"])*?)\"';\nvar DOUBLE_QUOTE = '\\'((\\\\\\\\\\'|[^\\'])*?)\\'';\n\nvar TOKEN = '';\nfor (var i = 0; i < 4; i++) {\n TOKEN += (Math.pow(16,8)*Math.random()).toString(16);\n}\n\nexports.parse = function (s, env, opts) {\n var mapped = parse(s, env, opts);\n if (typeof env !== 'function') return mapped;\n return mapped.reduce(function (acc, s) {\n if (typeof s === 'object') return acc.concat(s);\n var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));\n if (xs.length === 1) return acc.concat(xs[0]);\n return acc.concat(xs.filter(Boolean).map(function (x) {\n if (RegExp('^' + TOKEN).test(x)) {\n return JSON.parse(x.split(TOKEN)[1]);\n }\n else return x;\n }));\n }, []);\n};\n\nfunction parse (s, env, opts) {\n var chunker = new RegExp([\n '(' + CONTROL + ')', // control chars\n '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'\n ].join('|'), 'g');\n var match = s.match(chunker).filter(Boolean);\n var commented = false;\n\n if (!match) return [];\n if (!env) env = {};\n if (!opts) opts = {};\n return match.map(function (s, j) {\n if (commented) {\n return;\n }\n if (RegExp('^' + CONTROL + '$').test(s)) {\n return { op: s };\n }\n\n // Hand-written scanner/parser for Bash quoting rules:\n //\n // 1. inside single quotes, all characters are printed literally.\n // 2. inside double quotes, all characters are printed literally\n // except variables prefixed by '$' and backslashes followed by\n // either a double quote or another backslash.\n // 3. outside of any quotes, backslashes are treated as escape\n // characters and not printed (unless they are themselves escaped)\n // 4. quote context can switch mid-token if there is no whitespace\n // between the two quote contexts (e.g. all'one'\"token\" parses as\n // \"allonetoken\")\n var SQ = \"'\";\n var DQ = '\"';\n var DS = '$';\n var BS = opts.escape || '\\\\';\n var quote = false;\n var esc = false;\n var out = '';\n var isGlob = false;\n\n for (var i = 0, len = s.length; i < len; i++) {\n var c = s.charAt(i);\n isGlob = isGlob || (!quote && (c === '*' || c === '?'));\n if (esc) {\n out += c;\n esc = false;\n }\n else if (quote) {\n if (c === quote) {\n quote = false;\n }\n else if (quote == SQ) {\n out += c;\n }\n else { // Double quote\n if (c === BS) {\n i += 1;\n c = s.charAt(i);\n if (c === DQ || c === BS || c === DS) {\n out += c;\n } else {\n out += BS + c;\n }\n }\n else if (c === DS) {\n out += parseEnvVar();\n }\n else {\n out += c;\n }\n }\n }\n else if (c === DQ || c === SQ) {\n quote = c;\n }\n else if (RegExp('^' + CONTROL + '$').test(c)) {\n return { op: s };\n }\n else if (RegExp('^#$').test(c)) {\n commented = true;\n if (out.length){\n return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }];\n }\n return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }];\n }\n else if (c === BS) {\n esc = true;\n }\n else if (c === DS) {\n out += parseEnvVar();\n }\n else out += c;\n }\n\n if (isGlob) return {op: 'glob', pattern: out};\n\n return out;\n\n function parseEnvVar() {\n i += 1;\n var varend, varname;\n //debugger\n if (s.charAt(i) === '{') {\n i += 1;\n if (s.charAt(i) === '}') {\n throw new Error(\"Bad substitution: \" + s.substr(i - 2, 3));\n }\n varend = s.indexOf('}', i);\n if (varend < 0) {\n throw new Error(\"Bad substitution: \" + s.substr(i));\n }\n varname = s.substr(i, varend - i);\n i = varend;\n }\n else if (/[*@#?$!_\\-]/.test(s.charAt(i))) {\n varname = s.charAt(i);\n i += 1;\n }\n else {\n varend = s.substr(i).match(/[^\\w\\d_]/);\n if (!varend) {\n varname = s.substr(i);\n i = s.length;\n } else {\n varname = s.substr(i, varend.index);\n i += varend.index - 1;\n }\n }\n return getVar(null, '', varname);\n }\n })\n // finalize parsed aruments\n .reduce(function(prev, arg){\n if (arg === undefined){\n return prev;\n }\n return prev.concat(arg);\n },[]);\n\n function getVar (_, pre, key) {\n var r = typeof env === 'function' ? env(key) : env[key];\n if (r === undefined && key != '')\n r = '';\n else if (r === undefined)\n r = '$';\n\n if (typeof r === 'object') {\n return pre + TOKEN + JSON.stringify(r) + TOKEN;\n }\n else return pre + r;\n }\n}\n","module.exports = {\n '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',\n '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':\n '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',\n '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',\n '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':\n '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',\n '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':\n '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',\n '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text':\n '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',\n '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',\n '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron':\n 'code-insiders',\n '/Applications/AppCode.app/Contents/MacOS/appcode':\n '/Applications/AppCode.app/Contents/MacOS/appcode',\n '/Applications/CLion.app/Contents/MacOS/clion':\n '/Applications/CLion.app/Contents/MacOS/clion',\n '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':\n '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',\n '/Applications/PhpStorm.app/Contents/MacOS/phpstorm':\n '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',\n '/Applications/PyCharm.app/Contents/MacOS/pycharm':\n '/Applications/PyCharm.app/Contents/MacOS/pycharm',\n '/Applications/PyCharm CE.app/Contents/MacOS/pycharm':\n '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',\n '/Applications/RubyMine.app/Contents/MacOS/rubymine':\n '/Applications/RubyMine.app/Contents/MacOS/rubymine',\n '/Applications/WebStorm.app/Contents/MacOS/webstorm':\n '/Applications/WebStorm.app/Contents/MacOS/webstorm'\n}\n","module.exports = {\n atom: 'atom',\n Brackets: 'brackets',\n code: 'code',\n emacs: 'emacs',\n 'idea.sh': 'idea',\n 'phpstorm.sh': 'phpstorm',\n 'pycharm.sh': 'pycharm',\n 'rubymine.sh': 'rubymine',\n sublime_text: 'subl',\n vim: 'vim',\n 'webstorm.sh': 'webstorm'\n}\n","module.exports = [\n 'Brackets.exe',\n 'Code.exe',\n 'atom.exe',\n 'sublime_text.exe',\n 'notepad++.exe',\n 'clion.exe',\n 'clion64.exe',\n 'idea.exe',\n 'idea64.exe',\n 'phpstorm.exe',\n 'phpstorm64.exe',\n 'pycharm.exe',\n 'pycharm64.exe',\n 'rubymine.exe',\n 'rubymine64.exe',\n 'webstorm.exe',\n 'webstorm64.exe'\n]\n","const path = require('path')\nconst shellQuote = require('shell-quote')\nconst childProcess = require('child_process')\n\n// Map from full process name to binary that starts the process\n// We can't just re-use full process name, because it will spawn a new instance\n// of the app every time\nconst COMMON_EDITORS_OSX = require('./editor-info/osx')\nconst COMMON_EDITORS_LINUX = require('./editor-info/linux')\nconst COMMON_EDITORS_WIN = require('./editor-info/windows')\n\nmodule.exports = function guessEditor (specifiedEditor) {\n if (specifiedEditor) {\n return shellQuote.parse(specifiedEditor)\n }\n // We can find out which editor is currently running by:\n // `ps x` on macOS and Linux\n // `Get-Process` on Windows\n try {\n if (process.platform === 'darwin') {\n const output = childProcess.execSync('ps x').toString()\n const processNames = Object.keys(COMMON_EDITORS_OSX)\n for (let i = 0; i < processNames.length; i++) {\n const processName = processNames[i]\n if (output.indexOf(processName) !== -1) {\n return [COMMON_EDITORS_OSX[processName]]\n }\n }\n } else if (process.platform === 'win32') {\n const output = childProcess\n .execSync('powershell -Command \"Get-Process | Select-Object Path\"', {\n stdio: ['pipe', 'pipe', 'ignore']\n })\n .toString()\n const runningProcesses = output.split('\\r\\n')\n for (let i = 0; i < runningProcesses.length; i++) {\n // `Get-Process` sometimes returns empty lines\n if (!runningProcesses[i]) {\n continue\n }\n\n const fullProcessPath = runningProcesses[i].trim()\n const shortProcessName = path.basename(fullProcessPath)\n\n if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {\n return [fullProcessPath]\n }\n }\n } else if (process.platform === 'linux') {\n // --no-heading No header line\n // x List all processes owned by you\n // -o comm Need only names column\n const output = childProcess\n .execSync('ps x --no-heading -o comm --sort=comm')\n .toString()\n const processNames = Object.keys(COMMON_EDITORS_LINUX)\n for (let i = 0; i < processNames.length; i++) {\n const processName = processNames[i]\n if (output.indexOf(processName) !== -1) {\n return [COMMON_EDITORS_LINUX[processName]]\n }\n }\n }\n } catch (error) {\n // Ignore...\n }\n\n // Last resort, use old skool env vars\n if (process.env.VISUAL) {\n return [process.env.VISUAL]\n } else if (process.env.EDITOR) {\n return [process.env.EDITOR]\n }\n\n return [null]\n}\n","const path = require('path')\n\n// normalize file/line numbers into command line args for specific editors\nmodule.exports = function getArgumentsForPosition (\n editor,\n fileName,\n lineNumber,\n columnNumber = 1\n) {\n const editorBasename = path.basename(editor).replace(/\\.(exe|cmd|bat)$/i, '')\n switch (editorBasename) {\n case 'atom':\n case 'Atom':\n case 'Atom Beta':\n case 'subl':\n case 'sublime':\n case 'sublime_text':\n case 'wstorm':\n case 'charm':\n return [`${fileName}:${lineNumber}:${columnNumber}`]\n case 'notepad++':\n return ['-n' + lineNumber, fileName]\n case 'vim':\n case 'mvim':\n return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName]\n case 'joe':\n return ['+' + `${lineNumber}`, fileName]\n case 'emacs':\n case 'emacsclient':\n return [`+${lineNumber}:${columnNumber}`, fileName]\n case 'rmate':\n case 'mate':\n case 'mine':\n return ['--line', lineNumber, fileName]\n case 'code':\n case 'code-insiders':\n case 'Code':\n return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`]\n case 'appcode':\n case 'clion':\n case 'clion64':\n case 'idea':\n case 'idea64':\n case 'phpstorm':\n case 'phpstorm64':\n case 'pycharm':\n case 'pycharm64':\n case 'rubymine':\n case 'rubymine64':\n case 'webstorm':\n case 'webstorm64':\n return ['--line', lineNumber, fileName]\n }\n\n // For all others, drop the lineNumber until we have\n // a mapping above, since providing the lineNumber incorrectly\n // can result in errors or confusing behavior.\n return [fileName]\n}\n","/**\n * Copyright (c) 2015-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file at\n * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE\n *\n * Modified by Yuxi Evan You\n */\n\nconst fs = require('fs')\nconst os = require('os')\nconst path = require('path')\nconst chalk = require('chalk')\nconst childProcess = require('child_process')\n\nconst guessEditor = require('./guess')\nconst getArgumentsForPosition = require('./get-args')\n\nfunction wrapErrorCallback (cb) {\n return (fileName, errorMessage) => {\n console.log()\n console.log(\n chalk.red('Could not open ' + path.basename(fileName) + ' in the editor.')\n )\n if (errorMessage) {\n if (errorMessage[errorMessage.length - 1] !== '.') {\n errorMessage += '.'\n }\n console.log(\n chalk.red('The editor process exited with an error: ' + errorMessage)\n )\n }\n console.log()\n if (cb) cb(fileName, errorMessage)\n }\n}\n\nfunction isTerminalEditor (editor) {\n switch (editor) {\n case 'vim':\n case 'emacs':\n case 'nano':\n return true\n }\n return false\n}\n\nconst positionRE = /:(\\d+)(:(\\d+))?$/\nfunction parseFile (file) {\n const fileName = file.replace(positionRE, '')\n const match = file.match(positionRE)\n const lineNumber = match && match[1]\n const columnNumber = match && match[3]\n return {\n fileName,\n lineNumber,\n columnNumber\n }\n}\n\nlet _childProcess = null\n\nfunction launchEditor (file, specifiedEditor, onErrorCallback) {\n const parsed = parseFile(file)\n let { fileName } = parsed\n const { lineNumber, columnNumber } = parsed\n\n if (!fs.existsSync(fileName)) {\n return\n }\n\n if (typeof specifiedEditor === 'function') {\n onErrorCallback = specifiedEditor\n specifiedEditor = undefined\n }\n\n onErrorCallback = wrapErrorCallback(onErrorCallback)\n\n const [editor, ...args] = guessEditor(specifiedEditor)\n if (!editor) {\n onErrorCallback(fileName, null)\n return\n }\n\n if (\n process.platform === 'linux' &&\n fileName.startsWith('/mnt/') &&\n /Microsoft/i.test(os.release())\n ) {\n // Assume WSL / \"Bash on Ubuntu on Windows\" is being used, and\n // that the file exists on the Windows file system.\n // `os.release()` is \"4.4.0-43-Microsoft\" in the current release\n // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364\n // When a Windows editor is specified, interop functionality can\n // handle the path translation, but only if a relative path is used.\n fileName = path.relative('', fileName)\n }\n\n if (lineNumber) {\n const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber)\n args.push.apply(args, extraArgs)\n } else {\n args.push(fileName)\n }\n\n if (_childProcess && isTerminalEditor(editor)) {\n // There's an existing editor process already and it's attached\n // to the terminal, so go kill it. Otherwise two separate editor\n // instances attach to the stdin/stdout which gets confusing.\n _childProcess.kill('SIGKILL')\n }\n\n if (process.platform === 'win32') {\n // On Windows, launch the editor in a shell because spawn can only\n // launch .exe files.\n _childProcess = childProcess.spawn(\n 'cmd.exe',\n ['/C', editor].concat(args),\n { stdio: 'inherit' }\n )\n } else {\n _childProcess = childProcess.spawn(editor, args, { stdio: 'inherit' })\n }\n _childProcess.on('exit', function (errorCode) {\n _childProcess = null\n\n if (errorCode) {\n onErrorCallback(fileName, '(code ' + errorCode + ')')\n }\n })\n\n _childProcess.on('error', function (error) {\n onErrorCallback(fileName, error.message)\n })\n}\n\nmodule.exports = launchEditor\n","const url = require('url')\nconst path = require('path')\nconst launch = require('launch-editor')\n\nmodule.exports = (specifiedEditor, srcRoot, onErrorCallback) => {\n if (typeof specifiedEditor === 'function') {\n onErrorCallback = specifiedEditor\n specifiedEditor = undefined\n }\n\n if (typeof srcRoot === 'function') {\n onErrorCallback = srcRoot\n srcRoot = undefined\n }\n\n srcRoot = srcRoot || process.cwd()\n\n return function launchEditorMiddleware (req, res, next) {\n const { file } = url.parse(req.url, true).query || {}\n if (!file) {\n res.statusCode = 500\n res.end(`launch-editor-middleware: required query param \"file\" is missing.`)\n } else {\n launch(path.resolve(srcRoot, file), specifiedEditor, onErrorCallback)\n res.end()\n }\n }\n}\n","import path from 'path'\nimport { Loader, Plugin, ImportKind } from 'esbuild'\nimport { KNOWN_ASSET_TYPES } from '../constants'\nimport { ResolvedConfig } from '..'\nimport {\n isRunningWithYarnPnp,\n flattenId,\n normalizePath,\n isExternalUrl\n} from '../utils'\nimport { browserExternalId } from '../plugins/resolve'\nimport { ExportsData } from '.'\n\nconst externalTypes = [\n 'css',\n // supported pre-processor types\n 'less',\n 'sass',\n 'scss',\n 'styl',\n 'stylus',\n 'pcss',\n 'postcss',\n // known SFC types\n 'vue',\n 'svelte',\n 'marko',\n 'astro',\n // JSX/TSX may be configured to be compiled differently from how esbuild\n // handles it by default, so exclude them as well\n 'jsx',\n 'tsx',\n ...KNOWN_ASSET_TYPES\n]\n\nexport function esbuildDepPlugin(\n qualified: Record,\n exportsData: Record,\n config: ResolvedConfig,\n ssr?: boolean\n): Plugin {\n // default resolver which prefers ESM\n const _resolve = config.createResolver({ asSrc: false })\n\n // cjs resolver that prefers Node\n const _resolveRequire = config.createResolver({\n asSrc: false,\n isRequire: true\n })\n\n const resolve = (\n id: string,\n importer: string,\n kind: ImportKind,\n resolveDir?: string\n ): Promise => {\n let _importer: string\n // explicit resolveDir - this is passed only during yarn pnp resolve for\n // entries\n if (resolveDir) {\n _importer = normalizePath(path.join(resolveDir, '*'))\n } else {\n // map importer ids to file paths for correct resolution\n _importer = importer in qualified ? qualified[importer] : importer\n }\n const resolver = kind.startsWith('require') ? _resolveRequire : _resolve\n return resolver(id, _importer, undefined, ssr)\n }\n\n return {\n name: 'vite:dep-pre-bundle',\n setup(build) {\n // externalize assets and commonly known non-js file types\n build.onResolve(\n {\n filter: new RegExp(`\\\\.(` + externalTypes.join('|') + `)(\\\\?.*)?$`)\n },\n async ({ path: id, importer, kind }) => {\n const resolved = await resolve(id, importer, kind)\n if (resolved) {\n return {\n path: resolved,\n external: true\n }\n }\n }\n )\n\n function resolveEntry(id: string) {\n const flatId = flattenId(id)\n if (flatId in qualified) {\n return {\n path: flatId,\n namespace: 'dep'\n }\n }\n }\n\n build.onResolve(\n { filter: /^[\\w@][^:]/ },\n async ({ path: id, importer, kind }) => {\n // ensure esbuild uses our resolved entries\n let entry: { path: string; namespace: string } | undefined\n // if this is an entry, return entry namespace resolve result\n if (!importer) {\n if ((entry = resolveEntry(id))) return entry\n // check if this is aliased to an entry - also return entry namespace\n const aliased = await _resolve(id, undefined, true)\n if (aliased && (entry = resolveEntry(aliased))) {\n return entry\n }\n }\n\n // use vite's own resolver\n const resolved = await resolve(id, importer, kind)\n if (resolved) {\n if (resolved.startsWith(browserExternalId)) {\n return {\n path: id,\n namespace: 'browser-external'\n }\n }\n if (isExternalUrl(resolved)) {\n return {\n path: resolved,\n external: true\n }\n }\n return {\n path: path.resolve(resolved)\n }\n }\n }\n )\n\n // For entry files, we'll read it ourselves and construct a proxy module\n // to retain the entry's raw id instead of file path so that esbuild\n // outputs desired output file structure.\n // It is necessary to do the re-exporting to separate the virtual proxy\n // module from the actual module since the actual module may get\n // referenced via relative imports - if we don't separate the proxy and\n // the actual module, esbuild will create duplicated copies of the same\n // module!\n const root = path.resolve(config.root)\n build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => {\n const entryFile = qualified[id]\n\n let relativePath = normalizePath(path.relative(root, entryFile))\n if (\n !relativePath.startsWith('./') &&\n !relativePath.startsWith('../') &&\n relativePath !== '.'\n ) {\n relativePath = `./${relativePath}`\n }\n\n let contents = ''\n const data = exportsData[id]\n const [imports, exports] = data\n if (!imports.length && !exports.length) {\n // cjs\n contents += `export default require(\"${relativePath}\");`\n } else {\n if (exports.includes('default')) {\n contents += `import d from \"${relativePath}\";export default d;`\n }\n if (\n data.hasReExports ||\n exports.length > 1 ||\n exports[0] !== 'default'\n ) {\n contents += `\\nexport * from \"${relativePath}\"`\n }\n }\n\n let ext = path.extname(entryFile).slice(1)\n if (ext === 'mjs') ext = 'js'\n return {\n loader: ext as Loader,\n contents,\n resolveDir: root\n }\n })\n\n build.onLoad(\n { filter: /.*/, namespace: 'browser-external' },\n ({ path: id }) => {\n return {\n contents:\n `export default new Proxy({}, {\n get() {\n throw new Error('Module \"${id}\" has been externalized for ` +\n `browser compatibility and cannot be accessed in client code.')\n }\n})`\n }\n }\n )\n\n // yarn 2 pnp compat\n if (isRunningWithYarnPnp) {\n build.onResolve(\n { filter: /.*/ },\n async ({ path, importer, kind, resolveDir }) => ({\n // pass along resolveDir for entries\n path: await resolve(path, importer, kind, resolveDir)\n })\n )\n build.onLoad({ filter: /.*/ }, async (args) => ({\n contents: await require('fs').promises.readFile(args.path),\n loader: 'default'\n }))\n }\n }\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport chalk from 'chalk'\nimport { createHash } from 'crypto'\nimport { build, BuildOptions as EsbuildBuildOptions } from 'esbuild'\nimport { ResolvedConfig } from '../config'\nimport {\n createDebugger,\n emptyDir,\n lookupFile,\n normalizePath,\n writeFile,\n flattenId,\n normalizeId\n} from '../utils'\nimport { esbuildDepPlugin } from './esbuildDepPlugin'\nimport { init, parse } from 'es-module-lexer'\nimport { scanImports } from './scan'\nimport { transformWithEsbuild } from '../plugins/esbuild'\nimport { performance } from 'perf_hooks'\n\nconst debug = createDebugger('vite:deps')\n\nexport type ExportsData = ReturnType & {\n // es-module-lexer has a facade detection but isn't always accurate for our\n // use case when the module has default export\n hasReExports?: true\n}\n\nexport interface DepOptimizationOptions {\n /**\n * By default, Vite will crawl your index.html to detect dependencies that\n * need to be pre-bundled. If build.rollupOptions.input is specified, Vite\n * will crawl those entry points instead.\n *\n * If neither of these fit your needs, you can specify custom entries using\n * this option - the value should be a fast-glob pattern or array of patterns\n * (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from\n * vite project root. This will overwrite default entries inference.\n */\n entries?: string | string[]\n /**\n * Force optimize listed dependencies (must be resolvable import paths,\n * cannot be globs).\n */\n include?: string[]\n /**\n * Do not optimize these dependencies (must be resolvable import paths,\n * cannot be globs).\n */\n exclude?: string[]\n /**\n * Options to pass to esbuild during the dep scanning and optimization\n *\n * Certain options are omitted since changing them would not be compatible\n * with Vite's dep optimization.\n *\n * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option\n * - `plugins` are merged with Vite's dep plugin\n * - `keepNames` takes precedence over the deprecated `optimizeDeps.keepNames`\n *\n * https://esbuild.github.io/api\n */\n esbuildOptions?: Omit<\n EsbuildBuildOptions,\n | 'bundle'\n | 'entryPoints'\n | 'external'\n | 'write'\n | 'watch'\n | 'outdir'\n | 'outfile'\n | 'outbase'\n | 'outExtension'\n | 'metafile'\n >\n /**\n * @deprecated use `esbuildOptions.keepNames`\n */\n keepNames?: boolean\n}\n\nexport interface DepOptimizationMetadata {\n /**\n * The main hash is determined by user config and dependency lockfiles.\n * This is checked on server startup to avoid unnecessary re-bundles.\n */\n hash: string\n /**\n * The browser hash is determined by the main hash plus additional dependencies\n * discovered at runtime. This is used to invalidate browser requests to\n * optimized deps.\n */\n browserHash: string\n optimized: Record<\n string,\n {\n file: string\n src: string\n needsInterop: boolean\n }\n >\n}\n\nexport async function optimizeDeps(\n config: ResolvedConfig,\n force = config.server.force,\n asCommand = false,\n newDeps?: Record, // missing imports encountered after server has started\n ssr?: boolean\n): Promise {\n config = {\n ...config,\n command: 'build'\n }\n\n const { root, logger, cacheDir } = config\n const log = asCommand ? logger.info : debug\n\n if (!cacheDir) {\n log(`No cache directory. Skipping.`)\n return null\n }\n\n const dataPath = path.join(cacheDir, '_metadata.json')\n const mainHash = getDepHash(root, config)\n const data: DepOptimizationMetadata = {\n hash: mainHash,\n browserHash: mainHash,\n optimized: {}\n }\n\n if (!force) {\n let prevData: DepOptimizationMetadata | undefined\n try {\n prevData = JSON.parse(fs.readFileSync(dataPath, 'utf-8'))\n } catch (e) {}\n // hash is consistent, no need to re-bundle\n if (prevData && prevData.hash === data.hash) {\n log('Hash is consistent. Skipping. Use --force to override.')\n return prevData\n }\n }\n\n if (fs.existsSync(cacheDir)) {\n emptyDir(cacheDir)\n } else {\n fs.mkdirSync(cacheDir, { recursive: true })\n }\n // a hint for Node.js\n // all files in the cache directory should be recognized as ES modules\n writeFile(\n path.resolve(cacheDir, 'package.json'),\n JSON.stringify({ type: 'module' })\n )\n\n let deps: Record, missing: Record\n if (!newDeps) {\n ;({ deps, missing } = await scanImports(config))\n } else {\n deps = newDeps\n missing = {}\n }\n\n // update browser hash\n data.browserHash = createHash('sha256')\n .update(data.hash + JSON.stringify(deps))\n .digest('hex')\n .substr(0, 8)\n\n const missingIds = Object.keys(missing)\n if (missingIds.length) {\n throw new Error(\n `The following dependencies are imported but could not be resolved:\\n\\n ${missingIds\n .map(\n (id) =>\n `${chalk.cyan(id)} ${chalk.white.dim(\n `(imported by ${missing[id]})`\n )}`\n )\n .join(`\\n `)}\\n\\nAre they installed?`\n )\n }\n\n const include = config.optimizeDeps?.include\n if (include) {\n const resolve = config.createResolver({ asSrc: false })\n for (const id of include) {\n // normalize 'foo >bar` as 'foo > bar' to prevent same id being added\n // and for pretty printing\n const normalizedId = normalizeId(id)\n if (!deps[normalizedId]) {\n const entry = await resolve(id)\n if (entry) {\n deps[normalizedId] = entry\n } else {\n throw new Error(\n `Failed to resolve force included dependency: ${chalk.cyan(id)}`\n )\n }\n }\n }\n }\n\n const qualifiedIds = Object.keys(deps)\n\n if (!qualifiedIds.length) {\n writeFile(dataPath, JSON.stringify(data, null, 2))\n log(`No dependencies to bundle. Skipping.\\n\\n\\n`)\n return data\n }\n\n const total = qualifiedIds.length\n const maxListed = 5\n const listed = Math.min(total, maxListed)\n const extra = Math.max(0, total - maxListed)\n const depsString = chalk.yellow(\n qualifiedIds.slice(0, listed).join(`\\n `) +\n (extra > 0 ? `\\n (...and ${extra} more)` : ``)\n )\n if (!asCommand) {\n if (!newDeps) {\n // This is auto run on server start - let the user know that we are\n // pre-optimizing deps\n logger.info(\n chalk.greenBright(`Pre-bundling dependencies:\\n ${depsString}`)\n )\n logger.info(\n `(this will be run only when your dependencies or config have changed)`\n )\n }\n } else {\n logger.info(chalk.greenBright(`Optimizing dependencies:\\n ${depsString}`))\n }\n\n // esbuild generates nested directory output with lowest common ancestor base\n // this is unpredictable and makes it difficult to analyze entry / output\n // mapping. So what we do here is:\n // 1. flatten all ids to eliminate slash\n // 2. in the plugin, read the entry ourselves as virtual files to retain the\n // path.\n const flatIdDeps: Record = {}\n const idToExports: Record = {}\n const flatIdToExports: Record = {}\n\n const { plugins = [], ...esbuildOptions } =\n config.optimizeDeps?.esbuildOptions ?? {}\n\n await init\n for (const id in deps) {\n const flatId = flattenId(id)\n const filePath = (flatIdDeps[flatId] = deps[id])\n const entryContent = fs.readFileSync(filePath, 'utf-8')\n let exportsData: ExportsData\n try {\n exportsData = parse(entryContent) as ExportsData\n } catch {\n debug(\n `Unable to parse dependency: ${id}. Trying again with a JSX transform.`\n )\n const transformed = await transformWithEsbuild(entryContent, filePath, {\n loader: 'jsx'\n })\n // Ensure that optimization won't fail by defaulting '.js' to the JSX parser.\n // This is useful for packages such as Gatsby.\n esbuildOptions.loader = {\n '.js': 'jsx',\n ...esbuildOptions.loader\n }\n exportsData = parse(transformed.code) as ExportsData\n }\n for (const { ss, se } of exportsData[0]) {\n const exp = entryContent.slice(ss, se)\n if (/export\\s+\\*\\s+from/.test(exp)) {\n exportsData.hasReExports = true\n }\n }\n idToExports[id] = exportsData\n flatIdToExports[flatId] = exportsData\n }\n\n const define: Record = {\n 'process.env.NODE_ENV': JSON.stringify(config.mode)\n }\n for (const key in config.define) {\n const value = config.define[key]\n define[key] = typeof value === 'string' ? value : JSON.stringify(value)\n }\n\n const start = performance.now()\n\n const result = await build({\n absWorkingDir: process.cwd(),\n entryPoints: Object.keys(flatIdDeps),\n bundle: true,\n format: 'esm',\n target: config.build.target || undefined,\n external: config.optimizeDeps?.exclude,\n logLevel: 'error',\n splitting: true,\n sourcemap: true,\n outdir: cacheDir,\n ignoreAnnotations: true,\n metafile: true,\n define,\n plugins: [\n ...plugins,\n esbuildDepPlugin(flatIdDeps, flatIdToExports, config, ssr)\n ],\n ...esbuildOptions\n })\n\n const meta = result.metafile!\n\n // the paths in `meta.outputs` are relative to `process.cwd()`\n const cacheDirOutputPath = path.relative(process.cwd(), cacheDir)\n\n for (const id in deps) {\n const entry = deps[id]\n data.optimized[id] = {\n file: normalizePath(path.resolve(cacheDir, flattenId(id) + '.js')),\n src: entry,\n needsInterop: needsInterop(\n id,\n idToExports[id],\n meta.outputs,\n cacheDirOutputPath\n )\n }\n }\n\n writeFile(dataPath, JSON.stringify(data, null, 2))\n\n debug(`deps bundled in ${(performance.now() - start).toFixed(2)}ms`)\n return data\n}\n\n// https://github.com/vitejs/vite/issues/1724#issuecomment-767619642\n// a list of modules that pretends to be ESM but still uses `require`.\n// this causes esbuild to wrap them as CJS even when its entry appears to be ESM.\nconst KNOWN_INTEROP_IDS = new Set(['moment'])\n\nfunction needsInterop(\n id: string,\n exportsData: ExportsData,\n outputs: Record,\n cacheDirOutputPath: string\n): boolean {\n if (KNOWN_INTEROP_IDS.has(id)) {\n return true\n }\n const [imports, exports] = exportsData\n // entry has no ESM syntax - likely CJS or UMD\n if (!exports.length && !imports.length) {\n return true\n }\n\n // if a peer dependency used require() on a ESM dependency, esbuild turns the\n // ESM dependency's entry chunk into a single default export... detect\n // such cases by checking exports mismatch, and force interop.\n const flatId = flattenId(id) + '.js'\n let generatedExports: string[] | undefined\n for (const output in outputs) {\n if (\n normalizePath(output) ===\n normalizePath(path.join(cacheDirOutputPath, flatId))\n ) {\n generatedExports = outputs[output].exports\n break\n }\n }\n\n if (\n !generatedExports ||\n (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))\n ) {\n return true\n }\n return false\n}\n\nfunction isSingleDefaultExport(exports: readonly string[]) {\n return exports.length === 1 && exports[0] === 'default'\n}\n\nconst lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']\n\nfunction getDepHash(root: string, config: ResolvedConfig): string {\n let content = lookupFile(root, lockfileFormats) || ''\n // also take config into account\n // only a subset of config options that can affect dep optimization\n content += JSON.stringify(\n {\n mode: config.mode,\n root: config.root,\n resolve: config.resolve,\n assetsInclude: config.assetsInclude,\n plugins: config.plugins.map((p) => p.name),\n optimizeDeps: {\n include: config.optimizeDeps?.include,\n exclude: config.optimizeDeps?.exclude\n }\n },\n (_, value) => {\n if (typeof value === 'function' || value instanceof RegExp) {\n return value.toString()\n }\n return value\n }\n )\n return createHash('sha256').update(content).digest('hex').substr(0, 8)\n}\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n","import { SourceMapConsumer, RawSourceMap } from 'source-map'\nimport { ModuleGraph } from '../server/moduleGraph'\n\nlet offset: number\ntry {\n new Function('throw new Error(1)')()\n} catch (e) {\n // in Node 12, stack traces account for the function wrapper.\n // in Node 13 and later, the function wrapper adds two lines,\n // which must be subtracted to generate a valid mapping\n const match = /:(\\d+):\\d+\\)$/.exec(e.stack.split('\\n')[1])\n offset = match ? +match[1] - 1 : 0\n}\n\nexport function ssrRewriteStacktrace(\n stack: string,\n moduleGraph: ModuleGraph\n): string {\n return stack\n .split('\\n')\n .map((line) => {\n return line.replace(\n /^ {4}at (?:(.+?)\\s+\\()?(?:(.+?):(\\d+)(?::(\\d+))?)\\)?/,\n (input, varName, url, line, column) => {\n if (!url) return input\n\n const mod = moduleGraph.urlToModuleMap.get(url)\n const rawSourceMap = mod?.ssrTransformResult?.map\n\n if (!rawSourceMap) {\n return input\n }\n\n const consumer = new SourceMapConsumer(\n rawSourceMap as unknown as RawSourceMap\n )\n\n const pos = consumer.originalPositionFor({\n line: Number(line) - offset,\n column: Number(column),\n bias: SourceMapConsumer.LEAST_UPPER_BOUND\n })\n\n if (!pos.source) {\n return input\n }\n\n const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}`\n if (!varName || varName === 'eval') {\n return ` at ${source}`\n } else {\n return ` at ${varName} (${source})`\n }\n }\n )\n })\n .join('\\n')\n}\n\nexport function rebindErrorStacktrace(e: Error, stacktrace: string): void {\n const { configurable, writable } = Object.getOwnPropertyDescriptor(\n e,\n 'stack'\n )!\n if (configurable) {\n Object.defineProperty(e, 'stack', {\n value: stacktrace,\n enumerable: true,\n configurable: true,\n writable: true\n })\n } else if (writable) {\n e.stack = stacktrace\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport { pathToFileURL } from 'url'\nimport { ViteDevServer } from '..'\nimport {\n dynamicImport,\n cleanUrl,\n isBuiltin,\n resolveFrom,\n unwrapId,\n usingDynamicImport\n} from '../utils'\nimport { rebindErrorStacktrace, ssrRewriteStacktrace } from './ssrStacktrace'\nimport {\n ssrExportAllKey,\n ssrModuleExportsKey,\n ssrImportKey,\n ssrImportMetaKey,\n ssrDynamicImportKey\n} from './ssrTransform'\nimport { transformRequest } from '../server/transformRequest'\n\ninterface SSRContext {\n global: NodeJS.Global\n}\n\ntype SSRModule = Record\n\nconst pendingModules = new Map>()\nconst pendingImports = new Map()\n\nexport async function ssrLoadModule(\n url: string,\n server: ViteDevServer,\n context: SSRContext = { global },\n urlStack: string[] = []\n): Promise {\n url = unwrapId(url)\n\n // when we instantiate multiple dependency modules in parallel, they may\n // point to shared modules. We need to avoid duplicate instantiation attempts\n // by register every module as pending synchronously so that all subsequent\n // request to that module are simply waiting on the same promise.\n const pending = pendingModules.get(url)\n if (pending) {\n return pending\n }\n\n const modulePromise = instantiateModule(url, server, context, urlStack)\n pendingModules.set(url, modulePromise)\n modulePromise\n .catch(() => {\n pendingImports.delete(url)\n })\n .finally(() => {\n pendingModules.delete(url)\n })\n return modulePromise\n}\n\nasync function instantiateModule(\n url: string,\n server: ViteDevServer,\n context: SSRContext = { global },\n urlStack: string[] = []\n): Promise {\n const { moduleGraph } = server\n const mod = await moduleGraph.ensureEntryFromUrl(url)\n\n if (mod.ssrModule) {\n return mod.ssrModule\n }\n\n const result =\n mod.ssrTransformResult ||\n (await transformRequest(url, server, { ssr: true }))\n if (!result) {\n // TODO more info? is this even necessary?\n throw new Error(`failed to load module for ssr: ${url}`)\n }\n\n const ssrModule = {\n [Symbol.toStringTag]: 'Module'\n }\n Object.defineProperty(ssrModule, '__esModule', { value: true })\n\n // Tolerate circular imports by ensuring the module can be\n // referenced before it's been instantiated.\n mod.ssrModule = ssrModule\n\n const ssrImportMeta = {\n // The filesystem URL, matching native Node.js modules\n url: pathToFileURL(mod.file!).toString()\n }\n\n urlStack = urlStack.concat(url)\n const isCircular = (url: string) => urlStack.includes(url)\n\n // Since dynamic imports can happen in parallel, we need to\n // account for multiple pending deps and duplicate imports.\n const pendingDeps: string[] = []\n\n const ssrImport = async (dep: string) => {\n if (dep[0] !== '.' && dep[0] !== '/') {\n return nodeImport(dep, mod.file, server.config)\n }\n dep = unwrapId(dep)\n if (!isCircular(dep) && !pendingImports.get(dep)?.some(isCircular)) {\n pendingDeps.push(dep)\n if (pendingDeps.length === 1) {\n pendingImports.set(url, pendingDeps)\n }\n await ssrLoadModule(dep, server, context, urlStack)\n if (pendingDeps.length === 1) {\n pendingImports.delete(url)\n } else {\n pendingDeps.splice(pendingDeps.indexOf(dep), 1)\n }\n }\n return moduleGraph.urlToModuleMap.get(dep)?.ssrModule\n }\n\n const ssrDynamicImport = (dep: string) => {\n // #3087 dynamic import vars is ignored at rewrite import path,\n // so here need process relative path\n if (dep[0] === '.') {\n dep = path.posix.resolve(path.dirname(url), dep)\n }\n return ssrImport(dep)\n }\n\n function ssrExportAll(sourceModule: any) {\n for (const key in sourceModule) {\n if (key !== 'default') {\n Object.defineProperty(ssrModule, key, {\n enumerable: true,\n configurable: true,\n get() {\n return sourceModule[key]\n }\n })\n }\n }\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n const AsyncFunction = async function () {}.constructor as typeof Function\n const initModule = new AsyncFunction(\n `global`,\n ssrModuleExportsKey,\n ssrImportMetaKey,\n ssrImportKey,\n ssrDynamicImportKey,\n ssrExportAllKey,\n result.code + `\\n//# sourceURL=${mod.url}`\n )\n await initModule(\n context.global,\n ssrModule,\n ssrImportMeta,\n ssrImport,\n ssrDynamicImport,\n ssrExportAll\n )\n } catch (e) {\n const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph)\n rebindErrorStacktrace(e, stacktrace)\n server.config.logger.error(\n `Error when evaluating SSR module ${url}:\\n${stacktrace}`,\n {\n timestamp: true,\n clear: server.config.clearScreen,\n error: e\n }\n )\n throw e\n }\n\n return Object.freeze(ssrModule)\n}\n\n// In node@12+ we can use dynamic import to load CJS and ESM\nasync function nodeImport(\n id: string,\n importer: string | null,\n config: ViteDevServer['config']\n) {\n let url: string\n // `resolve` doesn't handle `node:` builtins, so handle them directly\n if (id.startsWith('node:') || isBuiltin(id)) {\n url = id\n } else {\n url = resolve(id, importer, config.root, !!config.resolve.preserveSymlinks)\n if (usingDynamicImport) {\n url = pathToFileURL(url).toString()\n }\n }\n const mod = await dynamicImport(url)\n return proxyESM(id, mod)\n}\n\n// rollup-style default import interop for cjs\nfunction proxyESM(id: string, mod: any) {\n const defaultExport = mod.__esModule\n ? mod.default\n : mod.default\n ? mod.default\n : mod\n return new Proxy(mod, {\n get(mod, prop) {\n if (prop === 'default') return defaultExport\n return mod[prop]\n }\n })\n}\n\nconst resolveCache = new Map()\n\nfunction resolve(\n id: string,\n importer: string | null,\n root: string,\n preserveSymlinks: boolean\n) {\n const key = id + importer + root\n const cached = resolveCache.get(key)\n if (cached) {\n return cached\n }\n const resolveDir =\n importer && fs.existsSync(cleanUrl(importer))\n ? path.dirname(importer)\n : root\n const resolved = resolveFrom(id, resolveDir, preserveSymlinks, true)\n resolveCache.set(key, resolved)\n return resolved\n}\n","import chalk from 'chalk'\nimport { optimizeDeps } from '.'\nimport { ViteDevServer } from '..'\nimport { resolveSSRExternal } from '../ssr/ssrExternal'\n\n/**\n * The amount to wait for requests to register newly found dependencies before triggering\n * a re-bundle + page reload\n */\nconst debounceMs = 100\n\nexport function createMissingImporterRegisterFn(\n server: ViteDevServer\n): (id: string, resolved: string, ssr?: boolean) => void {\n const { logger } = server.config\n let knownOptimized = server._optimizeDepsMetadata!.optimized\n let currentMissing: Record = {}\n let handle: NodeJS.Timeout\n\n let pendingResolve: (() => void) | null = null\n\n async function rerun(ssr: boolean | undefined) {\n const newDeps = currentMissing\n currentMissing = {}\n\n logger.info(\n chalk.yellow(\n `new dependencies found: ${Object.keys(newDeps).join(\n ', '\n )}, updating...`\n ),\n {\n timestamp: true\n }\n )\n\n for (const id in knownOptimized) {\n newDeps[id] = knownOptimized[id].src\n }\n\n try {\n // Nullify previous metadata so that the resolver won't\n // resolve to optimized files during the optimizer re-run\n server._isRunningOptimizer = true\n server._optimizeDepsMetadata = null\n\n const newData = (server._optimizeDepsMetadata = await optimizeDeps(\n server.config,\n true,\n false,\n newDeps,\n ssr\n ))\n knownOptimized = newData!.optimized\n\n // update ssr externals\n server._ssrExternals = resolveSSRExternal(\n server.config,\n Object.keys(knownOptimized)\n )\n\n logger.info(\n chalk.greenBright(`✨ dependencies updated, reloading page...`),\n { timestamp: true }\n )\n } catch (e) {\n logger.error(\n chalk.red(`error while updating dependencies:\\n${e.stack}`),\n { timestamp: true, error: e }\n )\n } finally {\n server._isRunningOptimizer = false\n pendingResolve && pendingResolve()\n server._pendingReload = pendingResolve = null\n }\n\n // Cached transform results have stale imports (resolved to\n // old locations) so they need to be invalidated before the page is\n // reloaded.\n server.moduleGraph.invalidateAll()\n\n server.ws.send({\n type: 'full-reload',\n path: '*'\n })\n }\n\n return function registerMissingImport(\n id: string,\n resolved: string,\n ssr?: boolean\n ) {\n if (!knownOptimized[id]) {\n currentMissing[id] = resolved\n if (handle) clearTimeout(handle)\n handle = setTimeout(() => rerun(ssr), debounceMs)\n server._pendingReload = new Promise((r) => {\n pendingResolve = r\n })\n }\n }\n}\n","import fs from 'fs'\nimport { dirname } from 'path'\nimport { join } from 'path'\n\n// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079\nconst ROOT_FILES = [\n // '.git',\n\n // https://pnpm.js.org/workspaces/\n 'pnpm-workspace.yaml'\n\n // https://rushjs.io/pages/advanced/config_files/\n // 'rush.json',\n\n // https://nx.dev/latest/react/getting-started/nx-setup\n // 'workspace.json',\n // 'nx.json'\n]\n\n// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces\n// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it\nfunction hasWorkspacePackageJSON(root: string): boolean {\n const path = join(root, 'package.json')\n try {\n fs.accessSync(path, fs.constants.R_OK)\n } catch {\n return false\n }\n const content = JSON.parse(fs.readFileSync(path, 'utf-8')) || {}\n return !!content.workspaces\n}\n\nfunction hasRootFile(root: string): boolean {\n return ROOT_FILES.some((file) => fs.existsSync(join(root, file)))\n}\n\nfunction hasPackageJSON(root: string) {\n const path = join(root, 'package.json')\n return fs.existsSync(path)\n}\n\n/**\n * Search up for the nearest `package.json`\n */\nexport function searchForPackageRoot(current: string, root = current): string {\n if (hasPackageJSON(current)) return current\n\n const dir = dirname(current)\n // reach the fs root\n if (!dir || dir === current) return root\n\n return searchForPackageRoot(dir, root)\n}\n\n/**\n * Search up for the nearest workspace root\n */\nexport function searchForWorkspaceRoot(\n current: string,\n root = searchForPackageRoot(current)\n): string {\n if (hasRootFile(current)) return current\n if (hasWorkspacePackageJSON(current)) return current\n\n const dir = dirname(current)\n // reach the fs root\n if (!dir || dir === current) return root\n\n return searchForWorkspaceRoot(dir, root)\n}\n","import fs from 'fs'\nimport path from 'path'\nimport * as net from 'net'\nimport * as http from 'http'\nimport * as https from 'https'\nimport connect from 'connect'\nimport corsMiddleware from 'cors'\nimport chalk from 'chalk'\nimport { AddressInfo } from 'net'\nimport chokidar from 'chokidar'\nimport { resolveHttpsConfig, resolveHttpServer, httpServerStart } from './http'\nimport { resolveConfig, InlineConfig, ResolvedConfig } from '../config'\nimport { createPluginContainer, PluginContainer } from './pluginContainer'\nimport { FSWatcher, WatchOptions } from 'types/chokidar'\nimport { createWebSocketServer, WebSocketServer } from './ws'\nimport { baseMiddleware } from './middlewares/base'\nimport { proxyMiddleware, ProxyOptions } from './middlewares/proxy'\nimport { spaFallbackMiddleware } from './middlewares/spaFallback'\nimport { transformMiddleware } from './middlewares/transform'\nimport {\n createDevHtmlTransformFn,\n indexHtmlMiddleware\n} from './middlewares/indexHtml'\nimport {\n serveRawFsMiddleware,\n servePublicMiddleware,\n serveStaticMiddleware\n} from './middlewares/static'\nimport { timeMiddleware } from './middlewares/time'\nimport { ModuleGraph, ModuleNode } from './moduleGraph'\nimport { Connect } from 'types/connect'\nimport { ensureLeadingSlash, normalizePath } from '../utils'\nimport { errorMiddleware, prepareError } from './middlewares/error'\nimport { handleHMRUpdate, HmrOptions, handleFileAddUnlink } from './hmr'\nimport { openBrowser } from './openBrowser'\nimport launchEditorMiddleware from 'launch-editor-middleware'\nimport {\n TransformOptions,\n TransformResult,\n transformRequest\n} from './transformRequest'\nimport {\n transformWithEsbuild,\n ESBuildTransformResult\n} from '../plugins/esbuild'\nimport { TransformOptions as EsbuildTransformOptions } from 'esbuild'\nimport { DepOptimizationMetadata, optimizeDeps } from '../optimizer'\nimport { ssrLoadModule } from '../ssr/ssrModuleLoader'\nimport { resolveSSRExternal } from '../ssr/ssrExternal'\nimport {\n rebindErrorStacktrace,\n ssrRewriteStacktrace\n} from '../ssr/ssrStacktrace'\nimport { createMissingImporterRegisterFn } from '../optimizer/registerMissing'\nimport { resolveHostname } from '../utils'\nimport { searchForWorkspaceRoot } from './searchRoot'\nimport { CLIENT_DIR } from '../constants'\nimport { printHttpServerUrls } from '../logger'\n\nexport { searchForWorkspaceRoot } from './searchRoot'\n\nexport interface ServerOptions {\n host?: string | boolean\n port?: number\n /**\n * Enable TLS + HTTP/2.\n * Note: this downgrades to TLS only when the proxy option is also used.\n */\n https?: boolean | https.ServerOptions\n /**\n * Open browser window on startup\n */\n open?: boolean | string\n /**\n * Force dep pre-optimization regardless of whether deps have changed.\n */\n force?: boolean\n /**\n * Configure HMR-specific options (port, host, path & protocol)\n */\n hmr?: HmrOptions | boolean\n /**\n * chokidar watch options\n * https://github.com/paulmillr/chokidar#api\n */\n watch?: WatchOptions\n /**\n * Configure custom proxy rules for the dev server. Expects an object\n * of `{ key: options }` pairs.\n * Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).\n * Full options [here](https://github.com/http-party/node-http-proxy#options).\n *\n * Example `vite.config.js`:\n * ``` js\n * module.exports = {\n * proxy: {\n * // string shorthand\n * '/foo': 'http://localhost:4567/foo',\n * // with options\n * '/api': {\n * target: 'http://jsonplaceholder.typicode.com',\n * changeOrigin: true,\n * rewrite: path => path.replace(/^\\/api/, '')\n * }\n * }\n * }\n * ```\n */\n proxy?: Record\n /**\n * Configure CORS for the dev server.\n * Uses https://github.com/expressjs/cors.\n * Set to `true` to allow all methods from any origin, or configure separately\n * using an object.\n */\n cors?: CorsOptions | boolean\n /**\n * If enabled, vite will exit if specified port is already in use\n */\n strictPort?: boolean\n /**\n * Create Vite dev server to be used as a middleware in an existing server\n */\n middlewareMode?: boolean | 'html' | 'ssr'\n /**\n * Prepend this folder to http requests, for use when proxying vite as a subfolder\n * Should start and end with the `/` character\n */\n base?: string\n /**\n * Options for files served via '/\\@fs/'.\n */\n fs?: FileSystemServeOptions\n /**\n * Origin for the generated asset URLs.\n */\n origin?: string\n}\n\nexport interface ResolvedServerOptions extends ServerOptions {\n fs: Required\n}\n\nexport interface FileSystemServeOptions {\n /**\n * Strictly restrict file accessing outside of allowing paths.\n *\n * Set to `false` to disable the warning\n * Default to false at this moment, will enabled by default in the future versions.\n *\n * @experimental\n * @default undefined\n */\n strict?: boolean | undefined\n\n /**\n * Restrict accessing files outside the allowed directories.\n *\n * Accepts absolute path or a path relative to project root.\n * Will try to search up for workspace root by default.\n *\n * @experimental\n */\n allow?: string[]\n}\n\n/**\n * https://github.com/expressjs/cors#configuration-options\n */\nexport interface CorsOptions {\n origin?:\n | CorsOrigin\n | ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void)\n methods?: string | string[]\n allowedHeaders?: string | string[]\n exposedHeaders?: string | string[]\n credentials?: boolean\n maxAge?: number\n preflightContinue?: boolean\n optionsSuccessStatus?: number\n}\n\nexport type CorsOrigin = boolean | string | RegExp | (string | RegExp)[]\n\nexport type ServerHook = (\n server: ViteDevServer\n) => (() => void) | void | Promise<(() => void) | void>\n\nexport interface ViteDevServer {\n /**\n * The resolved vite config object\n */\n config: ResolvedConfig\n /**\n * A connect app instance.\n * - Can be used to attach custom middlewares to the dev server.\n * - Can also be used as the handler function of a custom http server\n * or as a middleware in any connect-style Node.js frameworks\n *\n * https://github.com/senchalabs/connect#use-middleware\n */\n middlewares: Connect.Server\n /**\n * @deprecated use `server.middlewares` instead\n */\n app: Connect.Server\n /**\n * native Node http server instance\n * will be null in middleware mode\n */\n httpServer: http.Server | null\n /**\n * chokidar watcher instance\n * https://github.com/paulmillr/chokidar#api\n */\n watcher: FSWatcher\n /**\n * web socket server with `send(payload)` method\n */\n ws: WebSocketServer\n /**\n * Rollup plugin container that can run plugin hooks on a given file\n */\n pluginContainer: PluginContainer\n /**\n * Module graph that tracks the import relationships, url to file mapping\n * and hmr state.\n */\n moduleGraph: ModuleGraph\n /**\n * Programmatically resolve, load and transform a URL and get the result\n * without going through the http request pipeline.\n */\n transformRequest(\n url: string,\n options?: TransformOptions\n ): Promise\n /**\n * Apply vite built-in HTML transforms and any plugin HTML transforms.\n */\n transformIndexHtml(\n url: string,\n html: string,\n originalUrl?: string\n ): Promise\n /**\n * Util for transforming a file with esbuild.\n * Can be useful for certain plugins.\n *\n * @deprecated import `transformWithEsbuild` from `vite` instead\n */\n transformWithEsbuild(\n code: string,\n filename: string,\n options?: EsbuildTransformOptions,\n inMap?: object\n ): Promise\n /**\n * Load a given URL as an instantiated module for SSR.\n */\n ssrLoadModule(url: string): Promise>\n /**\n * Fix ssr error stacktrace\n */\n ssrFixStacktrace(e: Error): void\n /**\n * Start the server.\n */\n listen(port?: number, isRestart?: boolean): Promise\n /**\n * Stop the server.\n */\n close(): Promise\n /**\n * Print server urls\n */\n printUrls(): void\n /**\n * @internal\n */\n _optimizeDepsMetadata: DepOptimizationMetadata | null\n /**\n * Deps that are externalized\n * @internal\n */\n _ssrExternals: string[] | null\n /**\n * @internal\n */\n _globImporters: Record<\n string,\n {\n module: ModuleNode\n importGlobs: {\n base: string\n pattern: string\n }[]\n }\n >\n /**\n * @internal\n */\n _isRunningOptimizer: boolean\n /**\n * @internal\n */\n _registerMissingImport:\n | ((id: string, resolved: string, ssr: boolean | undefined) => void)\n | null\n /**\n * @internal\n */\n _pendingReload: Promise | null\n /**\n * @internal\n */\n _pendingRequests: Record | null>\n}\n\nexport async function createServer(\n inlineConfig: InlineConfig = {}\n): Promise {\n const config = await resolveConfig(inlineConfig, 'serve', 'development')\n const root = config.root\n const serverConfig = config.server\n const httpsOptions = await resolveHttpsConfig(config)\n let { middlewareMode } = serverConfig\n if (middlewareMode === true) {\n middlewareMode = 'ssr'\n }\n\n const middlewares = connect() as Connect.Server\n const httpServer = middlewareMode\n ? null\n : await resolveHttpServer(serverConfig, middlewares, httpsOptions)\n const ws = createWebSocketServer(httpServer, config, httpsOptions)\n\n const { ignored = [], ...watchOptions } = serverConfig.watch || {}\n const watcher = chokidar.watch(path.resolve(root), {\n ignored: [\n '**/node_modules/**',\n '**/.git/**',\n ...(Array.isArray(ignored) ? ignored : [ignored])\n ],\n ignoreInitial: true,\n ignorePermissionErrors: true,\n disableGlobbing: true,\n ...watchOptions\n }) as FSWatcher\n\n const plugins = config.plugins\n const container = await createPluginContainer(config, watcher)\n const moduleGraph = new ModuleGraph(container)\n const closeHttpServer = createServerCloseFn(httpServer)\n\n // eslint-disable-next-line prefer-const\n let exitProcess: () => void\n\n const server: ViteDevServer = {\n config,\n middlewares,\n get app() {\n config.logger.warn(\n `ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`\n )\n return middlewares\n },\n httpServer,\n watcher,\n pluginContainer: container,\n ws,\n moduleGraph,\n transformWithEsbuild,\n transformRequest(url, options) {\n return transformRequest(url, server, options)\n },\n transformIndexHtml: null!, // to be immediately set\n ssrLoadModule(url) {\n if (!server._ssrExternals) {\n server._ssrExternals = resolveSSRExternal(\n config,\n server._optimizeDepsMetadata\n ? Object.keys(server._optimizeDepsMetadata.optimized)\n : []\n )\n }\n return ssrLoadModule(url, server)\n },\n ssrFixStacktrace(e) {\n if (e.stack) {\n const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph)\n rebindErrorStacktrace(e, stacktrace)\n }\n },\n listen(port?: number, isRestart?: boolean) {\n return startServer(server, port, isRestart)\n },\n async close() {\n process.off('SIGTERM', exitProcess)\n\n if (!middlewareMode && process.env.CI !== 'true') {\n process.stdin.off('end', exitProcess)\n }\n\n await Promise.all([\n watcher.close(),\n ws.close(),\n container.close(),\n closeHttpServer()\n ])\n },\n printUrls() {\n if (httpServer) {\n printHttpServerUrls(httpServer, config)\n } else {\n throw new Error('cannot print server URLs in middleware mode.')\n }\n },\n _optimizeDepsMetadata: null,\n _ssrExternals: null,\n _globImporters: Object.create(null),\n _isRunningOptimizer: false,\n _registerMissingImport: null,\n _pendingReload: null,\n _pendingRequests: Object.create(null)\n }\n\n server.transformIndexHtml = createDevHtmlTransformFn(server)\n\n exitProcess = async () => {\n try {\n await server.close()\n } finally {\n process.exit(0)\n }\n }\n\n process.once('SIGTERM', exitProcess)\n\n if (!middlewareMode && process.env.CI !== 'true') {\n process.stdin.on('end', exitProcess)\n }\n\n watcher.on('change', async (file) => {\n file = normalizePath(file)\n // invalidate module graph cache on file change\n moduleGraph.onFileChange(file)\n if (serverConfig.hmr !== false) {\n try {\n await handleHMRUpdate(file, server)\n } catch (err) {\n ws.send({\n type: 'error',\n err: prepareError(err)\n })\n }\n }\n })\n\n watcher.on('add', (file) => {\n handleFileAddUnlink(normalizePath(file), server)\n })\n\n watcher.on('unlink', (file) => {\n handleFileAddUnlink(normalizePath(file), server, true)\n })\n\n if (!middlewareMode && httpServer) {\n httpServer.once('listening', () => {\n // update actual port since this may be different from initial value\n serverConfig.port = (httpServer.address() as AddressInfo).port\n })\n }\n\n // apply server configuration hooks from plugins\n const postHooks: ((() => void) | void)[] = []\n for (const plugin of plugins) {\n if (plugin.configureServer) {\n postHooks.push(await plugin.configureServer(server))\n }\n }\n\n // Internal middlewares ------------------------------------------------------\n\n // request timer\n if (process.env.DEBUG) {\n middlewares.use(timeMiddleware(root))\n }\n\n // cors (enabled by default)\n const { cors } = serverConfig\n if (cors !== false) {\n middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors))\n }\n\n // proxy\n const { proxy } = serverConfig\n if (proxy) {\n middlewares.use(proxyMiddleware(httpServer, config))\n }\n\n // base\n if (config.base !== '/') {\n middlewares.use(baseMiddleware(server))\n }\n\n // open in editor support\n middlewares.use('/__open-in-editor', launchEditorMiddleware())\n\n // hmr reconnect ping\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n middlewares.use('/__vite_ping', function viteHMRPingMiddleware(_, res) {\n res.end('pong')\n })\n\n // serve static files under /public\n // this applies before the transform middleware so that these files are served\n // as-is without transforms.\n if (config.publicDir) {\n middlewares.use(servePublicMiddleware(config.publicDir))\n }\n\n // main transform middleware\n middlewares.use(transformMiddleware(server))\n\n // serve static files\n middlewares.use(serveRawFsMiddleware(server))\n middlewares.use(serveStaticMiddleware(root, config))\n\n // spa fallback\n if (!middlewareMode || middlewareMode === 'html') {\n middlewares.use(spaFallbackMiddleware(root))\n }\n\n // run post config hooks\n // This is applied before the html middleware so that user middleware can\n // serve custom content instead of index.html.\n postHooks.forEach((fn) => fn && fn())\n\n if (!middlewareMode || middlewareMode === 'html') {\n // transform index.html\n middlewares.use(indexHtmlMiddleware(server))\n // handle 404s\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n middlewares.use(function vite404Middleware(_, res) {\n res.statusCode = 404\n res.end()\n })\n }\n\n // error handler\n middlewares.use(errorMiddleware(server, !!middlewareMode))\n\n const runOptimize = async () => {\n if (config.cacheDir) {\n server._isRunningOptimizer = true\n try {\n server._optimizeDepsMetadata = await optimizeDeps(config)\n } finally {\n server._isRunningOptimizer = false\n }\n server._registerMissingImport = createMissingImporterRegisterFn(server)\n }\n }\n\n if (!middlewareMode && httpServer) {\n let isOptimized = false\n // overwrite listen to run optimizer before server start\n const listen = httpServer.listen.bind(httpServer)\n httpServer.listen = (async (port: number, ...args: any[]) => {\n if (!isOptimized) {\n try {\n await container.buildStart({})\n await runOptimize()\n isOptimized = true\n } catch (e) {\n httpServer.emit('error', e)\n return\n }\n }\n return listen(port, ...args)\n }) as any\n } else {\n await container.buildStart({})\n await runOptimize()\n }\n\n return server\n}\n\nasync function startServer(\n server: ViteDevServer,\n inlinePort?: number,\n isRestart: boolean = false\n): Promise {\n const httpServer = server.httpServer\n if (!httpServer) {\n throw new Error('Cannot call server.listen in middleware mode.')\n }\n\n const options = server.config.server\n const port = inlinePort || options.port || 3000\n const hostname = resolveHostname(options.host)\n\n const protocol = options.https ? 'https' : 'http'\n const info = server.config.logger.info\n const base = server.config.base\n\n const serverPort = await httpServerStart(httpServer, {\n port,\n strictPort: options.strictPort,\n host: hostname.host,\n logger: server.config.logger\n })\n\n // @ts-ignore\n const profileSession = global.__vite_profile_session\n if (profileSession) {\n profileSession.post('Profiler.stop', (err: any, { profile }: any) => {\n // Write profile to disk, upload, etc.\n if (!err) {\n const outPath = path.resolve('./vite-profile.cpuprofile')\n fs.writeFileSync(outPath, JSON.stringify(profile))\n info(\n chalk.yellow(` CPU profile written to ${chalk.white.dim(outPath)}\\n`)\n )\n } else {\n throw err\n }\n })\n }\n\n if (options.open && !isRestart) {\n const path = typeof options.open === 'string' ? options.open : base\n openBrowser(\n path.startsWith('http')\n ? path\n : `${protocol}://${hostname.name}:${serverPort}${path}`,\n true,\n server.config.logger\n )\n }\n\n return server\n}\n\nfunction createServerCloseFn(server: http.Server | null) {\n if (!server) {\n return () => {}\n }\n\n let hasListened = false\n const openSockets = new Set()\n\n server.on('connection', (socket) => {\n openSockets.add(socket)\n socket.on('close', () => {\n openSockets.delete(socket)\n })\n })\n\n server.once('listening', () => {\n hasListened = true\n })\n\n return () =>\n new Promise((resolve, reject) => {\n openSockets.forEach((s) => s.destroy())\n if (hasListened) {\n server.close((err) => {\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n } else {\n resolve()\n }\n })\n}\n\nfunction resolvedAllowDir(root: string, dir: string): string {\n return ensureLeadingSlash(normalizePath(path.resolve(root, dir)))\n}\n\nexport function resolveServerOptions(\n root: string,\n raw?: ServerOptions\n): ResolvedServerOptions {\n const server = raw || {}\n let allowDirs = server.fs?.allow\n\n if (!allowDirs) {\n allowDirs = [searchForWorkspaceRoot(root)]\n }\n\n allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i))\n\n // only push client dir when vite itself is outside-of-root\n const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR)\n if (!allowDirs.some((i) => resolvedClientDir.startsWith(i))) {\n allowDirs.push(resolvedClientDir)\n }\n\n server.fs = {\n // TODO: make strict by default\n strict: server.fs?.strict,\n allow: allowDirs\n }\n return server as ResolvedServerOptions\n}\n","const noop = () => null;\nfunction matches(pattern, importee) {\n if (pattern instanceof RegExp) {\n return pattern.test(importee);\n }\n if (importee.length < pattern.length) {\n return false;\n }\n if (importee === pattern) {\n return true;\n }\n const importeeStartsWithKey = importee.indexOf(pattern) === 0;\n const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/';\n return importeeStartsWithKey && importeeHasSlashAfterKey;\n}\nfunction normalizeId(id) {\n return id;\n}\nfunction getEntries({ entries }) {\n if (!entries) {\n return [];\n }\n if (Array.isArray(entries)) {\n return entries;\n }\n return Object.entries(entries).map(([key, value]) => {\n return { find: key, replacement: value };\n });\n}\nfunction getCustomResolver({ customResolver }, options) {\n if (typeof customResolver === 'function') {\n return customResolver;\n }\n if (customResolver && typeof customResolver.resolveId === 'function') {\n return customResolver.resolveId;\n }\n if (typeof options.customResolver === 'function') {\n return options.customResolver;\n }\n if (options.customResolver && typeof options.customResolver.resolveId === 'function') {\n return options.customResolver.resolveId;\n }\n return null;\n}\nfunction alias(options = {}) {\n const entries = getEntries(options);\n if (entries.length === 0) {\n return {\n name: 'alias',\n resolveId: noop\n };\n }\n return {\n name: 'alias',\n buildStart(inputOptions) {\n return Promise.all([...entries, options].map(({ customResolver }) => customResolver &&\n typeof customResolver === 'object' &&\n typeof customResolver.buildStart === 'function' &&\n customResolver.buildStart.call(this, inputOptions))).then(() => {\n // enforce void return value\n });\n },\n resolveId(importee, importer) {\n const importeeId = normalizeId(importee);\n const importerId = normalizeId(importer);\n // First match is supposed to be the correct one\n const matchedEntry = entries.find((entry) => matches(entry.find, importeeId));\n if (!matchedEntry || !importerId) {\n return null;\n }\n const updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement));\n const customResolver = getCustomResolver(matchedEntry, options);\n if (customResolver) {\n return customResolver.call(this, updatedId, importerId, {});\n }\n return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => {\n let finalResult = resolved;\n if (!finalResult) {\n finalResult = { id: updatedId };\n }\n return finalResult;\n });\n }\n };\n}\n\nexport default alias;\n","/**\n * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file at\n * https://github.com/rollup/plugins/blob/master/LICENSE\n */\n\nimport { dataToEsm } from '@rollup/pluginutils'\nimport { Plugin } from 'rollup'\nimport { SPECIAL_QUERY_RE } from '../constants'\n\nexport interface JsonOptions {\n /**\n * Generate a named export for every property of the JSON object\n * @default true\n */\n namedExports?: boolean\n /**\n * Generate performant output as JSON.parse(\"stringified\").\n * Enabling this will disable namedExports.\n * @default false\n */\n stringify?: boolean\n}\n\n// Custom json filter for vite\nconst jsonExtRE = /\\.json($|\\?)(?!commonjs-(proxy|external))/\n\nexport function jsonPlugin(\n options: JsonOptions = {},\n isBuild: boolean\n): Plugin {\n return {\n name: 'vite:json',\n\n transform(json, id) {\n if (!jsonExtRE.test(id)) return null\n if (SPECIAL_QUERY_RE.test(id)) return null\n\n try {\n if (options.stringify) {\n if (isBuild) {\n return {\n // during build, parse then double-stringify to remove all\n // unnecessary whitespaces to reduce bundle size.\n code: `export default JSON.parse(${JSON.stringify(\n JSON.stringify(JSON.parse(json))\n )})`,\n map: { mappings: '' }\n }\n } else {\n return `export default JSON.parse(${JSON.stringify(json)})`\n }\n }\n\n const parsed = JSON.parse(json)\n return {\n code: dataToEsm(parsed, {\n preferConst: true,\n namedExports: options.namedExports\n }),\n map: { mappings: '' }\n }\n } catch (e) {\n const errorMessageList = /[\\d]+/.exec(e.message)\n const position = errorMessageList && parseInt(errorMessageList[0], 10)\n const msg = position\n ? `, invalid JSON syntax found at line ${position}`\n : `.`\n this.error(`Failed to parse JSON file` + msg, e.idx)\n }\n }\n }\n}\n","import fs from 'fs'\nimport path from 'path'\nimport { Plugin } from '../plugin'\nimport { ResolvedConfig } from '../config'\nimport chalk from 'chalk'\nimport MagicString from 'magic-string'\nimport { init, parse as parseImports, ImportSpecifier } from 'es-module-lexer'\nimport { isCSSRequest, isDirectCSSRequest } from './css'\nimport {\n isBuiltin,\n cleanUrl,\n createDebugger,\n generateCodeFrame,\n injectQuery,\n isDataUrl,\n isExternalUrl,\n isJSRequest,\n prettifyUrl,\n timeFrom,\n normalizePath,\n removeImportQuery,\n unwrapId\n} from '../utils'\nimport {\n debugHmr,\n handlePrunedModules,\n lexAcceptedHmrDeps\n} from '../server/hmr'\nimport {\n FS_PREFIX,\n CLIENT_DIR,\n CLIENT_PUBLIC_PATH,\n DEP_VERSION_RE,\n VALID_ID_PREFIX,\n NULL_BYTE_PLACEHOLDER\n} from '../constants'\nimport { ViteDevServer } from '..'\nimport { checkPublicFile } from './asset'\nimport { parse as parseJS } from 'acorn'\nimport type { Node } from 'estree'\nimport { transformImportGlob } from '../importGlob'\nimport { makeLegalIdentifier } from '@rollup/pluginutils'\nimport { shouldExternalizeForSSR } from '../ssr/ssrExternal'\nimport { performance } from 'perf_hooks'\nimport { transformRequest } from '../server/transformRequest'\n\nconst isDebug = !!process.env.DEBUG\nconst debug = createDebugger('vite:import-analysis')\n\nconst clientDir = normalizePath(CLIENT_DIR)\n\nconst skipRE = /\\.(map|json)$/\nconst canSkip = (id: string) => skipRE.test(id) || isDirectCSSRequest(id)\n\nfunction isExplicitImportRequired(url: string) {\n return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url)\n}\n\nfunction markExplicitImport(url: string) {\n if (isExplicitImportRequired(url)) {\n return injectQuery(url, 'import')\n }\n return url\n}\n\n/**\n * Server-only plugin that lexes, resolves, rewrites and analyzes url imports.\n *\n * - Imports are resolved to ensure they exist on disk\n *\n * - Lexes HMR accept calls and updates import relationships in the module graph\n *\n * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to\n * absolute file paths, e.g.\n *\n * ```js\n * import 'foo'\n * ```\n * is rewritten to\n * ```js\n * import '/@fs//project/node_modules/foo/dist/foo.js'\n * ```\n *\n * - CSS imports are appended with `.js` since both the js module and the actual\n * css (referenced via ) may go through the transform pipeline:\n *\n * ```js\n * import './style.css'\n * ```\n * is rewritten to\n * ```js\n * import './style.css.js'\n * ```\n */\nexport function importAnalysisPlugin(config: ResolvedConfig): Plugin {\n const { root, base } = config\n const clientPublicPath = path.posix.join(base, CLIENT_PUBLIC_PATH)\n\n let server: ViteDevServer\n\n return {\n name: 'vite:import-analysis',\n\n configureServer(_server) {\n server = _server\n },\n\n async transform(source, importer, ssr) {\n const prettyImporter = prettifyUrl(importer, root)\n\n if (canSkip(importer)) {\n isDebug && debug(chalk.dim(`[skipped] ${prettyImporter}`))\n return null\n }\n\n const start = performance.now()\n await init\n let imports: readonly ImportSpecifier[] = []\n // strip UTF-8 BOM\n if (source.charCodeAt(0) === 0xfeff) {\n source = source.slice(1)\n }\n try {\n imports = parseImports(source)[0]\n } catch (e: any) {\n const isVue = importer.endsWith('.vue')\n const maybeJSX = !isVue && isJSRequest(importer)\n\n const msg = isVue\n ? `Install @vitejs/plugin-vue to handle .vue files.`\n : maybeJSX\n ? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.`\n : `You may need to install appropriate plugins to handle the ${path.extname(\n importer\n )} file format.`\n\n this.error(\n `Failed to parse source for import analysis because the content ` +\n `contains invalid JS syntax. ` +\n msg,\n e.idx\n )\n }\n\n if (!imports.length) {\n isDebug &&\n debug(\n `${timeFrom(start)} ${chalk.dim(`[no imports] ${prettyImporter}`)}`\n )\n return source\n }\n\n let hasHMR = false\n let isSelfAccepting = false\n let hasEnv = false\n let needQueryInjectHelper = false\n let s: MagicString | undefined\n const str = () => s || (s = new MagicString(source))\n // vite-only server context\n const { moduleGraph } = server\n // since we are already in the transform phase of the importer, it must\n // have been loaded so its entry is guaranteed in the module graph.\n const importerModule = moduleGraph.getModuleById(importer)!\n const importedUrls = new Set()\n const staticImportedUrls = new Set()\n const acceptedUrls = new Set<{\n url: string\n start: number\n end: number\n }>()\n const toAbsoluteUrl = (url: string) =>\n path.posix.resolve(path.posix.dirname(importerModule.url), url)\n\n const normalizeUrl = async (\n url: string,\n pos: number\n ): Promise<[string, string]> => {\n if (base !== '/' && url.startsWith(base)) {\n url = url.replace(base, '/')\n }\n\n const resolved = await this.resolve(url, importer)\n\n if (!resolved) {\n this.error(\n `Failed to resolve import \"${url}\" from \"${path.relative(\n process.cwd(),\n importer\n )}\". Does the file exist?`,\n pos\n )\n }\n\n const isRelative = url.startsWith('.')\n const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer)\n\n // normalize all imports into resolved URLs\n // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js`\n if (resolved.id.startsWith(root + '/')) {\n // in root: infer short absolute path from root\n url = resolved.id.slice(root.length)\n } else if (fs.existsSync(cleanUrl(resolved.id))) {\n // exists but out of root: rewrite to absolute /@fs/ paths\n url = path.posix.join(FS_PREFIX + resolved.id)\n } else {\n url = resolved.id\n }\n\n if (isExternalUrl(url)) {\n return [url, url]\n }\n\n // if the resolved id is not a valid browser import specifier,\n // prefix it to make it valid. We will strip this before feeding it\n // back into the transform pipeline\n if (!url.startsWith('.') && !url.startsWith('/')) {\n url =\n VALID_ID_PREFIX + resolved.id.replace('\\0', NULL_BYTE_PLACEHOLDER)\n }\n\n // make the URL browser-valid if not SSR\n if (!ssr) {\n // mark non-js/css imports with `?import`\n url = markExplicitImport(url)\n\n // for relative js/css imports, or self-module virtual imports\n // (e.g. vue blocks), inherit importer's version query\n // do not do this for unknown type imports, otherwise the appended\n // query can break 3rd party plugin's extension checks.\n if ((isRelative || isSelfImport) && !/[\\?&]import=?\\b/.test(url)) {\n const versionMatch = importer.match(DEP_VERSION_RE)\n if (versionMatch) {\n url = injectQuery(url, versionMatch[1])\n }\n }\n\n // check if the dep has been hmr updated. If yes, we need to attach\n // its last updated timestamp to force the browser to fetch the most\n // up-to-date version of this module.\n try {\n const depModule = await moduleGraph.ensureEntryFromUrl(url)\n if (depModule.lastHMRTimestamp > 0) {\n url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`)\n }\n } catch (e: any) {\n // it's possible that the dep fails to resolve (non-existent import)\n // attach location to the missing import\n e.pos = pos\n throw e\n }\n\n // prepend base (dev base is guaranteed to have ending slash)\n url = base + url.replace(/^\\//, '')\n }\n\n return [url, resolved.id]\n }\n\n for (let index = 0; index < imports.length; index++) {\n const {\n s: start,\n e: end,\n ss: expStart,\n se: expEnd,\n d: dynamicIndex,\n // #2083 User may use escape path,\n // so use imports[index].n to get the unescaped string\n // @ts-ignore\n n: specifier\n } = imports[index]\n\n const rawUrl = source.slice(start, end)\n\n // check import.meta usage\n if (rawUrl === 'import.meta') {\n const prop = source.slice(end, end + 4)\n if (prop === '.hot') {\n hasHMR = true\n if (source.slice(end + 4, end + 11) === '.accept') {\n // further analyze accepted modules\n if (\n lexAcceptedHmrDeps(\n source,\n source.indexOf('(', end + 11) + 1,\n acceptedUrls\n )\n ) {\n isSelfAccepting = true\n }\n }\n } else if (prop === '.env') {\n hasEnv = true\n } else if (prop === '.glo' && source[end + 4] === 'b') {\n // transform import.meta.glob()\n // e.g. `import.meta.glob('glob:./dir/*.js')`\n const {\n imports,\n importsString,\n exp,\n endIndex,\n base,\n pattern,\n isEager\n } = await transformImportGlob(\n source,\n start,\n importer,\n index,\n root,\n normalizeUrl\n )\n str().prepend(importsString)\n str().overwrite(expStart, endIndex, exp)\n imports.forEach((url) => {\n url = url.replace(base, '/')\n importedUrls.add(url)\n if (isEager) staticImportedUrls.add(url)\n })\n if (!(importerModule.file! in server._globImporters)) {\n server._globImporters[importerModule.file!] = {\n module: importerModule,\n importGlobs: []\n }\n }\n server._globImporters[importerModule.file!].importGlobs.push({\n base,\n pattern\n })\n }\n continue\n }\n\n const isDynamicImport = dynamicIndex >= 0\n\n // static import or valid string in dynamic import\n // If resolvable, let's resolve it\n if (specifier) {\n // skip external / data uri\n if (isExternalUrl(specifier) || isDataUrl(specifier)) {\n continue\n }\n // skip ssr external\n if (ssr) {\n if (\n server._ssrExternals &&\n shouldExternalizeForSSR(specifier, server._ssrExternals)\n ) {\n continue\n }\n if (isBuiltin(specifier)) {\n continue\n }\n }\n // skip client\n if (specifier === clientPublicPath) {\n continue\n }\n\n // warn imports to non-asset /public files\n if (\n specifier.startsWith('/') &&\n !config.assetsInclude(cleanUrl(specifier)) &&\n !specifier.endsWith('.json') &&\n checkPublicFile(specifier, config)\n ) {\n throw new Error(\n `Cannot import non-asset file ${specifier} which is inside /public.` +\n `JS/CSS files inside /public are copied as-is on build and ` +\n `can only be referenced via