oc-server 1.1.3 → 1.1.5

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.
@@ -0,0 +1 @@
1
+ export declare function cli(): void;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.cli = void 0;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const node_util_1 = require("node:util");
9
+ const oc_1 = require("./oc");
10
+ const server_1 = require("./server");
11
+ const pkg = require(node_path_1.default.join(process.cwd(), 'package.json'));
12
+ const { templateType } = (0, oc_1.parsePkg)(pkg);
13
+ function cli() {
14
+ const { positionals: [command], values: { help, port = '5000' }, } = (0, node_util_1.parseArgs)({
15
+ allowPositionals: true,
16
+ options: {
17
+ port: {
18
+ type: 'string',
19
+ default: '5000',
20
+ short: 'p',
21
+ },
22
+ help: {
23
+ type: 'boolean',
24
+ default: false,
25
+ short: 'h',
26
+ },
27
+ },
28
+ });
29
+ if (help || !command) {
30
+ console.log(`
31
+ Usage:
32
+ $ oc-server <command> [options]
33
+
34
+ Commands:
35
+ dev Start the development server
36
+
37
+ Options:
38
+ -h, --help Display this message
39
+ `);
40
+ if (help && command === 'dev') {
41
+ console.log(`
42
+ Usage:
43
+ $ oc-server <command> [options]
44
+
45
+ Commands:
46
+ dev Start the development server
47
+
48
+ Options:
49
+ -h, --help Display this message
50
+ -p, --port Port to use (default: 5000)
51
+ `);
52
+ }
53
+ process.exit(0);
54
+ }
55
+ let template;
56
+ try {
57
+ template = require(`${templateType}-compiler/dist/lib/hmr`);
58
+ }
59
+ catch (e) {
60
+ console.error(`The template ${templateType} is not supported. Try updating to the last version`);
61
+ process.exit(1);
62
+ }
63
+ if (command === 'dev') {
64
+ (0, server_1.createServer)({ template, port });
65
+ }
66
+ }
67
+ exports.cli = cli;
@@ -0,0 +1,8 @@
1
+ export interface PluginMock {
2
+ name: string;
3
+ register: {
4
+ register: (options: unknown, dependencies: unknown, next: () => void) => void;
5
+ execute: (...args: unknown[]) => unknown;
6
+ };
7
+ }
8
+ export default function getMockedPlugins(componentsDir: string): PluginMock[];
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const path_1 = __importDefault(require("path"));
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const readJsonSync = (path) => JSON.parse(fs_1.default.readFileSync(path, 'utf-8'));
9
+ const isMockValid = (plugin) => {
10
+ const isFunction = typeof plugin === 'function';
11
+ const isValidObject = !!plugin &&
12
+ typeof plugin === 'object' &&
13
+ typeof plugin.register === 'function' &&
14
+ typeof plugin.execute === 'function';
15
+ return isFunction || isValidObject;
16
+ };
17
+ const defaultRegister = (_options, _dependencies, next) => {
18
+ next();
19
+ };
20
+ const registerStaticMocks = (mocks) => Object.entries(mocks).map(([pluginName, mockedValue]) => {
21
+ return {
22
+ name: pluginName,
23
+ register: {
24
+ register: defaultRegister,
25
+ execute: () => mockedValue,
26
+ },
27
+ };
28
+ });
29
+ const registerDynamicMocks = (ocJsonLocation, mocks) => Object.entries(mocks)
30
+ .map(([pluginName, source]) => {
31
+ let pluginMock;
32
+ try {
33
+ pluginMock = require(path_1.default.resolve(ocJsonLocation, source));
34
+ }
35
+ catch (er) {
36
+ return;
37
+ }
38
+ if (!isMockValid(pluginMock)) {
39
+ return;
40
+ }
41
+ const register = pluginMock.register || defaultRegister;
42
+ const execute = pluginMock.execute || pluginMock;
43
+ return {
44
+ name: pluginName,
45
+ register: { execute, register },
46
+ };
47
+ })
48
+ .filter((pluginMock) => !!pluginMock);
49
+ const findPath = (pathToResolve, fileName) => {
50
+ const rootDir = fs_1.default.realpathSync('.');
51
+ const fileToResolve = path_1.default.join(pathToResolve, fileName);
52
+ if (!fs_1.default.existsSync(fileToResolve)) {
53
+ if (pathToResolve === rootDir) {
54
+ return undefined;
55
+ }
56
+ const getParent = (pathToResolve) => pathToResolve.split('/').slice(0, -1).join('/');
57
+ const parentDir = pathToResolve ? getParent(pathToResolve) : rootDir;
58
+ return findPath(parentDir, fileName);
59
+ }
60
+ return fileToResolve;
61
+ };
62
+ function getMockedPlugins(componentsDir) {
63
+ componentsDir = path_1.default.resolve(componentsDir || '.');
64
+ let plugins = [];
65
+ const ocJsonFileName = 'oc.json';
66
+ const ocJsonPath = findPath(componentsDir, ocJsonFileName);
67
+ if (!ocJsonPath) {
68
+ return plugins;
69
+ }
70
+ const content = readJsonSync(ocJsonPath);
71
+ const ocJsonLocation = ocJsonPath.slice(0, -ocJsonFileName.length);
72
+ if (!content.mocks || !content.mocks.plugins) {
73
+ return plugins;
74
+ }
75
+ plugins = plugins.concat(registerStaticMocks(content.mocks.plugins.static ?? {}));
76
+ plugins = plugins.concat(registerDynamicMocks(ocJsonLocation, content.mocks.plugins.dynamic ?? {}));
77
+ return plugins;
78
+ }
79
+ exports.default = getMockedPlugins;
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ process.env.VITE_CJS_IGNORE_WARNING = 'true';
5
+ const cli_1 = require("./cli");
6
+ (0, cli_1.cli)();
@@ -0,0 +1,52 @@
1
+ /// <reference types="node" />
2
+ import { PluginMock } from './get-mocked-plugins';
3
+ import type { Request } from 'express';
4
+ interface Package {
5
+ name: string;
6
+ version: string;
7
+ oc?: {
8
+ parameters?: Record<string, {
9
+ mandatory: boolean;
10
+ example: string | number | boolean;
11
+ }>;
12
+ files: {
13
+ data?: string;
14
+ template?: {
15
+ type?: string;
16
+ src?: string;
17
+ };
18
+ };
19
+ };
20
+ }
21
+ export declare function parsePkg(pkg: Package): {
22
+ name: string;
23
+ version: string;
24
+ defaultParams: {};
25
+ serverEntry: string | undefined;
26
+ appEntry: string;
27
+ templateType: string;
28
+ };
29
+ export declare function getContext(plugins: PluginMock[], req: Request, params: any, action?: any): {
30
+ context: {
31
+ action: any;
32
+ acceptLanguage: string | undefined;
33
+ easeUrl: string;
34
+ env: {
35
+ name: string;
36
+ };
37
+ params: any;
38
+ plugins: {
39
+ [k: string]: (...args: unknown[]) => unknown;
40
+ };
41
+ renderComponent: () => never;
42
+ renderComponents: () => never;
43
+ requestHeaders: import("http").IncomingHttpHeaders;
44
+ requestIp: string | undefined;
45
+ setEmptyResponse: null;
46
+ staticPath: string;
47
+ setHeader: (header: string, value: string) => void;
48
+ templates: string;
49
+ };
50
+ responseHeaders: Record<string, string>;
51
+ };
52
+ export {};
package/dist/cli/oc.js ADDED
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getContext = exports.parsePkg = void 0;
4
+ function parsePkg(pkg) {
5
+ const serverEntry = pkg.oc?.files?.data;
6
+ let appEntry = pkg.oc?.files?.template?.src || '';
7
+ if (!appEntry) {
8
+ throw new Error('Missing an entry on your package.json under oc.files.template.src');
9
+ }
10
+ if (!appEntry.startsWith('/')) {
11
+ appEntry = `/${appEntry}`;
12
+ }
13
+ const defaultParams = (() => {
14
+ let params = {};
15
+ if (pkg.oc?.parameters) {
16
+ params = Object.fromEntries(Object.entries(pkg.oc.parameters || {})
17
+ .filter(([, param]) => {
18
+ return !!param.mandatory && 'example' in param;
19
+ })
20
+ .map(([paramName, param]) => [paramName, param.example]));
21
+ }
22
+ return params;
23
+ })();
24
+ const templateType = pkg.oc?.files?.template?.type;
25
+ if (!templateType) {
26
+ throw new Error('Missing an entry on your package.json under oc.files.template.type');
27
+ }
28
+ return {
29
+ name: pkg.name,
30
+ version: pkg.version,
31
+ defaultParams,
32
+ serverEntry,
33
+ appEntry,
34
+ templateType,
35
+ };
36
+ }
37
+ exports.parsePkg = parsePkg;
38
+ function getContext(plugins, req, params, action) {
39
+ const responseHeaders = {};
40
+ const context = {
41
+ action,
42
+ acceptLanguage: req.headers['accept-language'],
43
+ easeUrl: '/',
44
+ env: { name: 'local' },
45
+ params,
46
+ plugins: Object.fromEntries(plugins.map((plugin) => [plugin.name, plugin.register.execute])),
47
+ renderComponent: () => {
48
+ throw new Error('renderComponent is not implemented in the server context');
49
+ },
50
+ renderComponents: () => {
51
+ throw new Error('renderComponents is not implemented in the server context');
52
+ },
53
+ requestHeaders: req.headers,
54
+ requestIp: req.ip,
55
+ setEmptyResponse: null,
56
+ staticPath: '/',
57
+ setHeader: (header, value) => {
58
+ if (!(typeof header === 'string' && typeof value === 'string')) {
59
+ throw new Error('context.setHeader parameters must be strings');
60
+ }
61
+ if (header && value) {
62
+ responseHeaders[header.toLowerCase()] = value;
63
+ }
64
+ },
65
+ templates: 'repository.getTemplatesInfo()',
66
+ };
67
+ return { context, responseHeaders };
68
+ }
69
+ exports.getContext = getContext;
@@ -0,0 +1,13 @@
1
+ export declare function createServer({ template, port, }: {
2
+ template: Template;
3
+ port: string;
4
+ }): Promise<void>;
5
+ interface Template {
6
+ appBlock: (opts: {
7
+ name: string;
8
+ version: string;
9
+ entry: string;
10
+ }) => string;
11
+ plugin?: () => any;
12
+ }
13
+ export {};
@@ -1,10 +1,9 @@
1
- #!/usr/bin/env node
2
1
  "use strict";
