@faasjs/load 0.0.2-beta.99 → 0.0.3-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,61 @@
1
1
  # @faasjs/load
2
2
 
3
- 资源加载类库
4
-
5
- [![License: MIT](https://img.shields.io/npm/l/@faasjs/load.svg)](https://github.com/faasjs/faasjs/blob/master/packages/faasjs/load/LICENSE)
3
+ [![License: MIT](https://img.shields.io/npm/l/@faasjs/load.svg)](https://github.com/faasjs/faasjs/blob/main/packages/faasjs/load/LICENSE)
6
4
  [![NPM Stable Version](https://img.shields.io/npm/v/@faasjs/load/stable.svg)](https://www.npmjs.com/package/@faasjs/load)
7
5
  [![NPM Beta Version](https://img.shields.io/npm/v/@faasjs/load/beta.svg)](https://www.npmjs.com/package/@faasjs/load)
6
+
7
+ FaasJS's load module.
8
+
9
+ ## Install
10
+
11
+ npm install @faasjs/load
12
+ ## Modules
13
+
14
+ ### Functions
15
+
16
+ - [loadConfig](#loadconfig)
17
+ - [loadTs](#loadts)
18
+
19
+ ## Functions
20
+
21
+ ### loadConfig
22
+
23
+ ▸ **loadConfig**(`root`, `filename`): `Config`
24
+
25
+ 加载配置
26
+
27
+ #### Parameters
28
+
29
+ | Name | Type | Description |
30
+ | :------ | :------ | :------ |
31
+ | `root` | `string` | {string} 根目录 |
32
+ | `filename` | `string` | {filename} 目标文件,用于读取目录层级 |
33
+
34
+ #### Returns
35
+
36
+ `Config`
37
+
38
+ ___
39
+
40
+ ### loadTs
41
+
42
+ ▸ **loadTs**(`filename`, `options?`): `Promise`<{ `dependencies`: { `[key: string]`: `string`; } ; `module?`: `Func` ; `modules?`: { `[key: string]`: `string`; } }\>
43
+
44
+ 加载 ts 文件
45
+
46
+ #### Parameters
47
+
48
+ | Name | Type | Description |
49
+ | :------ | :------ | :------ |
50
+ | `filename` | `string` | {string} 完整源文件路径 |
51
+ | `options` | `Object` | {object} 配置项 |
52
+ | `options.input?` | `Object` | {object} 读取配置 |
53
+ | `options.modules?` | `Object` | {object} 生成 modules 的配置 |
54
+ | `options.modules.additions?` | `string`[] | - |
55
+ | `options.modules.excludes?` | `string`[] | - |
56
+ | `options.output?` | `Object` | {object} 写入配置 |
57
+ | `options.tmp?` | `boolean` | {boolean} 是否为临时文件,true 则生成的文件会被删除,默认为 false |
58
+
59
+ #### Returns
60
+
61
+ `Promise`<{ `dependencies`: { `[key: string]`: `string`; } ; `module?`: `Func` ; `modules?`: { `[key: string]`: `string`; } }\>
@@ -0,0 +1,63 @@
1
+ import { Config as Config$1, Func } from '@faasjs/func';
2
+
3
+ /**
4
+ * 配置类
5
+ */
6
+ declare class Config {
7
+ [key: string]: any;
8
+ readonly root: string;
9
+ readonly filename: string;
10
+ readonly origin: {
11
+ [key: string]: Config$1;
12
+ defaults: Config$1;
13
+ };
14
+ readonly defaults: Config$1;
15
+ /**
16
+ * 创建配置类,并自动读取配置内容
17
+ *
18
+ * @param root {string} 根目录
19
+ * @param filename {filename} 目标文件,用于读取目录层级
20
+ */
21
+ constructor(root: string, filename: string);
22
+ }
23
+ /**
24
+ * 加载配置
25
+ * @param root {string} 根目录
26
+ * @param filename {filename} 目标文件,用于读取目录层级
27
+ */
28
+ declare function loadConfig(root: string, filename: string): Config;
29
+
30
+ /**
31
+ * 加载 ts 文件
32
+ *
33
+ * @param filename {string} 完整源文件路径
34
+ * @param options {object} 配置项
35
+ * @param options.input {object} 读取配置
36
+ * @param options.output {object} 写入配置
37
+ * @param options.tmp {boolean} 是否为临时文件,true 则生成的文件会被删除,默认为 false
38
+ * @param options.modules {object} 生成 modules 的配置
39
+ * @param options.modules.excludes {string[]} modules 中需排除的模块
40
+ */
41
+ declare function loadTs(filename: string, options?: {
42
+ input?: {
43
+ [key: string]: any;
44
+ };
45
+ output?: {
46
+ [key: string]: any;
47
+ };
48
+ tmp?: boolean;
49
+ modules?: {
50
+ excludes?: string[];
51
+ additions?: string[];
52
+ };
53
+ }): Promise<{
54
+ module?: Func;
55
+ dependencies: {
56
+ [key: string]: string;
57
+ };
58
+ modules?: {
59
+ [key: string]: string;
60
+ };
61
+ }>;
62
+
63
+ export { loadConfig, loadTs };
package/dist/index.js ADDED
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ loadConfig: () => loadConfig,
24
+ loadTs: () => loadTs
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+
28
+ // src/load_config.ts
29
+ var import_deep_merge = require("@faasjs/deep_merge");
30
+ var import_fs = require("fs");
31
+ var import_path = require("path");
32
+ var import_js_yaml = require("js-yaml");
33
+ var Config = class {
34
+ constructor(root, filename) {
35
+ this.root = root;
36
+ if (!this.root.endsWith(import_path.sep))
37
+ this.root += import_path.sep;
38
+ this.filename = filename;
39
+ const configs = [];
40
+ const paths = [this.root, "."].concat((0, import_path.dirname)(filename.replace(root, "")).split(import_path.sep));
41
+ paths.reduce(function(base, path) {
42
+ const root2 = (0, import_path.join)(base, path);
43
+ if (root2 === base)
44
+ return base;
45
+ const faas = (0, import_path.join)(root2, "faas.yaml");
46
+ if ((0, import_fs.existsSync)(faas))
47
+ configs.push((0, import_js_yaml.load)((0, import_fs.readFileSync)(faas).toString()));
48
+ return root2;
49
+ });
50
+ this.origin = (0, import_deep_merge.deepMerge)(...configs);
51
+ this.defaults = (0, import_deep_merge.deepMerge)(this.origin.defaults || {});
52
+ for (const key in this.origin) {
53
+ if (key !== "defaults")
54
+ this[key] = (0, import_deep_merge.deepMerge)(this.origin.defaults, this.origin[key]);
55
+ const data = this[key];
56
+ if (data.plugins)
57
+ for (const pluginKey in data.plugins) {
58
+ const plugin = data.plugins[pluginKey];
59
+ plugin.name = pluginKey;
60
+ if (plugin.provider)
61
+ if (typeof plugin.provider === "string") {
62
+ if (!data.providers[plugin.provider])
63
+ throw Error(`[faas.yaml] missing provider: ${plugin.provider} <${key}/plugins/${pluginKey}>`);
64
+ plugin.provider = data.providers[plugin.provider];
65
+ } else
66
+ plugin.provider = (0, import_deep_merge.deepMerge)(data.providers[plugin.provider], plugin.provider);
67
+ }
68
+ }
69
+ }
70
+ };
71
+ function loadConfig(root, filename) {
72
+ return new Config(root, filename);
73
+ }
74
+
75
+ // src/load_ts.ts
76
+ var import_deep_merge2 = require("@faasjs/deep_merge");
77
+ var import_fs2 = require("fs");
78
+ var import_rollup = require("rollup/dist/rollup.js");
79
+ var import_path2 = require("path");
80
+ var import_ts_transform = require("@faasjs/ts-transform");
81
+ var FaasPackages = [
82
+ "@faasjs/cloud_function",
83
+ "@faasjs/deep_merge",
84
+ "@faasjs/deployer",
85
+ "@faasjs/func",
86
+ "@faasjs/http",
87
+ "@faasjs/knex",
88
+ "@faasjs/load",
89
+ "@faasjs/logger",
90
+ "@faasjs/mongo",
91
+ "@faasjs/redis",
92
+ "@faasjs/request",
93
+ "@faasjs/tencentcloud",
94
+ "@faasjs/ts-transform"
95
+ ];
96
+ function resolveModuleBasePath(moduleName) {
97
+ const moduleMainFilePath = require.resolve(moduleName);
98
+ const moduleNameParts = moduleName.split("/");
99
+ let searchForPathSection;
100
+ if (moduleName.startsWith("@") && moduleNameParts.length > 1) {
101
+ const [org, mod] = moduleNameParts;
102
+ searchForPathSection = `node_modules${import_path2.sep}${org}${import_path2.sep}${mod}`;
103
+ } else {
104
+ const [mod] = moduleNameParts;
105
+ searchForPathSection = `node_modules${import_path2.sep}${mod}`;
106
+ }
107
+ const lastIndex = moduleMainFilePath.lastIndexOf(searchForPathSection);
108
+ if (lastIndex === -1) {
109
+ console.log(searchForPathSection, moduleMainFilePath);
110
+ throw new Error(`Couldn't resolve the base path of "${moduleName}". Searched inside the resolved main file path "${moduleMainFilePath}" using "${searchForPathSection}"`);
111
+ }
112
+ return moduleMainFilePath.slice(0, lastIndex + searchForPathSection.length);
113
+ }
114
+ function findModule(list, key, options = { excludes: [] }) {
115
+ if (list[key])
116
+ return;
117
+ if (key.startsWith("@types/") || options.excludes.includes(key))
118
+ return;
119
+ try {
120
+ list[key] = (0, import_path2.dirname)(require.resolve((0, import_path2.join)(key, "package.json")));
121
+ } catch (error) {
122
+ console.warn(error);
123
+ try {
124
+ list[key] = resolveModuleBasePath(key);
125
+ } catch (error2) {
126
+ console.warn(error2);
127
+ }
128
+ }
129
+ if (!list[key])
130
+ return;
131
+ const pkg = JSON.parse((0, import_fs2.readFileSync)((0, import_path2.join)(list[key], "package.json")).toString());
132
+ const deps = Object.keys(pkg.dependencies || {}).concat(Object.keys(pkg.peerDependencies || {}));
133
+ if (pkg.peerDependenciesMeta) {
134
+ Object.keys(pkg.peerDependenciesMeta).forEach((key2) => {
135
+ if (pkg.peerDependenciesMeta[key2].optional) {
136
+ const index = deps.indexOf(key2);
137
+ if (index >= 0)
138
+ deps.splice(index, 1);
139
+ }
140
+ });
141
+ }
142
+ deps.map((d) => findModule(list, d, options));
143
+ }
144
+ function swc(externalModules) {
145
+ return {
146
+ name: "swc",
147
+ async transform(code, filename) {
148
+ return (0, import_ts_transform.bundle)({
149
+ filename,
150
+ externalModules
151
+ });
152
+ }
153
+ };
154
+ }
155
+ async function loadTs(filename, options = /* @__PURE__ */ Object.create(null)) {
156
+ var _a;
157
+ const PackageJSON = require(`${process.cwd()}/package.json`);
158
+ const external = PackageJSON.dependencies ? Object.keys(PackageJSON.dependencies) : [];
159
+ if (options.modules && options.modules.excludes == null)
160
+ options.modules.excludes = [];
161
+ const input = (0, import_deep_merge2.deepMerge)({
162
+ input: filename,
163
+ external,
164
+ plugins: [swc(external.concat(FaasPackages))],
165
+ onwarn: () => null
166
+ }, options.input || {});
167
+ const bundle2 = await (0, import_rollup.rollup)(input);
168
+ const dependencies = /* @__PURE__ */ Object.create(null);
169
+ for (const m of ((_a = bundle2.cache) == null ? void 0 : _a.modules) || [])
170
+ for (const d of m.dependencies)
171
+ if (!d.startsWith("/") && !dependencies[d] && !import_ts_transform.NodeBuiltinModules.includes(d))
172
+ dependencies[d] = "*";
173
+ const output = (0, import_deep_merge2.deepMerge)({
174
+ file: filename + ".tmp.js",
175
+ format: "cjs",
176
+ exports: "auto"
177
+ }, options.output || {});
178
+ await bundle2.write(output);
179
+ const result = /* @__PURE__ */ Object.create(null);
180
+ result.dependencies = dependencies;
181
+ result.module = require(output.file);
182
+ if (options.tmp)
183
+ (0, import_fs2.unlinkSync)(output.file);
184
+ if (options.modules) {
185
+ const modules = /* @__PURE__ */ Object.create(null);
186
+ Object.keys(dependencies).map((d) => findModule(modules, d, options.modules));
187
+ if (options.modules.additions)
188
+ options.modules.additions.map((d) => findModule(modules, d, options.modules));
189
+ result.modules = modules;
190
+ }
191
+ return result;
192
+ }
193
+ // Annotate the CommonJS export names for ESM import in node:
194
+ 0 && (module.exports = {
195
+ loadConfig,
196
+ loadTs
197
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,185 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw new Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/load_config.ts
10
+ import { deepMerge } from "@faasjs/deep_merge";
11
+ import { existsSync, readFileSync } from "fs";
12
+ import {
13
+ sep,
14
+ dirname,
15
+ join
16
+ } from "path";
17
+ import { load } from "js-yaml";
18
+ var Config = class {
19
+ constructor(root, filename) {
20
+ this.root = root;
21
+ if (!this.root.endsWith(sep))
22
+ this.root += sep;
23
+ this.filename = filename;
24
+ const configs = [];
25
+ const paths = [this.root, "."].concat(dirname(filename.replace(root, "")).split(sep));
26
+ paths.reduce(function(base, path) {
27
+ const root2 = join(base, path);
28
+ if (root2 === base)
29
+ return base;
30
+ const faas = join(root2, "faas.yaml");
31
+ if (existsSync(faas))
32
+ configs.push(load(readFileSync(faas).toString()));
33
+ return root2;
34
+ });
35
+ this.origin = deepMerge(...configs);
36
+ this.defaults = deepMerge(this.origin.defaults || {});
37
+ for (const key in this.origin) {
38
+ if (key !== "defaults")
39
+ this[key] = deepMerge(this.origin.defaults, this.origin[key]);
40
+ const data = this[key];
41
+ if (data.plugins)
42
+ for (const pluginKey in data.plugins) {
43
+ const plugin = data.plugins[pluginKey];
44
+ plugin.name = pluginKey;
45
+ if (plugin.provider)
46
+ if (typeof plugin.provider === "string") {
47
+ if (!data.providers[plugin.provider])
48
+ throw Error(`[faas.yaml] missing provider: ${plugin.provider} <${key}/plugins/${pluginKey}>`);
49
+ plugin.provider = data.providers[plugin.provider];
50
+ } else
51
+ plugin.provider = deepMerge(data.providers[plugin.provider], plugin.provider);
52
+ }
53
+ }
54
+ }
55
+ };
56
+ function loadConfig(root, filename) {
57
+ return new Config(root, filename);
58
+ }
59
+
60
+ // src/load_ts.ts
61
+ import { deepMerge as deepMerge2 } from "@faasjs/deep_merge";
62
+ import { readFileSync as readFileSync2, unlinkSync } from "fs";
63
+ import { rollup } from "rollup/dist/rollup.js";
64
+ import {
65
+ join as join2,
66
+ sep as sep2,
67
+ dirname as dirname2
68
+ } from "path";
69
+ import { bundle, NodeBuiltinModules } from "@faasjs/ts-transform";
70
+ var FaasPackages = [
71
+ "@faasjs/cloud_function",
72
+ "@faasjs/deep_merge",
73
+ "@faasjs/deployer",
74
+ "@faasjs/func",
75
+ "@faasjs/http",
76
+ "@faasjs/knex",
77
+ "@faasjs/load",
78
+ "@faasjs/logger",
79
+ "@faasjs/mongo",
80
+ "@faasjs/redis",
81
+ "@faasjs/request",
82
+ "@faasjs/tencentcloud",
83
+ "@faasjs/ts-transform"
84
+ ];
85
+ function resolveModuleBasePath(moduleName) {
86
+ const moduleMainFilePath = __require.resolve(moduleName);
87
+ const moduleNameParts = moduleName.split("/");
88
+ let searchForPathSection;
89
+ if (moduleName.startsWith("@") && moduleNameParts.length > 1) {
90
+ const [org, mod] = moduleNameParts;
91
+ searchForPathSection = `node_modules${sep2}${org}${sep2}${mod}`;
92
+ } else {
93
+ const [mod] = moduleNameParts;
94
+ searchForPathSection = `node_modules${sep2}${mod}`;
95
+ }
96
+ const lastIndex = moduleMainFilePath.lastIndexOf(searchForPathSection);
97
+ if (lastIndex === -1) {
98
+ console.log(searchForPathSection, moduleMainFilePath);
99
+ throw new Error(`Couldn't resolve the base path of "${moduleName}". Searched inside the resolved main file path "${moduleMainFilePath}" using "${searchForPathSection}"`);
100
+ }
101
+ return moduleMainFilePath.slice(0, lastIndex + searchForPathSection.length);
102
+ }
103
+ function findModule(list, key, options = { excludes: [] }) {
104
+ if (list[key])
105
+ return;
106
+ if (key.startsWith("@types/") || options.excludes.includes(key))
107
+ return;
108
+ try {
109
+ list[key] = dirname2(__require.resolve(join2(key, "package.json")));
110
+ } catch (error) {
111
+ console.warn(error);
112
+ try {
113
+ list[key] = resolveModuleBasePath(key);
114
+ } catch (error2) {
115
+ console.warn(error2);
116
+ }
117
+ }
118
+ if (!list[key])
119
+ return;
120
+ const pkg = JSON.parse(readFileSync2(join2(list[key], "package.json")).toString());
121
+ const deps = Object.keys(pkg.dependencies || {}).concat(Object.keys(pkg.peerDependencies || {}));
122
+ if (pkg.peerDependenciesMeta) {
123
+ Object.keys(pkg.peerDependenciesMeta).forEach((key2) => {
124
+ if (pkg.peerDependenciesMeta[key2].optional) {
125
+ const index = deps.indexOf(key2);
126
+ if (index >= 0)
127
+ deps.splice(index, 1);
128
+ }
129
+ });
130
+ }
131
+ deps.map((d) => findModule(list, d, options));
132
+ }
133
+ function swc(externalModules) {
134
+ return {
135
+ name: "swc",
136
+ async transform(code, filename) {
137
+ return bundle({
138
+ filename,
139
+ externalModules
140
+ });
141
+ }
142
+ };
143
+ }
144
+ async function loadTs(filename, options = /* @__PURE__ */ Object.create(null)) {
145
+ var _a;
146
+ const PackageJSON = __require(`${process.cwd()}/package.json`);
147
+ const external = PackageJSON.dependencies ? Object.keys(PackageJSON.dependencies) : [];
148
+ if (options.modules && options.modules.excludes == null)
149
+ options.modules.excludes = [];
150
+ const input = deepMerge2({
151
+ input: filename,
152
+ external,
153
+ plugins: [swc(external.concat(FaasPackages))],
154
+ onwarn: () => null
155
+ }, options.input || {});
156
+ const bundle2 = await rollup(input);
157
+ const dependencies = /* @__PURE__ */ Object.create(null);
158
+ for (const m of ((_a = bundle2.cache) == null ? void 0 : _a.modules) || [])
159
+ for (const d of m.dependencies)
160
+ if (!d.startsWith("/") && !dependencies[d] && !NodeBuiltinModules.includes(d))
161
+ dependencies[d] = "*";
162
+ const output = deepMerge2({
163
+ file: filename + ".tmp.js",
164
+ format: "cjs",
165
+ exports: "auto"
166
+ }, options.output || {});
167
+ await bundle2.write(output);
168
+ const result = /* @__PURE__ */ Object.create(null);
169
+ result.dependencies = dependencies;
170
+ result.module = __require(output.file);
171
+ if (options.tmp)
172
+ unlinkSync(output.file);
173
+ if (options.modules) {
174
+ const modules = /* @__PURE__ */ Object.create(null);
175
+ Object.keys(dependencies).map((d) => findModule(modules, d, options.modules));
176
+ if (options.modules.additions)
177
+ options.modules.additions.map((d) => findModule(modules, d, options.modules));
178
+ result.modules = modules;
179
+ }
180
+ return result;
181
+ }
182
+ export {
183
+ loadConfig,
184
+ loadTs
185
+ };
package/package.json CHANGED
@@ -1,31 +1,38 @@
1
1
  {
2
2
  "name": "@faasjs/load",
3
- "version": "0.0.2-beta.99",
3
+ "version": "0.0.3-beta.2",
4
4
  "license": "MIT",
5
- "main": "lib/index.js",
6
- "types": "lib/index.d.ts",
7
- "module": "lib/index.es.js",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "homepage": "https://faasjs.com/doc/load",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/faasjs/faasjs.git",
11
+ "directory": "packages/load"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/faasjs/faasjs/issues"
15
+ },
16
+ "funding": "https://github.com/sponsors/faasjs",
8
17
  "scripts": {
9
- "lint": "eslint --ext .ts src",
10
- "prepack": "rm -rf ./lib && rollup -c && mv lib/*/src/* lib/",
11
- "ci": "yarn lint && jest --silent"
18
+ "build": "tsup-node src/index.ts --format esm,cjs",
19
+ "build:types": "tsup-node src/index.ts --dts-only"
12
20
  },
13
21
  "files": [
14
- "lib"
22
+ "dist"
15
23
  ],
16
24
  "dependencies": {
17
- "@faasjs/deep_merge": "^0.0.2-beta.54",
25
+ "@faasjs/deep_merge": "^0.0.3-beta.2",
26
+ "@faasjs/func": "^0.0.3-beta.2",
27
+ "@faasjs/ts-transform": "^0.0.3-beta.2",
18
28
  "js-yaml": "*",
19
- "rollup": "*",
20
- "rollup-plugin-typescript2": "*",
21
- "typescript": "*"
29
+ "rollup": "*"
22
30
  },
23
31
  "devDependencies": {
24
- "@faasjs/func": "^0.0.2-beta.99",
25
- "@types/debug": "*",
26
- "@types/jest": "*",
27
- "@types/js-yaml": "*",
28
- "@types/node": "*"
32
+ "@types/js-yaml": "*"
29
33
  },
30
- "gitHead": "8c2bc1591c90b91123b6295845f43e09fac3e53b"
34
+ "engines": {
35
+ "npm": ">=8.0.0",
36
+ "node": ">=16.0.0"
37
+ }
31
38
  }
package/lib/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- import loadConfig from './load_config';
2
- import loadTs from './load_ts';
3
- export { loadConfig, loadTs };
package/lib/index.es.js DELETED
@@ -1,170 +0,0 @@
1
- import deepMerge from '@faasjs/deep_merge';
2
- import { existsSync, readFileSync, unlinkSync } from 'fs';
3
- import { sep, dirname, join } from 'path';
4
- import { safeLoad } from 'js-yaml';
5
- import { rollup } from 'rollup';
6
- import typescript from 'rollup-plugin-typescript2';
7
-
8
- /**
9
- * 配置类
10
- */
11
- class Config {
12
- /**
13
- * 创建配置类,并自动读取配置内容
14
- *
15
- * @param root {string} 根目录
16
- * @param filename {filename} 目标文件,用于读取目录层级
17
- */
18
- constructor(root, filename) {
19
- this.root = root;
20
- if (!this.root.endsWith(sep))
21
- this.root += sep;
22
- this.filename = filename;
23
- const configs = [];
24
- const paths = [this.root, '.'].concat(dirname(filename.replace(root, '')).split(sep));
25
- paths.reduce(function (base, path) {
26
- const root = join(base, path);
27
- const faas = join(root, 'faas.yaml');
28
- if (existsSync(faas))
29
- configs.push(safeLoad(readFileSync(faas).toString()));
30
- return root;
31
- });
32
- this.origin = deepMerge(...configs);
33
- if (!this.origin.defaults)
34
- throw Error('[faas.yaml] need defaults env.');
35
- this.defaults = deepMerge(this.origin.defaults);
36
- for (const key in this.origin) {
37
- if (key !== 'defaults')
38
- this[key] = deepMerge(this.origin.defaults, this.origin[key]);
39
- const data = this[key];
40
- if (!data.providers)
41
- throw Error(`[faas.yaml] missing key: ${key}/providers`);
42
- if (!data.plugins)
43
- throw Error(`[faas.yaml] missing key: ${key}/plugins`);
44
- for (const pluginKey in data.plugins) {
45
- const plugin = data.plugins[pluginKey];
46
- plugin.name = pluginKey;
47
- if (plugin.provider)
48
- if (typeof plugin.provider === 'string') {
49
- if (!data.providers[plugin.provider])
50
- throw Error(`[faas.yaml] missing provider: ${plugin.provider} <${key}/plugins/${pluginKey}>`);
51
- plugin.provider = data.providers[plugin.provider];
52
- }
53
- else
54
- plugin.provider = deepMerge(data.providers[plugin.provider], plugin.provider);
55
- }
56
- }
57
- }
58
- }
59
- /**
60
- * 加载配置
61
- * @param root {string} 根目录
62
- * @param filename {filename} 目标文件,用于读取目录层级
63
- */
64
- function loadConfig(root, filename) {
65
- return new Config(root, filename);
66
- }
67
-
68
- const FAAS_PACKAGES = [
69
- '@faasjs/browser',
70
- '@faasjs/cli',
71
- '@faasjs/cloud_function',
72
- 'create-faas-app',
73
- '@faasjs/deep_merge',
74
- '@faasjs/deployer',
75
- '@faasjs/eslint-config-recommended',
76
- '@faasjs/eslint-config-vue',
77
- 'faasjs',
78
- '@faasjs/func',
79
- '@faasjs/graphql-server',
80
- '@faasjs/http',
81
- '@faasjs/load',
82
- '@faasjs/logger',
83
- '@faasjs/nuxt',
84
- '@faasjs/redis',
85
- '@faasjs/request',
86
- '@faasjs/server',
87
- '@faasjs/sql',
88
- '@faasjs/tencentcloud',
89
- '@faasjs/test',
90
- '@faasjs/vue-plugin'
91
- ];
92
- const NODE_PACKAGES = [
93
- 'async_hooks',
94
- 'child_process',
95
- 'cluster',
96
- 'crypto',
97
- 'dns',
98
- 'events',
99
- 'fs',
100
- 'http',
101
- 'http2',
102
- 'https',
103
- 'inspector',
104
- 'net',
105
- 'os',
106
- 'path',
107
- 'perf_hooks',
108
- 'process',
109
- 'querystring',
110
- 'readline',
111
- 'repl',
112
- 'stream',
113
- 'string_decoder',
114
- 'tls',
115
- 'trace_events',
116
- 'tty',
117
- 'dgram',
118
- 'udp4',
119
- 'url',
120
- 'util',
121
- 'v8',
122
- 'vm',
123
- 'wasi',
124
- 'worker_threads',
125
- 'zlib'
126
- ];
127
- const EXTERNAL = FAAS_PACKAGES.concat(NODE_PACKAGES);
128
- /**
129
- * 加载 ts 文件
130
- *
131
- * @param filename {string} 完整源文件路径
132
- * @param options {object} 配置项
133
- * @param options.input {object} 读取配置
134
- * @param options.output {object} 写入配置
135
- * @param options.tmp {boolean} 是否为临时文件,true 则生成的文件会被删除,默认为 false
136
- */
137
- async function loadTs(filename, options = Object.create(null)) {
138
- // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
139
- const PackageJSON = require(`${process.cwd()}/package.json`);
140
- const external = PackageJSON['dependencies'] ? EXTERNAL.concat(Object.keys(PackageJSON.dependencies)) : EXTERNAL;
141
- const input = deepMerge({
142
- input: filename,
143
- external,
144
- plugins: [
145
- typescript({ tsconfigOverride: { compilerOptions: { declaration: false } } })
146
- ],
147
- onwarn: () => null
148
- }, options.input || {});
149
- const bundle = await rollup(input);
150
- const dependencies = Object.create(null);
151
- for (const m of bundle.cache.modules || [])
152
- for (const d of m.dependencies)
153
- if (!d.startsWith('/') && !dependencies[d] && !NODE_PACKAGES.includes(d))
154
- dependencies[d] = '*';
155
- const output = deepMerge({
156
- file: filename + '.tmp.js',
157
- format: 'cjs'
158
- }, options.output || {});
159
- await bundle.write(output);
160
- // eslint-disable-next-line @typescript-eslint/no-var-requires
161
- const module = require(output.file);
162
- if (options.tmp)
163
- unlinkSync(output.file);
164
- return {
165
- module,
166
- dependencies
167
- };
168
- }
169
-
170
- export { loadConfig, loadTs };
package/lib/index.js DELETED
@@ -1,177 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- var deepMerge = _interopDefault(require('@faasjs/deep_merge'));
8
- var fs = require('fs');
9
- var path = require('path');
10
- var jsYaml = require('js-yaml');
11
- var rollup = require('rollup');
12
- var typescript = _interopDefault(require('rollup-plugin-typescript2'));
13
-
14
- /**
15
- * 配置类
16
- */
17
- class Config {
18
- /**
19
- * 创建配置类,并自动读取配置内容
20
- *
21
- * @param root {string} 根目录
22
- * @param filename {filename} 目标文件,用于读取目录层级
23
- */
24
- constructor(root, filename) {
25
- this.root = root;
26
- if (!this.root.endsWith(path.sep))
27
- this.root += path.sep;
28
- this.filename = filename;
29
- const configs = [];
30
- const paths = [this.root, '.'].concat(path.dirname(filename.replace(root, '')).split(path.sep));
31
- paths.reduce(function (base, path$1) {
32
- const root = path.join(base, path$1);
33
- const faas = path.join(root, 'faas.yaml');
34
- if (fs.existsSync(faas))
35
- configs.push(jsYaml.safeLoad(fs.readFileSync(faas).toString()));
36
- return root;
37
- });
38
- this.origin = deepMerge(...configs);
39
- if (!this.origin.defaults)
40
- throw Error('[faas.yaml] need defaults env.');
41
- this.defaults = deepMerge(this.origin.defaults);
42
- for (const key in this.origin) {
43
- if (key !== 'defaults')
44
- this[key] = deepMerge(this.origin.defaults, this.origin[key]);
45
- const data = this[key];
46
- if (!data.providers)
47
- throw Error(`[faas.yaml] missing key: ${key}/providers`);
48
- if (!data.plugins)
49
- throw Error(`[faas.yaml] missing key: ${key}/plugins`);
50
- for (const pluginKey in data.plugins) {
51
- const plugin = data.plugins[pluginKey];
52
- plugin.name = pluginKey;
53
- if (plugin.provider)
54
- if (typeof plugin.provider === 'string') {
55
- if (!data.providers[plugin.provider])
56
- throw Error(`[faas.yaml] missing provider: ${plugin.provider} <${key}/plugins/${pluginKey}>`);
57
- plugin.provider = data.providers[plugin.provider];
58
- }
59
- else
60
- plugin.provider = deepMerge(data.providers[plugin.provider], plugin.provider);
61
- }
62
- }
63
- }
64
- }
65
- /**
66
- * 加载配置
67
- * @param root {string} 根目录
68
- * @param filename {filename} 目标文件,用于读取目录层级
69
- */
70
- function loadConfig(root, filename) {
71
- return new Config(root, filename);
72
- }
73
-
74
- const FAAS_PACKAGES = [
75
- '@faasjs/browser',
76
- '@faasjs/cli',
77
- '@faasjs/cloud_function',
78
- 'create-faas-app',
79
- '@faasjs/deep_merge',
80
- '@faasjs/deployer',
81
- '@faasjs/eslint-config-recommended',
82
- '@faasjs/eslint-config-vue',
83
- 'faasjs',
84
- '@faasjs/func',
85
- '@faasjs/graphql-server',
86
- '@faasjs/http',
87
- '@faasjs/load',
88
- '@faasjs/logger',
89
- '@faasjs/nuxt',
90
- '@faasjs/redis',
91
- '@faasjs/request',
92
- '@faasjs/server',
93
- '@faasjs/sql',
94
- '@faasjs/tencentcloud',
95
- '@faasjs/test',
96
- '@faasjs/vue-plugin'
97
- ];
98
- const NODE_PACKAGES = [
99
- 'async_hooks',
100
- 'child_process',
101
- 'cluster',
102
- 'crypto',
103
- 'dns',
104
- 'events',
105
- 'fs',
106
- 'http',
107
- 'http2',
108
- 'https',
109
- 'inspector',
110
- 'net',
111
- 'os',
112
- 'path',
113
- 'perf_hooks',
114
- 'process',
115
- 'querystring',
116
- 'readline',
117
- 'repl',
118
- 'stream',
119
- 'string_decoder',
120
- 'tls',
121
- 'trace_events',
122
- 'tty',
123
- 'dgram',
124
- 'udp4',
125
- 'url',
126
- 'util',
127
- 'v8',
128
- 'vm',
129
- 'wasi',
130
- 'worker_threads',
131
- 'zlib'
132
- ];
133
- const EXTERNAL = FAAS_PACKAGES.concat(NODE_PACKAGES);
134
- /**
135
- * 加载 ts 文件
136
- *
137
- * @param filename {string} 完整源文件路径
138
- * @param options {object} 配置项
139
- * @param options.input {object} 读取配置
140
- * @param options.output {object} 写入配置
141
- * @param options.tmp {boolean} 是否为临时文件,true 则生成的文件会被删除,默认为 false
142
- */
143
- async function loadTs(filename, options = Object.create(null)) {
144
- // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
145
- const PackageJSON = require(`${process.cwd()}/package.json`);
146
- const external = PackageJSON['dependencies'] ? EXTERNAL.concat(Object.keys(PackageJSON.dependencies)) : EXTERNAL;
147
- const input = deepMerge({
148
- input: filename,
149
- external,
150
- plugins: [
151
- typescript({ tsconfigOverride: { compilerOptions: { declaration: false } } })
152
- ],
153
- onwarn: () => null
154
- }, options.input || {});
155
- const bundle = await rollup.rollup(input);
156
- const dependencies = Object.create(null);
157
- for (const m of bundle.cache.modules || [])
158
- for (const d of m.dependencies)
159
- if (!d.startsWith('/') && !dependencies[d] && !NODE_PACKAGES.includes(d))
160
- dependencies[d] = '*';
161
- const output = deepMerge({
162
- file: filename + '.tmp.js',
163
- format: 'cjs'
164
- }, options.output || {});
165
- await bundle.write(output);
166
- // eslint-disable-next-line @typescript-eslint/no-var-requires
167
- const module = require(output.file);
168
- if (options.tmp)
169
- fs.unlinkSync(output.file);
170
- return {
171
- module,
172
- dependencies
173
- };
174
- }
175
-
176
- exports.loadConfig = loadConfig;
177
- exports.loadTs = loadTs;
@@ -1,27 +0,0 @@
1
- import { Config as FuncConfig } from '@faasjs/func';
2
- /**
3
- * 配置类
4
- */
5
- export declare class Config {
6
- [key: string]: any;
7
- readonly root: string;
8
- readonly filename: string;
9
- readonly origin: {
10
- [key: string]: FuncConfig;
11
- defaults: FuncConfig;
12
- };
13
- readonly defaults: FuncConfig;
14
- /**
15
- * 创建配置类,并自动读取配置内容
16
- *
17
- * @param root {string} 根目录
18
- * @param filename {filename} 目标文件,用于读取目录层级
19
- */
20
- constructor(root: string, filename: string);
21
- }
22
- /**
23
- * 加载配置
24
- * @param root {string} 根目录
25
- * @param filename {filename} 目标文件,用于读取目录层级
26
- */
27
- export default function loadConfig(root: string, filename: string): Config;
package/lib/load_ts.d.ts DELETED
@@ -1,24 +0,0 @@
1
- import { Func } from '@faasjs/func';
2
- /**
3
- * 加载 ts 文件
4
- *
5
- * @param filename {string} 完整源文件路径
6
- * @param options {object} 配置项
7
- * @param options.input {object} 读取配置
8
- * @param options.output {object} 写入配置
9
- * @param options.tmp {boolean} 是否为临时文件,true 则生成的文件会被删除,默认为 false
10
- */
11
- export default function loadTs(filename: string, options?: {
12
- input?: {
13
- [key: string]: any;
14
- };
15
- output?: {
16
- [key: string]: any;
17
- };
18
- tmp?: boolean;
19
- }): Promise<{
20
- module: Func;
21
- dependencies: {
22
- [key: string]: string;
23
- };
24
- }>;