Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
406 lines (399 loc) · 12.8 KB
/
Copy pathindex.js
File metadata and controls
406 lines (399 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
const Workflow = require("@saltcorn/data/models/workflow");
const Form = require("@saltcorn/data/models/form");
const File = require("@saltcorn/data/models/file");
const Plugin = require("@saltcorn/data/models/plugin");
const db = require("@saltcorn/data/db");
const { getState, features } = require("@saltcorn/data/db/state");
const { spawn } = require("child_process");
const fs = require("fs").promises;
const path = require("path");
const buildMainBundle = async (buildMode, libPath, libMain, timestamp) => {
getState().log(6, `spawn ${buildMode} build of main bundle`);
const tenant = db.getTenantSchema() || "public";
return new Promise((resolve, reject) => {
const child = spawn(
"npm",
[
"run",
buildMode === "development" ? "build_main_dev" : "build_main",
"--",
"--env",
`user_lib_path=${libPath}`,
"--env",
`user_lib_main=${libMain}`,
"--env",
`tenant_name=${tenant}`,
"--env",
`timestamp=${timestamp}`,
],
{
cwd: __dirname,
}
);
child.stdout.on("data", (data) => {
getState().log(5, data.toString());
});
child.stderr?.on("data", (data) => {
getState().log(2, data.toString());
});
child.on("exit", function (code, signal) {
getState().log(5, `child process exited with code ${code}`);
resolve(code);
});
child.on("error", (msg) => {
getState().log(2, `child process failed: ${msg.code}`);
reject(msg.code);
});
});
};
const prepareDirectory = async ({
codeSource,
codeLocation,
buildMode,
timestamp,
}) => {
const userLibPath = async (source, location) => {
switch (source) {
case "local":
return location;
case "Saltcorn folder":
const folder = await File.findOne(location);
if (!folder)
throw new Error(`Folder ${location} not found in Saltcorn folders`);
return folder.location;
case "Not set":
return null;
default:
throw new Error("Unknown code source");
}
};
const libPath = await userLibPath(codeSource, codeLocation);
const userLibMain = async () => {
const packageJson = JSON.parse(
await fs.readFile(path.join(libPath, "package.json"), "utf8")
);
if (packageJson.main) return packageJson.main;
else {
throw new Error(
"No main field in package.json, please specify the main file"
);
}
};
// ensure a tenant directory exists
const tenant = db.getTenantSchema() || "public";
const tenantDir = path.join(__dirname, "public", tenant);
const tenantDirExists = await fs
.access(tenantDir)
.then(() => true)
.catch(() => false);
if (!tenantDirExists) {
getState().log(5, `Creating tenant directory ${tenantDir}`);
await fs.mkdir(tenantDir, { recursive: true });
}
if (
(await buildMainBundle(
buildMode,
libPath,
libPath ? await userLibMain() : null,
timestamp
)) !== 0
) {
throw new Error("Webpack failed, please check your Server logs");
}
// remove all main_bundle files except the one with the current timestamp
const files = await fs.readdir(tenantDir);
for (const file of files) {
if (file.startsWith("main_bundle_") && !file.endsWith(`${timestamp}.js`)) {
await fs.unlink(path.join(tenantDir, file));
}
}
};
const configuration_workflow = () =>
new Workflow({
onDone: async (context) => {
const { app_code_source, app_code_path, sc_folder, build_mode } = context;
const timestamp = new Date().valueOf();
await prepareDirectory({
codeSource: app_code_source,
codeLocation:
app_code_source === "local"
? app_code_path
: app_code_source === "Saltcorn folder"
? sc_folder
: null,
buildMode: build_mode,
timestamp,
});
context.timestamp = timestamp;
return context;
},
steps: [
{
name: "React plugin",
form: async (context) => {
const directories = await File.find({ isDirectory: true });
return new Form({
blurb:
"This plugin allows using React in Saltcorn views. " +
"You need a global main bundle with React and your custom React components, " +
"plus a bundle per view with some view-specific code. " +
"Here you can create the main bundle, a view bundle comes from the view config dialog. " +
"The 'Build' button generates the main bundle and stays on the page, " +
"'Finish' builds and completes the process. For an example, " +
"take a look at the <a href='https://github.com/saltcorn/react' target='_blank'>README</a>",
additionalHeaders: [
{
headerTag: `<script>
function runBuild(btn) {
if (window.savingViewConfig) {
notifyAlert({
type: "danger",
text: "Please wait until the config is saved",
});
return false;
}
$(btn).data("old-text", "build");
$.ajax({
type: "POST",
headers: {
"CSRF-Token": _sc_globalCsrf,
},
url: "/react/run_build",
success: function (data) {
emptyAlerts();
if (data.notify_success)
notifyAlert({ type: "success", text: data.notify_success })
else
notifyAlert({ type: "success", text: "Build successful" });
setTimeout(() => {
restore_old_button("build_button_id");
}, 50);
},
error: function (data) {
if (data.responseText)
notifyAlert({ type: "danger", text: data.responseText });
else
notifyAlert({ type: "danger", text: "Build failed, please check your Server logs" });
console.error(data);
setTimeout(() => {
restore_old_button("build_button_id");
}, 50);
},
});
return true;
}
</script>`,
},
],
fields: [
{
name: "app_code_source",
label: "Code source",
sublabel: "Where do you want to get your React code from?",
type: "String",
required: true,
attributes: {
options: ["Saltcorn folder", "local", "Not set"],
},
help: {
topic: "Code source",
plugin: "react",
},
},
{
name: "app_code_path",
label: "Path to code",
sublabel: "Please enter a local path to your React code",
type: "String",
// required: true (but has problems with app_code_source showIf)
showIf: { app_code_source: "local" },
},
{
name: "sc_folder",
label: "Saltcorn folder",
sublabel:
"Please select a Saltcorn folder with your React code",
type: "String",
// required: true (but has problems with app_code_source showIf)
showIf: { app_code_source: "Saltcorn folder" },
attributes: {
options: directories.map((d) => d.path_to_serve),
},
},
{
name: "build_mode",
label: "Build mode",
sublabel: "Bundle your code for production or development",
type: "String",
required: true,
default: "production",
attributes: {
options: ["production", "development"],
},
},
],
additionalButtons: [
{
id: "build_button_id",
label: "build",
onclick: "if (runBuild(this)) press_store_button(this);",
class: "btn btn-primary",
},
],
});
},
},
],
});
// Only admins may trigger a rebuild of the main bundle. Uses the centralized
// authorize_api hook when the running core supports it (features.authorize_access_hooks),
// falling back to a plain role check on older cores.
const isRunBuildAuthorized = async (req) => {
if (features?.authorize_access_hooks) {
return await getState().authorizeApi(req.user, {
route: "react/run_build",
action: "post",
req,
});
}
return !!(req.user && req.user.role_id <= 1);
};
const routes = ({ app_code_source, app_code_path, sc_folder, build_mode }) => {
return [
{
url: "/react/run_build",
method: "post",
callback: async (req, res) => {
if (!(await isRunBuildAuthorized(req))) {
res.status(401).json({ error: "Not authorized" });
return;
}
getState().log(5, "Building your React code");
getState().log(
6,
`app_code_source: ${app_code_source}, app_code_path: ${app_code_path}, ` +
`sc_folder: ${sc_folder}, build_mode: ${build_mode}, `
);
const timestamp = new Date().valueOf();
await prepareDirectory({
codeSource: app_code_source,
codeLocation:
app_code_source === "local"
? app_code_path
: app_code_source === "Saltcorn folder"
? sc_folder
: null,
buildMode: build_mode,
timestamp,
});
let plugin = await Plugin.findOne({ name: "react" });
if (!plugin) {
plugin = await Plugin.findOne({
name: "@saltcorn/react",
});
}
plugin.configuration.timestamp = timestamp;
await plugin.upsert();
getState().processSend({
refresh_plugin_cfg: plugin.name,
tenant: db.getTenantSchema(),
});
res.json({ notify_success: "Build successful" });
},
},
];
};
module.exports = {
sc_plugin_api_version: 1,
plugin_name: "react",
configuration_workflow,
routes,
authorize_api: (cfg) => async (request, user) => {
if (request.route !== "react/run_build") return null;
return user && user.role_id <= 1
? { decision: "allow" }
: {
decision: "deny",
reason: "Only admins may rebuild the React bundle",
};
},
// Gates the "React" viewtemplate's build_user_code route (react_view.js) -
// only admins may rebuild a view's per-view bundle. Scoped to that one
// route so it never weighs in on the view's regular get/post rendering.
authorize_view: (cfg) => async (request, user) => {
if (
request.action !== "post" ||
request.route !== "build_user_code" ||
request.view?.viewtemplate !== "React"
)
return null;
return user && user.role_id <= 1
? { decision: "allow" }
: {
decision: "deny",
reason: "Only admins may rebuild the React view bundle",
};
},
viewtemplates: (cfg) => [require("./react_view")],
headers: (cfg) => {
const tenant = db.getTenantSchema() || "public";
return [
{
headerTag: `<script>var tenant_name = "${tenant}";</script>`,
},
{
script: `/plugins/public/react/${tenant}/main_bundle_${cfg.timestamp}.js`,
},
];
},
copilot_skills: (cfg) => [require("./copilot-skill-legacy")(cfg)],
exchange: (cfg) => ({ agent_skills: [require("./agent-skill")] }),
onLoad: async (configuration) => {
if (!require("cluster").isMaster) return;
try {
const tenant = db.getTenantSchema() || "public";
const mainBundlePath = path.join(
__dirname,
"public",
tenant,
`main_bundle_${configuration.timestamp}.js`
);
const mainBundleExists = await fs
.access(mainBundlePath)
.then(() => true)
.catch(() => false);
if (!mainBundleExists) {
getState().log(5, "Main bundle does not exist, building it now");
const { app_code_source, app_code_path, sc_folder, build_mode } =
configuration;
const timestamp = new Date().valueOf();
await prepareDirectory({
codeSource: app_code_source,
codeLocation:
app_code_source === "local"
? app_code_path
: app_code_source === "Saltcorn folder"
? sc_folder
: null,
buildMode: build_mode,
timestamp,
});
let plugin = await Plugin.findOne({ name: "react" });
if (!plugin) {
plugin = await Plugin.findOne({
name: "@saltcorn/react",
});
}
plugin.configuration.timestamp = timestamp;
await plugin.upsert();
getState().processSend({
refresh_plugin_cfg: plugin.name,
tenant: db.getTenantSchema(),
});
}
} catch (e) {
getState().log(2, `Error building main bundle: ${e.message}`);
}
},
ready_for_mobile: true,
};