3
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
4
  };
6
5
  Object.defineProperty(exports, "__esModule", { value: true });
7
- process.env.VITE_CJS_IGNORE_WARNING = 'true';
6
+ exports.createServer = void 0;
8
7
  const node_fs_1 = __importDefault(require("node:fs"));
9
8
  const node_path_1 = __importDefault(require("node:path"));
10
9
  const node_vm_1 = __importDefault(require("node:vm"));
@@ -13,31 +12,11 @@ const vite_1 = require("vite");
13
12
  const esbuild_1 = __importDefault(require("esbuild"));
14
13
  const oc_client_browser_1 = __importDefault(require("oc-client-browser"));
15
14
  const cssModulesPlugin_1 = __importDefault(require("oc-vite-compiler/dist/lib/cssModulesPlugin"));
16
- const get_mocked_plugins_js_1 = __importDefault(require("oc/dist/cli/domain/get-mocked-plugins.js"));
17
- const node_util_1 = require("node:util");
15
+ const oc_1 = require("./oc");
16
+ const get_mocked_plugins_1 = __importDefault(require("./get-mocked-plugins"));
18
17
  const promisify = (fn) => (...args) => new Promise((resolve, reject) => fn(...args, (err, data) => (err ? reject(err) : resolve(data))));
19
- const plugins = (0, get_mocked_plugins_js_1.default)({ err: () => { }, log: () => { }, ok: () => { }, warn: () => { } }, node_path_1.default.join(process.cwd(), '..'));
20
- const pkg = require(node_path_1.default.join(process.cwd(), 'package.json'));
21
- const serverEntry = pkg.oc?.files?.data;
22
- let appEntry = pkg.oc?.files?.template?.src || '';
23
- if (!appEntry) {
24
- console.log('Missing an entry on your package.json under oc.files.template.src');
25
- process.exit(1);
26
- }
27
- if (!appEntry.startsWith('/')) {
28
- appEntry = `/${appEntry}`;
29
- }
30
- const defaultParams = (() => {
31
- let params = {};
32
- if (pkg.oc?.parameters) {
33
- params = Object.fromEntries(Object.entries(pkg.oc.parameters || {})
34
- .filter(([, param]) => {
35
- return !!param.mandatory && 'example' in param;
36
- })
37
- .map(([paramName, param]) => [paramName, param.example]));
38
- }
39
- return params;
40
- })();
18
+ const pk = require(node_path_1.default.join(process.cwd(), 'package.json'));
19
+ const { name, version, appEntry, serverEntry, defaultParams } = (0, oc_1.parsePkg)(pk);
41
20
  function getDataProvider() {
42
21
  if (!serverEntry) {
43
22
  return async (context) => ({ ...(context.params ?? {}) });
@@ -57,37 +36,6 @@ function getDataProvider() {
57
36
  const dataProvider = backend.data || backend.server.getData();
58
37
  return promisify(dataProvider);
59
38
  }
60
- function getContext(req, params, action) {
61
- const responseHeaders = {};
62
- const context = {
63
- action,
64
- acceptLanguage: req.headers['accept-language'],
65
- easeUrl: '/',
66
- env: { name: 'local' },
67
- params,
68
- plugins: Object.fromEntries(plugins.map((plugin) => [plugin.name, plugin.register.execute])),
69
- renderComponent: () => {
70
- throw new Error('renderComponent is not implemented in the server context');
71
- },
72
- renderComponents: () => {
73
- throw new Error('renderComponents is not implemented in the server context');
74
- },
75
- requestHeaders: req.headers,
76
- requestIp: req.ip,
77
- setEmptyResponse: null,
78
- staticPath: '/',
79
- setHeader: (header, value) => {
80
- if (!(typeof header === 'string' && typeof value === 'string')) {
81
- throw new Error('context.setHeader parameters must be strings');
82
- }
83
- if (header && value) {
84
- responseHeaders[header.toLowerCase()] = value;
85
- }
86
- },
87
- templates: 'repository.getTemplatesInfo()',
88
- };
89
- return { context, responseHeaders };
90
- }
91
39
  function getBaseTemplate(appBlock) {
92
40
  const baseTemplate = `
93
41
  <!DOCTYPE html>
@@ -106,7 +54,7 @@ function getBaseTemplate(appBlock) {
106
54
  </head>
107
55
  <body>
108
56
  <script src="/oc-client/client.js"></script>
109
- ${appBlock({ name: pkg.name, version: pkg.version, entry: appEntry })}
57
+ ${appBlock({ name, version, entry: appEntry })}
110
58
  </body>
111
59
  </html>
112
60
  `;
@@ -127,8 +75,8 @@ async function getHtmlTemplate(appBlock, filePath = 'index.html') {
127
75
  }
128
76
  </script>
129
77
  ${appBlock({
130
- name: pkg.name,
131
- version: pkg.version,
78
+ name,
79
+ version,
132
80
  entry: appEntry,
133
81
  })}</body>`);
134
82
  }
@@ -141,14 +89,14 @@ async function createServer({ template, port, }) {
141
89
  const { dev: clientJs } = oc_client_browser_1.default.compileSync();
142
90
  const app = (0, express_1.default)();
143
91
  const dataProvider = getDataProvider();
92
+ const plugins = (0, get_mocked_plugins_1.default)(node_path_1.default.join(process.cwd(), '..'));
144
93
  for (const plugin of plugins) {
145
94
  plugin.register.register(null, null, () => { });
146
95
  }
147
96
  app.use(express_1.default.json());
148
97
  const vite = await (0, vite_1.createServer)({
149
98
  server: { middlewareMode: true },
150
- // @ts-ignore
151
- plugins: [(0, cssModulesPlugin_1.default)(), template.plugin()],
99
+ plugins: [(0, cssModulesPlugin_1.default)(), template.plugin?.()].filter(Boolean),
152
100
  mode: 'development',
153
101
  optimizeDeps: {
154
102
  exclude: ['fsevents'],
@@ -162,7 +110,7 @@ async function createServer({ template, port, }) {
162
110
  app.post('/', async (req, res, next) => {
163
111
  try {
164
112
  const { action, parameters } = req.body.components[0];
165
- const { context, responseHeaders } = getContext(req, parameters, action);
113
+ const { context, responseHeaders } = (0, oc_1.getContext)(plugins, req, parameters, action);
166
114
  const props = await dataProvider(context);
167
115
  const response = [
168
116
  {
@@ -193,7 +141,7 @@ async function createServer({ template, port, }) {
193
141
  const url = req.originalUrl;
194
142
  try {
195
143
  const params = defaultParams;
196
- const { context, responseHeaders } = getContext(req, params);
144
+ const { context, responseHeaders } = (0, oc_1.getContext)(plugins, req, params);
197
145
  let htmlTemplate = await getHtmlTemplate(template.appBlock);
198
146
  const data = await dataProvider(context);
199
147
  htmlTemplate = htmlTemplate.replace('__INITIAL_DATA__', JSON.stringify(data));
@@ -211,63 +159,4 @@ async function createServer({ template, port, }) {
211
159
  app.listen(port);
212
160
  console.log(`Listening on: http://localhost:${port}`);
213
161
  }
214
- const major = Number(process.versions.node.split('.')[0]) || 0;
215
- if (major < 22) {
216
- console.error('This script requires Node.js v22 or higher');
217
- process.exit(1);
218
- }
219
- function cli(template) {
220
- const { positionals: [command], values: { help, port = '5000' }, } = (0, node_util_1.parseArgs)({
221
- allowPositionals: true,
222
- options: {
223
- port: {
224
- type: 'string',
225
- default: '5000',
226
- short: 'p',
227
- },
228
- help: {
229
- type: 'boolean',
230
- default: false,
231
- short: 'h',
232
- },
233
- },
234
- });
235
- if (help || !command) {
236
- console.log(`
237
- Usage:
238
- $ oc-server <command> [options]
239
-
240
- Commands:
241
- dev Start the development server
242
-
243
- Options:
244
- -h, --help Display this message
245
- `);
246
- if (help && command === 'dev') {
247
- console.log(`
248
- Usage:
249
- $ oc-server <command> [options]
250
-
251
- Commands:
252
- dev Start the development server
253
-
254
- Options:
255
- -h, --help Display this message
256
- -p, --port Port to use (default: 5000)
257
- `);
258
- }
259
- process.exit(0);
260
- }
261
- if (command === 'dev') {
262
- createServer({ template, port });
263
- }
264
- }
265
- let template;
266
- try {
267
- template = require(`${pkg.oc?.files?.template?.type}-compiler/dist/lib/hmr`);
268
- }
269
- catch (e) {
270
- console.error(`The template ${pkg.oc?.files?.template?.type} is not supported. Try updating to the last version`);
271
- process.exit(1);
272
- }
273
- cli(template);
162
+ exports.createServer = createServer;
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "oc-server",
3
- "version": "1.1.3",
3
+ "version": "1.1.5",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
- "bin": "dist/cli.js",
7
+ "bin": "dist/cli/index.js",
8
8
  "scripts": {
9
9
  "build": "tsc",
10
10
  "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
@@ -21,10 +21,11 @@
21
21
  "dist/**"
22
22
  ],
23
23
  "license": "MIT",
24
- "dependencies": {
25
- "oc": "^0.49.57"
26
- },
27
24
  "devDependencies": {
28
25
  "@types/express": "^4.17.21"
26
+ },
27
+ "dependencies": {
28
+ "express": "^4.19.2",
29
+ "oc-client-browser": "^1.8.0"
29
30
  }
30
- }
31
+ }
File without changes