@intelligentgraphics/ig.gfx.packager 3.0.22 → 3.1.0-alpha.1

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.
Files changed (27) hide show
  1. package/build/bin.mjs +1 -1
  2. package/build/{cli-f6586dd5.mjs → cli-fec9c069.mjs} +27 -37
  3. package/build/cli-fec9c069.mjs.map +1 -0
  4. package/build/{dependencies-e2aa1797.mjs → dependencies-d870016d.mjs} +2 -2
  5. package/build/{dependencies-e2aa1797.mjs.map → dependencies-d870016d.mjs.map} +1 -1
  6. package/build/{generateIndex-019c6946.mjs → generateIndex-dd0b4563.mjs} +2 -2
  7. package/build/{generateIndex-019c6946.mjs.map → generateIndex-dd0b4563.mjs.map} +1 -1
  8. package/build/{generateParameterType-ae69726a.mjs → generateParameterType-9a671e36.mjs} +2 -2
  9. package/build/{generateParameterType-ae69726a.mjs.map → generateParameterType-9a671e36.mjs.map} +1 -1
  10. package/build/{index-3d1291e7.mjs → index-0caf1a6e.mjs} +8 -3
  11. package/build/index-0caf1a6e.mjs.map +1 -0
  12. package/build/{index-39c79102.mjs → index-7fa42d48.mjs} +8 -5
  13. package/build/index-7fa42d48.mjs.map +1 -0
  14. package/build/{postinstall-3328545c.mjs → postinstall-81b6f0b0.mjs} +3 -3
  15. package/build/{postinstall-3328545c.mjs.map → postinstall-81b6f0b0.mjs.map} +1 -1
  16. package/build/{publishNpm-532e17a0.mjs → publishNpm-c985bd6e.mjs} +4 -4
  17. package/build/{publishNpm-532e17a0.mjs.map → publishNpm-c985bd6e.mjs.map} +1 -1
  18. package/build/swc-9ed0f3ce.mjs +60 -0
  19. package/build/swc-9ed0f3ce.mjs.map +1 -0
  20. package/build/{versionFile-644c7ff8.mjs → versionFile-cbfd3f4a.mjs} +2 -2
  21. package/build/{versionFile-644c7ff8.mjs.map → versionFile-cbfd3f4a.mjs.map} +1 -1
  22. package/lib/lib.mjs +18 -2514
  23. package/package.json +4 -4
  24. package/readme.md +4 -0
  25. package/build/cli-f6586dd5.mjs.map +0 -1
  26. package/build/index-39c79102.mjs.map +0 -1
  27. package/build/index-3d1291e7.mjs.map +0 -1
package/lib/lib.mjs CHANGED
@@ -1,2517 +1,21 @@
1
- import * as path from 'path';
2
- import * as fs$1 from 'fs/promises';
3
- import * as terser from 'terser';
4
- import * as fs from 'fs';
5
- import { createWriteStream, createReadStream } from 'fs';
6
- import resolve from 'resolve';
1
+ export { b as buildFolders, a as buildFoldersWatch, c as generateIndex, r as releaseFolder } from './lib-5a3a2112.mjs';
2
+ import 'path';
3
+ import 'fs/promises';
4
+ import 'terser';
5
+ import 'fs';
6
+ import 'resolve';
7
7
  import 'write-pkg';
8
- import glob from 'glob';
8
+ import 'glob';
9
9
  import 'write-json-file';
10
- import axios from 'axios';
11
- import ts from 'typescript';
12
- import typedoc from 'typedoc';
13
- import EventEmitter from 'events';
14
- import { SourceMapGenerator, SourceMapConsumer } from 'source-map-js';
15
- import Ajv from 'ajv';
16
- import { pipeline } from 'stream/promises';
17
- import { exec } from 'child_process';
18
- import { promisify } from 'util';
19
- import simpleGit from 'simple-git';
20
- import JSZip from 'jszip';
21
-
22
- const stripUtf8Bom = (text)=>{
23
- // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
24
- // conversion translates it to FEFF (UTF-16 BOM).
25
- if (text.charCodeAt(0) === 0xfeff) {
26
- return text.slice(1);
27
- }
28
- return text;
29
- };
30
-
31
- const readNpmManifest = (directory)=>{
32
- const packageJsonPath = path.join(directory, "package.json");
33
- const packageJson = stripUtf8Bom(fs.readFileSync(packageJsonPath, {
34
- encoding: "utf8"
35
- }));
36
- return JSON.parse(packageJson);
37
- };
38
-
39
- const getNodeErrorCode = (error)=>{
40
- if (error !== null && typeof error === "object" && error.code !== undefined) {
41
- return error.code;
42
- }
43
- };
44
- /**
45
- * Permission denied: An attempt was made to access a file in a way forbidden by its file access permissions.
46
- *
47
- * @param {unknown} error
48
- */ const isErrorEACCES = (error)=>getNodeErrorCode(error) === "EACCES";
49
- /**
50
- * No such file or directory: Commonly raised by fs operations to indicate that a component of the specified pathname does not exist. No entity (file or directory) could be found by the given path.
51
- *
52
- * @param {unknown} error
53
- */ const isErrorENOENT = (error)=>getNodeErrorCode(error) === "ENOENT";
54
- const isErrorEPERM = (error)=>getNodeErrorCode(error) === "EPERM";
55
-
56
- // Functionality related to working with a single package.
57
- const PACKAGE_FILE = "_Package.json";
58
- const INDEX_FILE = "_Index.json";
59
- const ANIMATION_FILE_SUFFIX = ".animation.json";
60
- const parseCreatorPackageName = (manifest)=>{
61
- const [domain, subdomain] = manifest.Package.split(".");
62
- return {
63
- domain,
64
- subdomain
65
- };
66
- };
67
- const readPackageCreatorManifest = (location)=>{
68
- const packageJsonPath = path.join(location.manifestDir, PACKAGE_FILE);
69
- const packageJson = stripUtf8Bom(fs.readFileSync(packageJsonPath, {
70
- encoding: "utf8"
71
- }));
72
- return JSON.parse(packageJson);
73
- };
74
- const writePackageCreatorManifest = (location, creatorPackage)=>{
75
- const packageJsonPath = path.join(location.manifestDir, PACKAGE_FILE);
76
- fs.writeFileSync(packageJsonPath, JSON.stringify(creatorPackage, null, " ") + "\n");
77
- };
78
- const getPackageCreatorIndexPath = (location)=>path.join(location.manifestDir, INDEX_FILE);
79
- const readPackageCreatorIndex = (location)=>{
80
- try {
81
- const indexPath = getPackageCreatorIndexPath(location);
82
- const index = stripUtf8Bom(fs.readFileSync(indexPath, {
83
- encoding: "utf8"
84
- }));
85
- return JSON.parse(index);
86
- } catch (err) {
87
- if (isErrorENOENT(err)) {
88
- return undefined;
89
- }
90
- throw err;
91
- }
92
- };
93
- const writePackageCreatorIndex = (location, index)=>{
94
- const indexPath = getPackageCreatorIndexPath(location);
95
- fs.writeFileSync(indexPath, JSON.stringify(index, null, " ") + "\n");
96
- };
97
- const readPackageNpmManifest = (location)=>{
98
- try {
99
- return readNpmManifest(location.manifestDir);
100
- } catch (err) {
101
- if (isErrorENOENT(err)) {
102
- return undefined;
103
- }
104
- throw err;
105
- }
106
- };
107
- const readPackageAnimationList = (location)=>{
108
- const directoryContent = fs.readdirSync(location.manifestDir);
109
- const animationPathList = [];
110
- for (const entry of directoryContent){
111
- if (entry.endsWith(ANIMATION_FILE_SUFFIX)) {
112
- const animationPath = path.join(location.manifestDir, entry);
113
- animationPathList.push(animationPath);
114
- }
115
- }
116
- return animationPathList;
117
- };
118
- const getPackageReleasesDirectory = (location)=>path.join(location.path, "Releases");
119
-
120
- /**
121
- * Detects a published package from a path.
122
- *
123
- * Can return undefined if the package is not installed.
124
- *
125
- * @param {string} resolveBasePath
126
- * @param {string} name
127
- * @return {*} {(PublishedPackageLocation | undefined)}
128
- */ const detectPublishedPackageFromPath = (resolveBasePath, name)=>{
129
- try {
130
- const manifestPath = resolve.sync(name + "/package.json", {
131
- basedir: resolveBasePath
132
- });
133
- const dir = path.dirname(manifestPath);
134
- return {
135
- _kind: "PublishedPackageLocation",
136
- path: dir
137
- };
138
- } catch (err) {
139
- return undefined;
140
- }
141
- };
142
- const readPublishedPackageNpmManifest = (location)=>{
143
- return readNpmManifest(location.path);
144
- };
145
- const readPublishedPackageCreatorManifest = (location)=>{
146
- try {
147
- const packageJsonPath = path.join(location.path, PACKAGE_FILE);
148
- const packageJson = stripUtf8Bom(fs.readFileSync(packageJsonPath, {
149
- encoding: "utf8"
150
- }));
151
- return JSON.parse(packageJson);
152
- } catch (err) {
153
- if (isErrorENOENT(err)) {
154
- return undefined;
155
- }
156
- throw err;
157
- }
158
- };
159
- const readPublishedPackageCreatorIndex = (location)=>{
160
- try {
161
- const packageJsonPath = path.join(location.path, INDEX_FILE);
162
- const packageJson = stripUtf8Bom(fs.readFileSync(packageJsonPath, {
163
- encoding: "utf8"
164
- }));
165
- const result = JSON.parse(packageJson);
166
- return result;
167
- } catch (err) {
168
- if (isErrorENOENT(err)) {
169
- return undefined;
170
- }
171
- throw err;
172
- }
173
- };
174
-
175
- const readWorkspaceNpmManifest = (workspace)=>{
176
- try {
177
- return readNpmManifest(workspace.path);
178
- } catch (err) {
179
- if (isErrorENOENT(err)) {
180
- throw new Error(`Expected a package.json file to exist in ${workspace.path}. See packager readme for instructions on how to create the package.json.`);
181
- }
182
- throw err;
183
- }
184
- };
185
- const getWorkspaceOutputPath = (workspace)=>path.join(workspace.path, "bin");
186
-
187
- // /**
188
- // * Determines the implicit dependencies of a an actual data workspace package.
189
- // *
190
- // * An implicit dependency is a dependency that is installed for the workspace and has the same runtime environment (evaluator, interactor) as the package.
191
- // *
192
- // * @param {WorkspaceLocation} workspace
193
- // * @param {CreatorPackage} creatorPackage
194
- // * @returns {PublishedPackageLocation[]}
195
- // */
196
- // export const determinePackageImplicitDependencies = (
197
- // workspace: WorkspaceLocation,
198
- // creatorPackage: CreatorPackage,
199
- // ): PublishedPackageLocation[] => {
200
- // const libraries = determineWorkspaceIGLibraries(workspace);
201
- // const results: PublishedPackageLocation[] = [];
202
- // for (const librarylocation of libraries) {
203
- // const libraryManifest =
204
- // readPublishedPackageCreatorManifest(librarylocation);
205
- // if (
206
- // libraryManifest !== undefined &&
207
- // (libraryManifest.Type === "Mixed" ||
208
- // libraryManifest.RunTime === creatorPackage.RunTime)
209
- // ) {
210
- // results.push(librarylocation);
211
- // }
212
- // }
213
- // return results;
214
- // };
215
- /**
216
- * Recursively determines all installed ig libraries for a workspace.
217
- *
218
- * @param {WorkspaceLocation} workspace
219
- * @returns {PublishedPackageLocation[]}
220
- */ const determineWorkspaceIGLibraries = (workspace)=>{
221
- const manifest = readWorkspaceNpmManifest(workspace);
222
- const libraries = collectIGLibraries(workspace, manifest);
223
- const results = new Map();
224
- for (const location of libraries){
225
- const manifest = readPublishedPackageNpmManifest(location);
226
- if (!results.has(manifest.name)) {
227
- results.set(manifest.name, location);
228
- }
229
- }
230
- return Array.from(results.values());
231
- };
232
- const collectIGLibraries = (workspace, manifest)=>{
233
- if (!manifest.dependencies) {
234
- return [];
235
- }
236
- const runtimeDependencies = Object.getOwnPropertyNames(manifest.dependencies);
237
- const result = [];
238
- for (const runtimeDependency of runtimeDependencies){
239
- var _runtimeManifest_ig;
240
- const location = detectPublishedPackageFromPath(workspace.path, runtimeDependency);
241
- if (location === undefined) {
242
- continue;
243
- }
244
- const runtimeManifest = readPublishedPackageNpmManifest(location);
245
- // packages need to explicitly be marked as ig scriptingLibraries
246
- if ((_runtimeManifest_ig = runtimeManifest.ig) == null ? void 0 : _runtimeManifest_ig.scriptingLibrary) {
247
- result.push(location);
248
- result.push(...collectIGLibraries(workspace, runtimeManifest));
249
- }
250
- }
251
- return result;
252
- };
253
-
254
- const readStringFromFile = (filePath)=>fs.readFileSync(filePath, {
255
- encoding: "utf8"
256
- });
257
- const readStringFromFileOrUndefined = (filePath)=>{
258
- try {
259
- return readStringFromFile(filePath);
260
- } catch (err) {
261
- if (!isErrorENOENT(err)) {
262
- throw err;
263
- }
264
- return undefined;
265
- }
266
- };
267
-
268
- const logPackageMessage = (name, step, index, total, maxNameLength = 15)=>{
269
- const numLength = total === undefined ? undefined : total.toString().length;
270
- const indexString = total === undefined || total < 2 ? "" : `${index.toString().padStart(numLength, "0")}/${total} `;
271
- const identifierString = `${indexString}${name.padEnd(maxNameLength)}`;
272
- console.log(`${identifierString} >> ${step}`);
273
- };
274
-
275
- const getPackageTypescriptFiles = (location)=>glob.sync("**/*.ts", {
276
- absolute: true,
277
- cwd: location.scriptsDir,
278
- ignore: "node_modules/**/*"
279
- });
280
-
281
- const PLUGIN_ID = "0feba3a0-b6d1-11e6-9598-0800200c9a66";
282
- /**
283
- * Starts an IG.Asset.Server session and returns the sessionId
284
- *
285
- * @param {SessionStartParams} params
286
- * @returns
287
- */ const startSession = async ({ url, authentication, ...params })=>{
288
- const payload = {
289
- ...params,
290
- user: undefined,
291
- password: undefined,
292
- license: undefined,
293
- plugin: PLUGIN_ID
294
- };
295
- if (authentication.type === "credentials") {
296
- payload.user = authentication.username;
297
- payload.password = authentication.password;
298
- } else if (authentication.type === "license") {
299
- payload.license = authentication.license;
300
- }
301
- const { data: { session: sessionId, state, response } } = await axios.post(`Session/Start2`, JSON.stringify(payload), {
302
- baseURL: url
303
- });
304
- if (state !== "SUCCESS") {
305
- let message = `Could not start session. IG.Asset.Server responded with ${state}`;
306
- if (response) {
307
- message += `: ${response}`;
308
- }
309
- throw new Error(message);
310
- }
311
- return {
312
- _kind: "AssetService",
313
- url,
314
- sessionId,
315
- domain: params.domain,
316
- subDomain: params.subDomain
317
- };
318
- };
319
- const closeSession = async (session)=>{
320
- await axios.get(`Session/Close/${session.sessionId}`, {
321
- baseURL: session.url
322
- });
323
- };
324
- const uploadPackageFromStream = async (session, { name, version }, stream)=>{
325
- await uploadPackageToUrl(session.url, `UploadPackage/${session.sessionId}/${name}_${version}/`, stream);
326
- };
327
- const uploadPackageToUrl = async (url, path, stream)=>{
328
- const { data, status } = await axios.post(path, stream, {
329
- baseURL: url
330
- });
331
- let objectBody;
332
- if (typeof data === "string") {
333
- try {
334
- objectBody = JSON.parse(data);
335
- } catch (err) {}
336
- } else if (typeof data === "object") {
337
- objectBody = data;
338
- }
339
- if (objectBody !== undefined) {
340
- if ("state" in objectBody && objectBody.state !== "SUCCESS") {
341
- throw new Error(objectBody.response ?? objectBody.state);
342
- }
343
- }
344
- if (status >= 400) {
345
- if (objectBody !== undefined) {
346
- let text_1 = "";
347
- for(const key in objectBody){
348
- text_1 += key + ": \n";
349
- if (typeof objectBody[key] === "object") {
350
- text_1 += JSON.stringify(objectBody[key], undefined, 2);
351
- } else {
352
- text_1 += objectBody[key];
353
- }
354
- text_1 += "\n\n";
355
- }
356
- throw new Error(text_1);
357
- }
358
- throw new Error(data);
359
- }
360
- return data;
361
- };
362
- const getExistingPackages = async (session)=>{
363
- const { data } = await axios.get(`Script/GetInformation/${session.sessionId}`, {
364
- baseURL: session.url,
365
- validateStatus: (status)=>status === 404 || status === 200
366
- }).catch((err)=>{
367
- throw new Error(`Failed to get existing packages: ${err.message}`);
368
- });
369
- return data;
370
- };
371
-
372
- const tryReadTsConfig = (location)=>{
373
- const { config } = ts.readConfigFile(path.join(location.scriptsDir, "tsconfig.json"), (path)=>{
374
- try {
375
- return fs.readFileSync(path, "utf8");
376
- } catch {
377
- return undefined;
378
- }
379
- });
380
- return config;
381
- };
382
- const createTSCBuildParticipant = (location, outputDir)=>(env)=>{
383
- const files = getPackageTypescriptFiles(location);
384
- if (files.length === 0) {
385
- env.onBuildStart();
386
- env.onBuildEnd({
387
- type: "success",
388
- artefacts: {
389
- js: "",
390
- definitions: ""
391
- }
392
- });
393
- return {
394
- destroy: ()=>{}
395
- };
396
- }
397
- try {
398
- env.onBuildStart();
399
- env.log("Compiling typescript files");
400
- const compilerOptions = getCompilerOptions(location, outputDir);
401
- const host = ts.createCompilerHost(compilerOptions);
402
- host.getCurrentDirectory = ()=>location.scriptsDir;
403
- let js;
404
- let definitions;
405
- let sourceMap;
406
- host.writeFile = (fileName, data, writeByteOrderMark)=>{
407
- if (fileName.endsWith(".js")) {
408
- js = data;
409
- } else if (fileName.endsWith(".d.ts")) {
410
- definitions = data;
411
- } else if (fileName.endsWith(".js.map")) {
412
- sourceMap = data;
413
- }
414
- };
415
- const programOptions = {
416
- rootNames: files,
417
- options: compilerOptions,
418
- host
419
- };
420
- const program = ts.createProgram(programOptions);
421
- const emitResult = program.emit();
422
- const allDiagnostics = ts.getPreEmitDiagnostics(program);
423
- if (!emitResult.emitSkipped) {
424
- if (allDiagnostics.length > 0) {
425
- console.log(allDiagnostics.map(createErrorMessage).join("\n"));
426
- }
427
- if (js === undefined || definitions === undefined) {
428
- throw new Error(`Unexpected: no js or definitions were created`);
429
- }
430
- env.onBuildEnd({
431
- type: "success",
432
- artefacts: {
433
- js: js.replace(`//# sourceMappingURL=out.js.map`, ""),
434
- definitions,
435
- sourceMap
436
- }
437
- });
438
- } else {
439
- const error = allDiagnostics.map(createErrorMessage).join("\n");
440
- throw new Error(error);
441
- }
442
- } catch (err) {
443
- env.onBuildEnd({
444
- type: "error",
445
- error: err.message
446
- });
447
- }
448
- return {
449
- destroy: ()=>{}
450
- };
451
- };
452
- const createTSCWatchBuildParticipant = (location, outputDir)=>{
453
- return ({ onBuildStart, onBuildEnd })=>{
454
- let state = {
455
- diagnostics: [],
456
- js: undefined,
457
- definitions: undefined,
458
- sourceMap: undefined
459
- };
460
- const customSys = {
461
- ...ts.sys,
462
- writeFile: (fileName, data, writeByteOrderMark)=>{
463
- if (fileName.endsWith(".js")) {
464
- state.js = data;
465
- } else if (fileName.endsWith(".d.ts")) {
466
- state.definitions = data;
467
- } else if (fileName.endsWith(".js.map")) {
468
- state.sourceMap = data;
469
- }
470
- }
471
- };
472
- const reportDiagnostic = (diagnostic)=>{
473
- switch(diagnostic.code){
474
- // file not found - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L4640
475
- // probably deleted -> ignore
476
- case 6053:
477
- return;
478
- // no inputs were found - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L6838
479
- // we don't care about this error. a user might have temporarily deleted the last ts file and will readd one later.
480
- case 18003:
481
- return;
482
- }
483
- state.diagnostics.push(diagnostic);
484
- };
485
- const reportWatchStatusChanged = (diagnostic)=>{
486
- switch(diagnostic.code){
487
- // regular watch mode - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L4567
488
- case 6031:
489
- // incremental watch mode - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L4571
490
- case 6032:
491
- // build start
492
- onBuildStart();
493
- break;
494
- // found one error - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L5119
495
- case 6193:
496
- // found n or 0 errors - https://github.com/microsoft/TypeScript/blob/93e6b9da0c4cb164ca90a5a1b07415e81e97f2b1/src/compiler/diagnosticMessages.json#L5123
497
- case 6194:
498
- // build end
499
- const emitState = state;
500
- state = {
501
- diagnostics: [],
502
- js: undefined,
503
- definitions: undefined,
504
- sourceMap: undefined
505
- };
506
- if (emitState.diagnostics.length > 0) {
507
- const message = emitState.diagnostics.map(createErrorMessage).join("\n");
508
- onBuildEnd({
509
- type: "error",
510
- error: message
511
- });
512
- return;
513
- }
514
- if (emitState.js === undefined || emitState.definitions === undefined) {
515
- onBuildEnd({
516
- type: "success",
517
- artefacts: {
518
- js: ""
519
- }
520
- });
521
- return;
522
- }
523
- onBuildEnd({
524
- type: "success",
525
- artefacts: {
526
- js: emitState.js.replace(`//# sourceMappingURL=out.js.map`, ""),
527
- definitions: emitState.definitions,
528
- sourceMap: emitState.sourceMap
529
- }
530
- });
531
- break;
532
- }
533
- };
534
- const host = ts.createWatchCompilerHost(path.join(location.scriptsDir, "tsconfig.json"), getCompilerOptions(location, outputDir), customSys, ts.createSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportWatchStatusChanged);
535
- const watchProgram = ts.createWatchProgram(host);
536
- const files = getPackageTypescriptFiles(location);
537
- if (files.length === 0) {
538
- onBuildStart();
539
- onBuildEnd({
540
- type: "success",
541
- artefacts: {
542
- js: "",
543
- definitions: ""
544
- }
545
- });
546
- }
547
- return {
548
- destroy: ()=>{
549
- watchProgram.close();
550
- }
551
- };
552
- };
553
- };
554
- const createErrorMessage = (diagnostic)=>{
555
- if (!diagnostic.file) {
556
- return `${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`;
557
- }
558
- const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
559
- const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
560
- return `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`;
561
- };
562
- const getCompilerOptions = (location, outputDir)=>{
563
- const config = tryReadTsConfig(location);
564
- config.compilerOptions.lib = [
565
- "es5",
566
- "dom"
567
- ];
568
- const result = ts.convertCompilerOptionsFromJson(config.compilerOptions, location.scriptsDir);
569
- const compilerOptions = {
570
- ...result.options,
571
- removeComments: false,
572
- declaration: true,
573
- sourceMap: true,
574
- inlineSources: false,
575
- // We don't use tsc to actually emit the files, but we still need to set the correct
576
- // output directory so the compiler can rewrite the `reference path` directives.
577
- outFile: path.join(outputDir, "out.js"),
578
- target: ts.ScriptTarget.ES5,
579
- noEmitOnError: true
580
- };
581
- return compilerOptions;
582
- };
583
-
584
- const generateDocs = async (location, declarationFile, outFolder, name)=>{
585
- const app = new typedoc.Application();
586
- const mediaDir = path.join(location.manifestDir, "Media");
587
- app.bootstrap({
588
- entryPoints: [
589
- declarationFile
590
- ],
591
- media: mediaDir,
592
- out: outFolder,
593
- tsconfig: path.join(location.scriptsDir, "tsconfig.json"),
594
- skipErrorChecking: true
595
- });
596
- app.options.setCompilerOptions([
597
- declarationFile
598
- ], {
599
- target: ts.ScriptTarget.ES5
600
- }, undefined);
601
- app.options.setValue("name", name);
602
- const [readmePath] = glob.sync("**/readme.md", {
603
- absolute: true,
604
- cwd: location.manifestDir
605
- });
606
- if (readmePath) {
607
- app.options.setValue("readme", readmePath);
608
- }
609
- const project = app.convert();
610
- if (project) {
611
- await app.generateDocs(project, outFolder);
612
- }
613
- };
614
-
615
- // Stolen from ig.tools.core
616
- const toposort = (packages)=>{
617
- const queue = Object.getOwnPropertyNames(packages);
618
- const result = [];
619
- let index = 0;
620
- while(queue.length > 0){
621
- if (index >= queue.length) {
622
- throw new Error("Packages can not have cyclic dependencies");
623
- }
624
- const queueEntry = queue[index];
625
- const dependencies = packages[queueEntry];
626
- const dependencyQueued = dependencies.some((dependency)=>queue.includes(dependency));
627
- if (dependencyQueued) {
628
- index++;
629
- continue;
630
- }
631
- queue.splice(index, 1);
632
- index = 0;
633
- result.push(queueEntry);
634
- }
635
- return result;
636
- };
637
-
638
- class BuildManager extends EventEmitter {
639
- constructor(manifest, writer, logStep){
640
- super();
641
- this.manifest = manifest;
642
- this.writer = writer;
643
- this.logStep = logStep;
644
- this.participants = new Map();
645
- this.states = new Map();
646
- }
647
- addParticipant(name, participant) {
648
- this.participants.set(name, participant);
649
- }
650
- run() {
651
- for (const [name] of this.participants){
652
- this.states.set(name, {
653
- type: "busy"
654
- });
655
- }
656
- this.emit("start");
657
- for (const [name, participant] of this.participants){
658
- participant({
659
- onBuildStart: ()=>{
660
- let alreadyBusy = false;
661
- for (const [name, state] of this.states){
662
- if (state.type === "busy") {
663
- alreadyBusy = true;
664
- continue;
665
- }
666
- }
667
- this.states.set(name, {
668
- type: "busy"
669
- });
670
- if (!alreadyBusy) {
671
- this.emit("start");
672
- }
673
- },
674
- onBuildEnd: (result)=>{
675
- this.states.set(name, result);
676
- this.maybeEmit();
677
- },
678
- log: this.logStep
679
- });
680
- }
681
- }
682
- maybeEmit() {
683
- const errors = [];
684
- const results = [];
685
- for (const [_, state] of this.states){
686
- if (state.type === "busy") {
687
- return;
688
- }
689
- if (state.type === "success") {
690
- results.push(state);
691
- } else if (state.type === "error") {
692
- errors.push(state.error);
693
- }
694
- }
695
- if (errors.length > 0) {
696
- this.emit("error", errors.join("\n"));
697
- return;
698
- }
699
- const completeResult = {
700
- js: ""
701
- };
702
- const sourceMapGenerator = new SourceMapGenerator();
703
- for (const result of results){
704
- if (result.artefacts.js) {
705
- if (completeResult.js) {
706
- completeResult.js += "\n";
707
- }
708
- if (result.artefacts.sourceMap) {
709
- const lines = completeResult.js.split("\n").length - 1;
710
- const sourceMap = new SourceMapConsumer(JSON.parse(result.artefacts.sourceMap));
711
- const sources = new Set();
712
- sourceMap.eachMapping((mapping)=>{
713
- sourceMapGenerator.addMapping({
714
- generated: {
715
- line: lines + mapping.generatedLine,
716
- column: mapping.generatedColumn
717
- },
718
- original: {
719
- line: mapping.originalLine,
720
- column: mapping.originalColumn
721
- },
722
- source: mapping.source,
723
- name: mapping.name
724
- });
725
- sources.add(mapping.source);
726
- });
727
- for (const source of sources){
728
- const content = sourceMap.sourceContentFor(source);
729
- if (content !== null) {
730
- sourceMapGenerator.setSourceContent(source, content);
731
- }
732
- }
733
- }
734
- completeResult.js += result.artefacts.js;
735
- }
736
- if (result.artefacts.definitions) {
737
- if (completeResult.definitions) {
738
- completeResult.definitions += "\n";
739
- } else {
740
- completeResult.definitions = "";
741
- }
742
- completeResult.definitions += result.artefacts.definitions;
743
- }
744
- }
745
- completeResult.sourceMap = sourceMapGenerator.toString();
746
- this.writer(completeResult).then(()=>{
747
- this.emit("build");
748
- });
749
- }
750
- }
751
-
752
- var animationSchema = {
753
- $schema: "http://json-schema.org/draft-07/schema",
754
- $id: "https://archive.intelligentgraphics.biz/schemas/gfx/animation.json",
755
- $comment: "Version 2023-02-17, Source: ig.data.gfx/Specs/animation.json",
756
- title: "Animation description format",
757
- additionalProperties: false,
758
- type: "object",
759
- properties: {
760
- $schema: {
761
- type: "string"
762
- },
763
- Id: {
764
- type: "string",
765
- description: "Animation id, to be unique in the project scope. Needs to be a valid JavaScript identifier."
766
- },
767
- Animations: {
768
- type: "array",
769
- description: "Declaration of animation states for gfx objects",
770
- items: {
771
- type: "object",
772
- additionalProperties: false,
773
- properties: {
774
- _: {
775
- type: "string",
776
- description: "Comment"
777
- },
778
- Path: {
779
- $ref: "#/definitions/igxcPath"
780
- },
781
- States: {
782
- type: "object",
783
- additionalProperties: {
784
- type: "object",
785
- additionalProperties: false,
786
- properties: {
787
- Position: {
788
- $ref: "#/definitions/vec3"
789
- },
790
- Rotation: {
791
- $ref: "#/definitions/rotation"
792
- },
793
- Scaling: {
794
- $ref: "#/definitions/vec3"
795
- },
796
- Visibility: {
797
- type: "boolean"
798
- },
799
- Deformation: {
800
- anyOf: [
801
- {
802
- type: "number"
803
- },
804
- {
805
- type: "string"
806
- }
807
- ]
808
- }
809
- }
810
- }
811
- }
812
- }
813
- }
814
- },
815
- Kinematics: {
816
- oneOf: [
817
- {
818
- $ref: "#/definitions/kinematicChain"
819
- },
820
- {
821
- type: "array",
822
- items: {
823
- $ref: "#/definitions/kinematicChain"
824
- }
825
- }
826
- ]
827
- },
828
- LinkedPoints: {
829
- type: "object",
830
- additionalProperties: {
831
- type: "array",
832
- items: {
833
- type: "string"
834
- }
835
- }
836
- },
837
- _: {
838
- type: "string",
839
- description: "Comment"
840
- }
841
- },
842
- definitions: {
843
- vec3: {
844
- type: "object",
845
- additionalProperties: false,
846
- properties: {
847
- X: {
848
- anyOf: [
849
- {
850
- type: "number"
851
- },
852
- {
853
- type: "string"
854
- }
855
- ]
856
- },
857
- Y: {
858
- anyOf: [
859
- {
860
- type: "number"
861
- },
862
- {
863
- type: "string"
864
- }
865
- ]
866
- },
867
- Z: {
868
- anyOf: [
869
- {
870
- type: "number"
871
- },
872
- {
873
- type: "string"
874
- }
875
- ]
876
- },
877
- _: {
878
- type: "string",
879
- description: "Comment"
880
- }
881
- }
882
- },
883
- rotation: {
884
- type: "object",
885
- additionalProperties: false,
886
- properties: {
887
- Q: {
888
- description: "If true, the rotation is considered to be a Quaternion. Otherwise, it's interpreted as Euler arcs and W will be ignored.",
889
- type: "boolean"
890
- },
891
- X: {
892
- anyOf: [
893
- {
894
- type: "number"
895
- },
896
- {
897
- type: "string"
898
- }
899
- ]
900
- },
901
- Y: {
902
- anyOf: [
903
- {
904
- type: "number"
905
- },
906
- {
907
- type: "string"
908
- }
909
- ]
910
- },
911
- Z: {
912
- anyOf: [
913
- {
914
- type: "number"
915
- },
916
- {
917
- type: "string"
918
- }
919
- ]
920
- },
921
- W: {
922
- anyOf: [
923
- {
924
- type: "number"
925
- },
926
- {
927
- type: "string"
928
- }
929
- ]
930
- },
931
- _: {
932
- type: "string",
933
- description: "Comment"
934
- }
935
- }
936
- },
937
- igxcPath: {
938
- type: "string",
939
- description: "Relative path of the target object",
940
- pattern: "^((o|e)\\d+(\\.(o|e)\\d+)*|\\.)$"
941
- },
942
- param: {
943
- type: "string",
944
- pattern: "^Param\\d+$"
945
- },
946
- kinematicChain: {
947
- type: "object",
948
- additionalProperties: false,
949
- properties: {
950
- GeometryBase: {
951
- type: "string"
952
- },
953
- Joints: {
954
- type: "array",
955
- items: {
956
- type: "object",
957
- additionalProperties: false,
958
- properties: {
959
- Name: {
960
- oneOf: [
961
- {
962
- $ref: "#/definitions/param"
963
- },
964
- {
965
- type: "string"
966
- }
967
- ]
968
- },
969
- HeadX: {
970
- oneOf: [
971
- {
972
- $ref: "#/definitions/param"
973
- },
974
- {
975
- $ref: "#/definitions/igxcPath"
976
- }
977
- ]
978
- },
979
- HeadY: {
980
- oneOf: [
981
- {
982
- $ref: "#/definitions/param"
983
- },
984
- {
985
- $ref: "#/definitions/igxcPath"
986
- }
987
- ]
988
- },
989
- HeadZ: {
990
- oneOf: [
991
- {
992
- $ref: "#/definitions/param"
993
- },
994
- {
995
- $ref: "#/definitions/igxcPath"
996
- }
997
- ]
998
- },
999
- Tail: {
1000
- oneOf: [
1001
- {
1002
- $ref: "#/definitions/param"
1003
- },
1004
- {
1005
- $ref: "#/definitions/igxcPath"
1006
- }
1007
- ]
1008
- },
1009
- LimitLeft: {
1010
- type: "number"
1011
- },
1012
- LimitRight: {
1013
- type: "number"
1014
- },
1015
- LimitUp: {
1016
- type: "number"
1017
- },
1018
- LimitDown: {
1019
- type: "number"
1020
- },
1021
- FollowJointNode: {
1022
- $ref: "#/definitions/igxcPath"
1023
- },
1024
- _TargetNodeForFollow: {
1025
- type: "string"
1026
- }
1027
- }
1028
- }
1029
- },
1030
- Target: {
1031
- oneOf: [
1032
- {
1033
- $ref: "#/definitions/igxcPath"
1034
- },
1035
- {
1036
- $ref: "#/definitions/param"
1037
- },
1038
- {
1039
- type: "string",
1040
- enum: [
1041
- "subbase"
1042
- ]
1043
- }
1044
- ]
1045
- },
1046
- Parent: {
1047
- oneOf: [
1048
- {
1049
- $ref: "#/definitions/igxcPath"
1050
- },
1051
- {
1052
- type: "string",
1053
- enum: [
1054
- "root"
1055
- ]
1056
- }
1057
- ]
1058
- },
1059
- Tolerance: {
1060
- type: "number"
1061
- },
1062
- MaxIterations: {
1063
- type: "integer"
1064
- },
1065
- _: {
1066
- type: "string",
1067
- description: "Comment"
1068
- },
1069
- __: {
1070
- type: "string",
1071
- description: "Super Comment"
1072
- }
1073
- }
1074
- }
1075
- }
1076
- };
1077
-
1078
- const createAnimationBuildParticipant = (location, manifest)=>{
1079
- return (env)=>{
1080
- env.onBuildStart();
1081
- bundleAnimations(location, manifest, env.log).then((result)=>{
1082
- env.onBuildEnd({
1083
- type: "success",
1084
- artefacts: {
1085
- js: (result == null ? void 0 : result.js) ?? ""
1086
- }
1087
- });
1088
- }).catch((err)=>{
1089
- env.onBuildEnd({
1090
- type: "error",
1091
- error: err.message
1092
- });
1093
- });
1094
- return {
1095
- destroy: ()=>{}
1096
- };
1097
- };
1098
- };
1099
- const createAnimationWatchBuildParticipant = (location, manifest)=>(env)=>{
1100
- env.onBuildStart();
1101
- bundleAnimations(location, manifest, env.log).then((result)=>{
1102
- env.onBuildEnd({
1103
- type: "success",
1104
- artefacts: {
1105
- js: (result == null ? void 0 : result.js) ?? ""
1106
- }
1107
- });
1108
- }).catch((err)=>{
1109
- env.onBuildEnd({
1110
- type: "error",
1111
- error: err.message
1112
- });
1113
- });
1114
- (async ()=>{
1115
- for await (const event of fs$1.watch(location.scriptsDir)){
1116
- if (event.filename.endsWith(".animation.json")) {
1117
- env.onBuildStart();
1118
- try {
1119
- const result = await bundleAnimations(location, manifest, env.log);
1120
- env.onBuildEnd({
1121
- type: "success",
1122
- artefacts: {
1123
- js: (result == null ? void 0 : result.js) ?? ""
1124
- }
1125
- });
1126
- } catch (err) {
1127
- env.onBuildEnd({
1128
- type: "error",
1129
- error: err.message
1130
- });
1131
- }
1132
- }
1133
- }
1134
- })();
1135
- return {
1136
- destroy: ()=>{}
1137
- };
1138
- };
1139
- const bundleAnimations = async (location, manifest, logStep)=>{
1140
- const animations = new Map();
1141
- for (const scriptFilePath of readPackageAnimationList(location)){
1142
- const content = await fs$1.readFile(scriptFilePath, {
1143
- encoding: "utf8"
1144
- });
1145
- let data;
1146
- try {
1147
- data = JSON.parse(content);
1148
- } catch (err) {
1149
- const relativePath = path.relative(location.path, scriptFilePath);
1150
- if (err instanceof SyntaxError) {
1151
- throw new Error(`Encountered invalid syntax in file "${relativePath}": ${String(err)}`);
1152
- }
1153
- throw new Error(`Encountered an unexpected error while parsing animation json file at path "${relativePath}"`, {
1154
- cause: err
1155
- });
1156
- }
1157
- if (!data.Id) {
1158
- const fileName = path.basename(scriptFilePath, ".animation.json");
1159
- data.Id = fileName;
1160
- }
1161
- (await getAnimationJsonValidation())(data);
1162
- delete data.$schema;
1163
- animations.set(data.Id, JSON.stringify(data));
1164
- }
1165
- if (animations.size > 0) {
1166
- const scope = manifest.Scope ?? manifest.Package;
1167
- const scopeParts = scope.split(".");
1168
- let js = createNamespace(scopeParts);
1169
- for (const [name, content] of animations){
1170
- js += `${scope}["${name}"] = ` + content + ";";
1171
- logStep(`Adding animation ${scope}.${name}`);
1172
- }
1173
- return {
1174
- js
1175
- };
1176
- }
1177
- return undefined;
1178
- };
1179
- const createNamespace = (parts)=>{
1180
- let code = `var ${parts[0]};`;
1181
- for(let index = 0; index < parts.length; index++){
1182
- const path = parts.slice(0, index + 1).join(".");
1183
- code += `\n(${path} = ${path} || {});`;
1184
- }
1185
- return code;
1186
- };
1187
- let validateAnimationJson;
1188
- const getAnimationJsonValidation = async ()=>{
1189
- if (validateAnimationJson === undefined) {
1190
- validateAnimationJson = new Ajv({
1191
- coerceTypes: true,
1192
- allErrors: true,
1193
- removeAdditional: true,
1194
- useDefaults: "empty",
1195
- validateSchema: "log"
1196
- }).compile(animationSchema);
1197
- }
1198
- return validateAnimationJson;
1199
- };
1200
-
1201
- const buildFolders = async (options)=>{
1202
- if (options.outDir !== undefined && options.clean) {
1203
- await fs$1.rm(options.outDir, {
1204
- recursive: true
1205
- });
1206
- }
1207
- const workspace = options.workspace;
1208
- const folders = options.packages;
1209
- let sortedPackages = sortPackagesByBuildOrder(folders);
1210
- let index = 1;
1211
- const manifests = new Map(sortedPackages.map((location)=>[
1212
- location,
1213
- readPackageCreatorManifest(location)
1214
- ]));
1215
- const maxNameLength = Array.from(manifests.values(), (manifest)=>manifest.Package.length).reduce((acc, length)=>Math.max(acc, length), 0);
1216
- for (const location of sortedPackages){
1217
- await ensureTsConfig(location);
1218
- const data = manifests.get(location);
1219
- const logStep = (step)=>logPackageMessage(data.Package, step, index, folders.length, maxNameLength);
1220
- const outputDirectory = options.outDir || location.scriptsDir;
1221
- await fs$1.mkdir(outputDirectory, {
1222
- recursive: true
1223
- });
1224
- const manager = new BuildManager(data, (result)=>writeBuildResult(result, data, location, workspace, outputDirectory, options.minimize, logStep), logStep);
1225
- if (options.banner) {
1226
- manager.addParticipant("banner", createBannerCommentBuildParticipant(options.banner));
1227
- }
1228
- manager.addParticipant("tsc", createTSCBuildParticipant(location, outputDirectory));
1229
- manager.addParticipant("animation", createAnimationBuildParticipant(location, data));
1230
- await new Promise((resolve, reject)=>{
1231
- manager.addListener("start", ()=>{
1232
- logStep(`Build started`);
1233
- });
1234
- manager.addListener("error", (error)=>{
1235
- reject(new Error(error));
1236
- });
1237
- manager.addListener("build", ()=>{
1238
- logStep(`Build complete`);
1239
- resolve();
1240
- });
1241
- manager.run();
1242
- });
1243
- if (options.docs) {
1244
- logStep("Generating typedoc documentation");
1245
- await generateDocs(location, path.join(outputDirectory, `${data.Package}.d.ts`), path.join(workspace.path, "docs", data.Package), data.Package);
1246
- }
1247
- index++;
1248
- }
1249
- };
1250
- const buildFoldersWatch = async (options)=>{
1251
- if (options.outDir !== undefined && options.clean) {
1252
- await fs$1.rm(options.outDir, {
1253
- recursive: true
1254
- });
1255
- }
1256
- const workspace = options.workspace;
1257
- const folders = options.packages;
1258
- let sortedPackages = sortPackagesByBuildOrder(folders);
1259
- let index = 1;
1260
- const manifests = new Map(sortedPackages.map((location)=>[
1261
- location,
1262
- readPackageCreatorManifest(location)
1263
- ]));
1264
- const maxNameLength = Array.from(manifests.values(), (manifest)=>manifest.Package.length).reduce((acc, length)=>Math.max(acc, length), 0);
1265
- for (const location of sortedPackages){
1266
- await ensureTsConfig(location);
1267
- const data = manifests.get(location);
1268
- const currentIndex = index;
1269
- const logStep = (step)=>logPackageMessage(data.Package, step, currentIndex, folders.length, maxNameLength);
1270
- const outputDirectory = options.outDir || location.scriptsDir;
1271
- await fs$1.mkdir(outputDirectory, {
1272
- recursive: true
1273
- });
1274
- const manager = new BuildManager(data, (result)=>writeBuildResult(result, data, location, workspace, outputDirectory, options.minimize, logStep), logStep);
1275
- if (options.banner) {
1276
- manager.addParticipant("banner", createBannerCommentBuildParticipant(options.banner));
1277
- }
1278
- manager.addParticipant("tsc", createTSCWatchBuildParticipant(location, outputDirectory));
1279
- manager.addParticipant("animation", createAnimationWatchBuildParticipant(location, data));
1280
- await new Promise((resolve, reject)=>{
1281
- manager.addListener("start", ()=>{
1282
- logStep(`Build started`);
1283
- });
1284
- manager.addListener("error", (error)=>{
1285
- logStep(`Build failed: ${error}`);
1286
- resolve();
1287
- });
1288
- manager.addListener("build", ()=>{
1289
- logStep(`Build complete`);
1290
- resolve();
1291
- });
1292
- manager.run();
1293
- });
1294
- index++;
1295
- }
1296
- await new Promise(()=>{});
1297
- };
1298
- const writeBuildResult = async (buildResult, manifest, location, workspace, outputDirectory, minimize, logStep)=>{
1299
- let js = buildResult.js;
1300
- if (buildResult.sourceMap) {
1301
- js += `\n//# sourceMappingURL=${manifest.Package}.js.map`;
1302
- }
1303
- await fs$1.writeFile(path.join(outputDirectory, `${manifest.Package}.js`), js, {
1304
- encoding: "utf8"
1305
- });
1306
- if (buildResult.definitions !== undefined) {
1307
- await fs$1.writeFile(path.join(outputDirectory, `${manifest.Package}.d.ts`), buildResult.definitions, {
1308
- encoding: "utf8"
1309
- });
1310
- }
1311
- if (buildResult.sourceMap !== undefined) {
1312
- await fs$1.writeFile(path.join(outputDirectory, `${manifest.Package}.js.map`), buildResult.sourceMap, {
1313
- encoding: "utf8"
1314
- });
1315
- }
1316
- if (minimize) {
1317
- logStep("Minifying the output");
1318
- const minifyResult = await terser.minify(js, {
1319
- ecma: 5,
1320
- sourceMap: {
1321
- content: buildResult.sourceMap,
1322
- includeSources: false
1323
- }
1324
- });
1325
- const minifiedPath = path.join(outputDirectory, `${manifest.Package}.min.js`);
1326
- await fs$1.writeFile(minifiedPath, minifyResult.code, {
1327
- encoding: "utf8"
1328
- });
1329
- if (minifyResult.map !== undefined) {
1330
- await fs$1.writeFile(minifiedPath + ".map", typeof minifyResult.map === "string" ? minifyResult.map : JSON.stringify(minifyResult.map), {
1331
- encoding: "utf8"
1332
- });
1333
- }
1334
- }
1335
- if (location.path.includes("Basics") && buildResult.definitions !== undefined) {
1336
- await fs$1.mkdir(path.join(workspace.path, "lib"), {
1337
- recursive: true
1338
- });
1339
- logStep("Copying basics definition file to the lib folder");
1340
- await fs$1.writeFile(path.join(workspace.path, "lib", `${manifest.Package}.d.ts`), buildResult.definitions, {
1341
- encoding: "utf8"
1342
- });
1343
- }
1344
- };
1345
- const createBannerCommentBuildParticipant = (options)=>(env)=>{
1346
- env.onBuildStart();
1347
- const banner = createBannerComment(options);
1348
- env.onBuildEnd({
1349
- type: "success",
1350
- artefacts: {
1351
- js: banner ?? "",
1352
- definitions: banner ?? ""
1353
- }
1354
- });
1355
- return {
1356
- destroy: ()=>{}
1357
- };
1358
- };
1359
- const ensureTsConfig = async (location)=>{
1360
- const tsconfigPath = path.join(location.scriptsDir, "tsconfig.json");
1361
- try {
1362
- const content = JSON.parse(await fs$1.readFile(tsconfigPath, "utf8"));
1363
- applyTsConfigOption(content);
1364
- await fs$1.writeFile(tsconfigPath, JSON.stringify(content, undefined, " "), "utf8");
1365
- } catch (err) {
1366
- if (!isErrorENOENT(err)) {
1367
- throw err;
1368
- }
1369
- const content = {};
1370
- applyTsConfigOption(content);
1371
- await fs$1.writeFile(tsconfigPath, JSON.stringify(content, undefined, " "), "utf8");
1372
- }
1373
- };
1374
- const applyTsConfigOption = (data)=>{
1375
- data.compilerOptions = data.compilerOptions ?? {};
1376
- data.compilerOptions.target = "es5";
1377
- data.compilerOptions.lib = [
1378
- "es5",
1379
- "dom"
1380
- ];
1381
- };
1382
- const sortPackagesByBuildOrder = (folders)=>{
1383
- const packages = Array.from(folders).reduce((acc, location)=>{
1384
- const data = readPackageNpmManifest(location);
1385
- if (data !== undefined) {
1386
- acc[data.name] = {
1387
- data,
1388
- location
1389
- };
1390
- } else {
1391
- acc[location.path] = {
1392
- data: undefined,
1393
- location
1394
- };
1395
- }
1396
- return acc;
1397
- }, {});
1398
- const packageDependencies = Object.getOwnPropertyNames(packages).reduce((acc, packageName)=>{
1399
- const packageData = packages[packageName];
1400
- if (packageData.data === undefined) {
1401
- acc[packageName] = [];
1402
- } else {
1403
- acc[packageName] = Object.getOwnPropertyNames({
1404
- ...packageData.data.devDependencies,
1405
- ...packageData.data.dependencies,
1406
- ...packageData.data.peerDependencies
1407
- }).filter((packageName)=>packages[packageName] !== undefined);
1408
- }
1409
- return acc;
1410
- }, {});
1411
- const sortedPackages = toposort(packageDependencies);
1412
- const result = [];
1413
- for (const packageName of sortedPackages){
1414
- const location = packages[packageName].location;
1415
- if (readPackageCreatorManifest(location).Package.endsWith(".Basics")) {
1416
- result.unshift(location);
1417
- } else {
1418
- result.push(location);
1419
- }
1420
- }
1421
- return result;
1422
- };
1423
- const createBannerComment = (banner)=>{
1424
- const bannerParts = [];
1425
- if (banner.text) {
1426
- bannerParts.push(" * " + banner.text);
1427
- }
1428
- {
1429
- const details = [];
1430
- if (banner.version) {
1431
- details.push(`Version: ${banner.version}`);
1432
- }
1433
- if (banner.commit) {
1434
- if (banner.commitDirty) {
1435
- details.push(`Commit: ${banner.commit} (dirty)`);
1436
- } else {
1437
- details.push(`Commit: ${banner.commit}`);
1438
- }
1439
- }
1440
- if (banner.date) {
1441
- details.push(`Date: ${banner.date.toISOString()}`);
1442
- }
1443
- const detailsText = details.map((line)=>` * ${line}`).join("\n");
1444
- if (detailsText) {
1445
- bannerParts.push(detailsText);
1446
- }
1447
- }
1448
- const bannerText = bannerParts.join("\n\n");
1449
- if (bannerText) {
1450
- return `/*
1451
- ${bannerText}
1452
- *
1453
- * @preserve
1454
- */`;
1455
- }
1456
- return undefined;
1457
- };
1458
-
1459
- const getVersionInformationFromGit = async (workspaceLocation, packageLocation)=>{
1460
- try {
1461
- var _log_latest, _log_latest1;
1462
- const git = simpleGit({
1463
- baseDir: workspaceLocation.path
1464
- });
1465
- // check wether the files for a folder are changed
1466
- // if so, mark as dirty
1467
- const diff = await git.diffSummary();
1468
- const dirty = diff.files.some((file)=>{
1469
- if (file.file.toLowerCase().includes("releases") || file.file.toLowerCase().endsWith("version.ts") || file.file.toLowerCase().endsWith("package.json")) {
1470
- return false;
1471
- }
1472
- const fullPath = path.resolve(workspaceLocation.path, file.file);
1473
- const relativePath = path.relative(packageLocation.path, fullPath);
1474
- return !relativePath.startsWith("..");
1475
- });
1476
- const log = await git.log({
1477
- maxCount: 1
1478
- });
1479
- const commit = !((_log_latest = log.latest) == null ? void 0 : _log_latest.hash) ? undefined : log.latest.hash.substring(0, 7);
1480
- return {
1481
- commit,
1482
- dirty,
1483
- commitDate: (_log_latest1 = log.latest) == null ? void 0 : _log_latest1.date
1484
- };
1485
- } catch (err) {
1486
- return {};
1487
- }
1488
- };
1489
-
1490
- const getWorkspaceBannerText = (manifest)=>{
1491
- var _manifest_packager;
1492
- let bannerText = manifest == null ? void 0 : (_manifest_packager = manifest.packager) == null ? void 0 : _manifest_packager.banner;
1493
- if (bannerText) {
1494
- const match = bannerText.match(/Copyright \(C\) (\d+)( ?- ?(\d+))?/);
1495
- if (match !== null) {
1496
- const startYear = parseInt(match[1]);
1497
- const endYear = new Date().getFullYear();
1498
- if (startYear !== endYear) {
1499
- bannerText = bannerText.replace(match[0], `Copyright (C) ${startYear} - ${endYear}`);
1500
- } else {
1501
- bannerText = bannerText.replace(match[0], `Copyright (C) ${startYear}`);
1502
- }
1503
- }
1504
- }
1505
- return bannerText;
1506
- };
1507
-
1508
- // Stolen from ig.tools.core
1509
- class PackageVersion {
1510
- static #_ = // https://regex101.com/r/90PEY9/1
1511
- this.fullTextMatcher = /(\d+)(\.(\d+)(\.(\d+)(\.(\d+))?(-([^\.]+)\.(\d+))?)?)?/;
1512
- static #_2 = this.lineMatcher = /^(\d+)(\.(\d+)(\.(\d+)(\.(\d+))?(-([^\.]+)\.(\d+))?)?)?$/;
1513
- static extractFromText(input, description) {
1514
- if (input === undefined) {
1515
- throw new Error(`Can not parse version from undefined`);
1516
- }
1517
- const match = input.match(PackageVersion.fullTextMatcher);
1518
- if (!match) {
1519
- throw new Error(`Could not extract a version from input: ${input}`);
1520
- }
1521
- return PackageVersion.fromMatch(match, description);
1522
- }
1523
- static extractFromLine(input, description) {
1524
- if (input === undefined) {
1525
- throw new Error(`Can not parse version from undefined`);
1526
- }
1527
- const match = input.match(PackageVersion.lineMatcher);
1528
- if (!match) {
1529
- throw new Error(`Could not parse version from input: ${input}`);
1530
- }
1531
- return PackageVersion.fromMatch(match, description);
1532
- }
1533
- static equals(a, b, checkPrerelease = false) {
1534
- if (a.major !== b.major || a.minor !== b.minor || a.patch !== b.patch) {
1535
- return false;
1536
- }
1537
- if (checkPrerelease === false) {
1538
- return true;
1539
- }
1540
- if (a.preRelease === b.preRelease) {
1541
- return true;
1542
- }
1543
- if (a.preRelease === undefined || b.preRelease === undefined) {
1544
- return false;
1545
- }
1546
- return a.preRelease.type === b.preRelease.type && a.preRelease.version === b.preRelease.version;
1547
- }
1548
- static fromMatch([, major, , minor = "0", , patch = "0", , build, , preReleaseType, preReleaseNumber], description) {
1549
- let preRelease = undefined;
1550
- let buildNumber = 100;
1551
- if (preReleaseType && preReleaseNumber) {
1552
- preRelease = {
1553
- type: preReleaseType,
1554
- version: parseInt(preReleaseNumber)
1555
- };
1556
- }
1557
- if (build) {
1558
- buildNumber = Number(build);
1559
- } else if (description) {
1560
- const descriptionMatch = description.match(/(\d+)\)$/);
1561
- if (descriptionMatch) {
1562
- buildNumber = parseInt(descriptionMatch[1]);
1563
- }
1564
- }
1565
- return new PackageVersion(parseInt(major), parseInt(minor), parseInt(patch), preRelease, buildNumber);
1566
- }
1567
- static sort(a, b, ascending = true) {
1568
- const createSortResult = (a, b)=>ascending ? a - b : b - a;
1569
- if (a.major !== b.major) {
1570
- return createSortResult(a.major, b.major);
1571
- }
1572
- if (a.minor !== b.minor) {
1573
- return createSortResult(a.minor, b.minor);
1574
- }
1575
- if (a.patch !== b.patch) {
1576
- return createSortResult(a.patch, b.patch);
1577
- }
1578
- return createSortResult(a.preRelease ? a.preRelease.version : 0, b.preRelease ? b.preRelease.version : 0);
1579
- }
1580
- static toNumber(version) {
1581
- return ((version.major * 1000 + version.minor) * 1000 + version.patch) * 1000 + version.buildNumber;
1582
- }
1583
- constructor(major, minor, patch, preRelease, buildNumber){
1584
- this.major = major;
1585
- this.minor = minor;
1586
- this.patch = patch;
1587
- this.preRelease = preRelease;
1588
- this.buildNumber = buildNumber;
1589
- }
1590
- isPreRelease() {
1591
- return this.preRelease !== undefined;
1592
- }
1593
- clone() {
1594
- return new PackageVersion(this.major, this.minor, this.patch, this.preRelease ? {
1595
- ...this.preRelease
1596
- } : undefined, this.buildNumber);
1597
- }
1598
- incrementMajor() {
1599
- this.preRelease = undefined;
1600
- this.patch = 0;
1601
- this.minor = 0;
1602
- this.major++;
1603
- }
1604
- incrementMinor() {
1605
- this.preRelease = undefined;
1606
- this.patch = 0;
1607
- this.minor++;
1608
- }
1609
- incrementPatch() {
1610
- this.preRelease = undefined;
1611
- this.patch++;
1612
- }
1613
- createPreRelease(type) {
1614
- if (!this.preRelease) {
1615
- this.buildNumber = 1;
1616
- } else {
1617
- this.buildNumber++;
1618
- }
1619
- if (this.preRelease && type === this.preRelease.type) {
1620
- this.preRelease.version++;
1621
- return;
1622
- }
1623
- this.preRelease = {
1624
- version: 0,
1625
- type
1626
- };
1627
- }
1628
- createRelease() {
1629
- this.preRelease = undefined;
1630
- this.buildNumber = 100;
1631
- }
1632
- toVersionString({ buildNumber } = {}) {
1633
- let version = [
1634
- this.major,
1635
- this.minor,
1636
- this.patch
1637
- ].join(".");
1638
- if (buildNumber) {
1639
- version += "." + this.buildNumber;
1640
- }
1641
- if (this.preRelease) {
1642
- version += `-${this.preRelease.type}.${this.preRelease.version}`;
1643
- }
1644
- return version;
1645
- }
1646
- toDescriptionString(packageName) {
1647
- const base = [
1648
- this.major,
1649
- this.minor,
1650
- this.patch
1651
- ].join(".");
1652
- const parts = [
1653
- packageName,
1654
- base
1655
- ];
1656
- if (this.preRelease) {
1657
- parts.push(upperCaseFirst(this.preRelease.type));
1658
- parts.push(this.preRelease.version);
1659
- }
1660
- parts.push(`(${base}.${this.buildNumber})`);
1661
- return parts.join(" ");
1662
- }
1663
- /**
1664
- * Determines wether the version is lesser than the input version
1665
- *
1666
- * @param {PackageVersion} version
1667
- * @returns
1668
- */ isLesserThan(version) {
1669
- return PackageVersion.toNumber(this) < PackageVersion.toNumber(version);
1670
- }
1671
- /**
1672
- * Determines wether the version is greater than the input version
1673
- *
1674
- * @param {PackageVersion} version
1675
- * @returns
1676
- */ isGreaterThan(version) {
1677
- return PackageVersion.toNumber(this) > PackageVersion.toNumber(version);
1678
- }
1679
- }
1680
- const upperCaseFirst = (input)=>{
1681
- return input.slice(0, 1).toUpperCase() + input.slice(1);
1682
- };
1683
-
1684
- const parseVersionFromString = (input)=>{
1685
- if (input === undefined) {
1686
- throw new Error(`Can not parse version from undefined`);
1687
- }
1688
- let match;
1689
- let major;
1690
- let minor;
1691
- let patch;
1692
- let build;
1693
- let preReleaseType;
1694
- let preReleaseNumber;
1695
- if (// first try to find a full match with build number
1696
- (match = input.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)(-([^\.]+)\.(\d+))?/)) !== null) {
1697
- [, major, minor, patch, build, preReleaseType, preReleaseNumber] = match;
1698
- } else if ((match = input.match(/(\d+)\.(\d+)\.(\d+)(-([^\.]+)\.(\d+))?/)) !== null) {
1699
- [, major, minor, patch, , preReleaseType, preReleaseNumber] = match;
1700
- }
1701
- if (match === null) {
1702
- throw new Error(`Could not parse version from input: ${input}`);
1703
- }
1704
- let preRelease = undefined;
1705
- let buildNumber = 100;
1706
- if (preReleaseType && preReleaseNumber) {
1707
- preRelease = {
1708
- type: preReleaseType,
1709
- version: parseInt(preReleaseNumber)
1710
- };
1711
- }
1712
- if (build) {
1713
- buildNumber = Number(build);
1714
- } else if (input) {
1715
- const descriptionMatch = input.match(/(\d+)\)$/);
1716
- if (descriptionMatch) {
1717
- buildNumber = parseInt(descriptionMatch[1]);
1718
- }
1719
- }
1720
- return new PackageVersion(parseInt(major), parseInt(minor), parseInt(patch), preRelease, buildNumber);
1721
- };
1722
- // 1000001001 -> 1.0.1.1
1723
- // 1002017001 -> 1.2.17.1
1724
- const parseVersionFromNumericVersion = (version)=>{
1725
- const major = Math.floor(version / 1000000000);
1726
- const minor = Math.floor(version % 1000000000 / 1000000);
1727
- const patch = Math.floor(version % 1000000 / 1000);
1728
- const buildNumber = version % 1000;
1729
- return new PackageVersion(major, minor, patch, undefined, buildNumber);
1730
- };
1731
-
1732
- // https://regex101.com/r/LtGAu5/1
1733
- const logRegex = /console\.log\(\s*"([\w\s\.\(\)]+)\ *Copyright[\w\s\(\)\.]+(\d{4}|\d{4} - \d{4})([\w\s\(\)\.]+)?",?\s*\)/i;
1734
- const currentYear = new Date(Date.now()).getFullYear();
1735
- const getVersionFileHandler = (location)=>{
1736
- const filePath = path.join(location.scriptsDir, "Version.ts");
1737
- const invalidVersionFile = (versionFile)=>({
1738
- version: undefined,
1739
- write: (name, newVersion)=>{
1740
- const scriptsContent = fs.readdirSync(location.scriptsDir);
1741
- const tsFiles = scriptsContent.filter((file)=>file.endsWith(".ts"));
1742
- if (tsFiles.length > 0) {
1743
- return createVersionFileWriter([
1744
- currentYear
1745
- ], "")(name, newVersion);
1746
- }
1747
- },
1748
- reset: ()=>{
1749
- if (versionFile !== undefined) {
1750
- fs.writeFileSync(filePath, versionFile, {
1751
- encoding: "utf8"
1752
- });
1753
- } else {
1754
- try {
1755
- fs.rmSync(filePath);
1756
- } catch (err) {
1757
- if (!isErrorENOENT(err)) {
1758
- throw err;
1759
- }
1760
- }
1761
- }
1762
- }
1763
- });
1764
- const createVersionFileWriter = (copyright = [
1765
- currentYear
1766
- ], copyrightStuff = "")=>(name, newVersion)=>{
1767
- const descriptionText = newVersion.toDescriptionString(name);
1768
- const copyrightText = createYearString(copyright);
1769
- const result = `console.log("${descriptionText}. Copyright (C) ${copyrightText}${copyrightStuff}");`;
1770
- fs.writeFileSync(filePath, result, {
1771
- encoding: "utf-8"
1772
- });
1773
- };
1774
- let rawVersionFile = readStringFromFileOrUndefined(filePath);
1775
- if (rawVersionFile === undefined) {
1776
- return invalidVersionFile(rawVersionFile);
1777
- }
1778
- const versionFile = rawVersionFile.replace(/\n/g, "");
1779
- const match = versionFile.match(logRegex);
1780
- if (!match) {
1781
- return invalidVersionFile(versionFile);
1782
- }
1783
- const [_full, _description, copyright, copyrightStuff] = match;
1784
- const copyrightYears = copyright.match(/^(\d+)( ?- ?(\d+))?$/);
1785
- let years;
1786
- if (copyrightYears === null) {
1787
- years = [
1788
- currentYear
1789
- ];
1790
- } else {
1791
- years = [
1792
- Number(copyrightYears[1]),
1793
- currentYear
1794
- ];
1795
- }
1796
- return {
1797
- write: createVersionFileWriter(years, copyrightStuff),
1798
- reset: ()=>{
1799
- fs.writeFileSync(filePath, versionFile, {
1800
- encoding: "utf8"
1801
- });
1802
- }
1803
- };
1804
- };
1805
- const createYearString = (years)=>{
1806
- if (years[1] === undefined || years[0] === years[1]) {
1807
- return years[0].toString();
1808
- }
1809
- return `${years[0]} - ${years[1]}`;
1810
- };
1811
-
1812
- const buildArchiveFromPublishedPackage = (location, manifest, creatorPackage)=>{
1813
- const archive = new JSZip();
1814
- archive.file(PACKAGE_FILE, JSON.stringify(creatorPackage, null, 2));
1815
- const index = readPublishedPackageCreatorIndex(location);
1816
- if (index !== undefined) {
1817
- archive.file(INDEX_FILE, JSON.stringify(index, null, 2));
1818
- }
1819
- archive.file(manifest.main, fs.createReadStream(path.join(location.path, manifest.main)));
1820
- if (creatorPackage.Package === "IG.GFX.Standard") {
1821
- const source = path.join(location.path, "Images");
1822
- if (fs.existsSync(source)) {
1823
- const images = fs.readdirSync(source);
1824
- for (const file of images){
1825
- const { ext } = path.parse(file);
1826
- switch(ext){
1827
- case ".png":
1828
- case ".jpeg":
1829
- case ".jpg":
1830
- break;
1831
- default:
1832
- continue;
1833
- }
1834
- archive.file(file, fs.createReadStream(path.join(source, file)));
1835
- }
1836
- }
1837
- }
1838
- return archive;
1839
- };
1840
- const runtimeScripts = [
1841
- "Interactor",
1842
- "Core",
1843
- "Mixed"
1844
- ];
1845
- const notRuntimeScripts = [
1846
- "Context",
1847
- "Evaluator"
1848
- ];
1849
- const buildArchiveFromPackage = async (packageLocation, data, binDir, minified = true)=>{
1850
- const { domain } = parseCreatorPackageName(data);
1851
- const logStep = (step)=>logPackageMessage(data.Package, step);
1852
- const scriptDirectories = [
1853
- packageLocation.path,
1854
- packageLocation.scriptsDir
1855
- ];
1856
- if (data.Package === "IG.GFX.Standard") {
1857
- logStep(`Including Images folder`);
1858
- scriptDirectories.push(path.join(packageLocation.path, "Images"));
1859
- }
1860
- const manifest = readPackageCreatorManifest(packageLocation);
1861
- if (manifest !== undefined) {
1862
- if (manifest.RunTime && notRuntimeScripts.includes(manifest.Type)) {
1863
- logStep("Setting script RunTime to false because of script type");
1864
- writePackageCreatorManifest(packageLocation, {
1865
- ...manifest,
1866
- RunTime: false
1867
- });
1868
- } else if (!manifest.RunTime && runtimeScripts.includes(manifest.Type)) {
1869
- logStep("Setting script RunTime to true because of script type");
1870
- writePackageCreatorManifest(packageLocation, {
1871
- ...manifest,
1872
- RunTime: true
1873
- });
1874
- }
1875
- }
1876
- let libFile;
1877
- try {
1878
- const libFilePath = minified ? path.join(binDir, `${data.Package}.min.js`) : path.join(binDir, `${data.Package}.js`);
1879
- libFile = fs.readFileSync(libFilePath, {
1880
- encoding: "utf8"
1881
- });
1882
- } catch (err) {
1883
- if (!isErrorENOENT(err)) {
1884
- throw err;
1885
- }
1886
- }
1887
- const archive = new JSZip();
1888
- let library = "";
1889
- if (libFile) {
1890
- library = libFile;
1891
- }
1892
- if (!library) {
1893
- const date = new Date(Date.now());
1894
- library = `/* This file is part of the ${domain} Data Packages.
1895
- * Copyright (C) ${date.getFullYear()} intelligentgraphics. All Rights Reserved. */`;
1896
- }
1897
- archive.file(`${data.Package}.js`, library);
1898
- archive.file(PACKAGE_FILE, JSON.stringify(data, null, 2));
1899
- const creatorIndex = readPackageCreatorIndex(packageLocation);
1900
- if (creatorIndex !== undefined) {
1901
- archive.file(INDEX_FILE, JSON.stringify(creatorIndex, null, 2));
1902
- }
1903
- for (const directory of scriptDirectories){
1904
- try {
1905
- for (const file of fs.readdirSync(directory)){
1906
- const { ext } = path.parse(file);
1907
- switch(ext){
1908
- case ".png":
1909
- case ".jpeg":
1910
- case ".jpg":
1911
- break;
1912
- default:
1913
- continue;
1914
- }
1915
- archive.file(file, fs.createReadStream(path.join(directory, file)));
1916
- }
1917
- } catch (err) {
1918
- console.error(`Script directory "${directory}" does not exist`);
1919
- }
1920
- }
1921
- return archive;
1922
- };
1923
-
1924
- const execAsync = promisify(exec);
1925
- const releaseFolder = async (options)=>{
1926
- const workspace = options.workspace;
1927
- const location = options.directory;
1928
- const { write: writeVersionFile, reset: resetVersionFile } = getVersionFileHandler(location);
1929
- const packageDescription = readPackageCreatorManifest(location);
1930
- const fullPackageName = packageDescription.Package;
1931
- const { domain, subdomain } = parseCreatorPackageName(packageDescription);
1932
- const publishDomain = options.domain ?? domain;
1933
- const publishSubdomain = options.subdomain ?? subdomain;
1934
- const sharedPackageJson = readWorkspaceNpmManifest(workspace);
1935
- let newVersion;
1936
- try {
1937
- newVersion = parseVersionFromString(options.newVersion);
1938
- } catch (err) {
1939
- throw new Error(`Please enter a version in this format 1.0.0.100`);
1940
- }
1941
- packageDescription.Version = newVersion.toVersionString({
1942
- buildNumber: true
1943
- });
1944
- writePackageCreatorManifest(location, packageDescription);
1945
- if (newVersion.buildNumber < 100) {
1946
- newVersion.preRelease = {
1947
- type: "beta",
1948
- version: newVersion.buildNumber
1949
- };
1950
- } else if (newVersion.buildNumber > 100) {
1951
- newVersion.preRelease = {
1952
- type: "patch",
1953
- version: newVersion.buildNumber - 100
1954
- };
1955
- }
1956
- if (sharedPackageJson !== undefined) {
1957
- logPackageMessage(packageDescription.Package, `Running npm install to make sure all dependencies are up to date`);
1958
- await execAsync(`npm install`, {
1959
- encoding: "utf-8",
1960
- cwd: workspace.path
1961
- });
1962
- }
1963
- const binDir = options.outDir ?? getWorkspaceOutputPath(workspace);
1964
- await fs$1.mkdir(binDir, {
1965
- recursive: true
1966
- });
1967
- let assetServerPackageDetails;
1968
- let packageNameWithVersion;
1969
- {
1970
- const versionWithoutPrelease = newVersion.clone();
1971
- versionWithoutPrelease.preRelease = undefined;
1972
- const newVersionString = versionWithoutPrelease.toVersionString({
1973
- buildNumber: true
1974
- });
1975
- packageNameWithVersion = `${packageDescription.Package}_${newVersionString}`;
1976
- assetServerPackageDetails = {
1977
- name: packageDescription.Package,
1978
- version: newVersionString
1979
- };
1980
- }
1981
- let zipFilePath = path.join(binDir, packageNameWithVersion + ".zip");
1982
- let uploadable = {
1983
- getStream: ()=>createReadStream(zipFilePath)
1984
- };
1985
- try {
1986
- if (options.pushOnly) {
1987
- const zipFileExists = await fs$1.stat(zipFilePath).catch((err)=>{
1988
- if (isErrorENOENT(err)) {
1989
- return false;
1990
- }
1991
- return Promise.reject(err);
1992
- });
1993
- if (zipFileExists) {
1994
- throw new Error(`Expected a zip file to exist at path ${zipFilePath} since pushOnly is specified`);
1995
- }
1996
- } else {
1997
- const gitVersionInformation = await getVersionInformationFromGit(workspace, location);
1998
- writeVersionFile(fullPackageName, newVersion);
1999
- const bannerText = sharedPackageJson !== undefined ? getWorkspaceBannerText(sharedPackageJson) : undefined;
2000
- await buildFolders({
2001
- ...options,
2002
- packages: [
2003
- location
2004
- ],
2005
- banner: options.banner ? {
2006
- text: bannerText,
2007
- commit: gitVersionInformation.commit,
2008
- commitDirty: gitVersionInformation.dirty,
2009
- version: newVersion.toVersionString({
2010
- buildNumber: true
2011
- }),
2012
- date: new Date(Date.now())
2013
- } : undefined
2014
- });
2015
- newVersion.preRelease = undefined;
2016
- try {
2017
- await fs$1.rm(zipFilePath);
2018
- } catch (err) {
2019
- if (!isErrorENOENT(err)) {
2020
- throw err;
2021
- }
2022
- }
2023
- if (readPackageAnimationList(location).length > 0) {
2024
- var _workspaceManifest_dependencies;
2025
- const workspaceManifest = readWorkspaceNpmManifest(workspace);
2026
- if (!((_workspaceManifest_dependencies = workspaceManifest.dependencies) == null ? void 0 : _workspaceManifest_dependencies["@intelligentgraphics/3d.ig.gfx.standard"])) {
2027
- const install = await options.prompter.confirm(`The IG.GFX.Standard package should be added as a dependency to provide the 'AnimationInteractor' used to display animations. Do you wish to add it now?`);
2028
- if (install) {
2029
- await execAsync(`npm install @intelligentgraphics/3d.ig.gfx.standard`, {
2030
- encoding: "utf-8",
2031
- cwd: workspace.path
2032
- });
2033
- await execAsync(`npm run postinstall`, {
2034
- cwd: workspace.path
2035
- });
2036
- }
2037
- }
2038
- }
2039
- logPackageMessage(packageDescription.Package, `Creating zip file`);
2040
- const archive = await buildArchiveFromPackage(location, packageDescription, binDir, options.minimize);
2041
- try {
2042
- const zipOutputStream = createWriteStream(zipFilePath);
2043
- await pipeline(archive.generateNodeStream(), zipOutputStream);
2044
- } catch (err) {
2045
- if (isErrorEACCES(err) || isErrorEPERM(err)) {
2046
- logPackageMessage(packageDescription.Package, `Could not create zip file in the bin directory because of a permissions error. Only using it in-memory`);
2047
- uploadable = {
2048
- getStream: ()=>archive.generateNodeStream()
2049
- };
2050
- } else {
2051
- throw err;
2052
- }
2053
- }
2054
- }
2055
- if (!options.noUpload) {
2056
- if (!options.authentication) {
2057
- throw new Error(`Expected authentication to be available`);
2058
- }
2059
- logPackageMessage(packageDescription.Package, `Opening connection to IG.Asset.Server`);
2060
- const sessionManager = await createSessionManager({
2061
- url: options.service,
2062
- address: options.address,
2063
- domain: publishDomain,
2064
- subDomain: publishSubdomain,
2065
- authentication: options.authentication
2066
- });
2067
- try {
2068
- if (!options.skipDependencies) {
2069
- await ensureRequiredVersions(workspace, packageDescription, sessionManager, options.prompter);
2070
- }
2071
- logPackageMessage(packageDescription.Package, `Uploading package to ${publishDomain}.${publishSubdomain}`);
2072
- await uploadPackageFromStream(sessionManager.getTargetSession(), assetServerPackageDetails, uploadable.getStream());
2073
- } finally{
2074
- await sessionManager.destroy().catch((err)=>{
2075
- logPackageMessage(packageDescription.Package, `Failed to close IG.Asset.Server session(s): ${err}`);
2076
- });
2077
- }
2078
- }
2079
- } catch (err) {
2080
- resetVersionFile();
2081
- throw err;
2082
- }
2083
- if (newVersion.buildNumber >= 100 && !options.pushOnly) {
2084
- logPackageMessage(fullPackageName, "Copying zip to releases folder");
2085
- const zipFileName = `${packageNameWithVersion}.zip`;
2086
- const releasesPath = getPackageReleasesDirectory(location);
2087
- await fs$1.mkdir(releasesPath, {
2088
- recursive: true
2089
- });
2090
- await pipeline(uploadable.getStream(), createWriteStream(path.join(releasesPath, zipFileName)));
2091
- }
2092
- };
2093
- const ensureRequiredVersions = async (workspaceLocation, creatorPackage, sessionManager, prompter)=>{
2094
- const libraries = determineWorkspaceIGLibraries(workspaceLocation);
2095
- // If there are no libraries, we don't need to check for required versions
2096
- if (libraries.length === 0) {
2097
- return true;
2098
- }
2099
- const targetSession = sessionManager.getTargetSession();
2100
- const rawUploadedPackages = await getExistingPackages(targetSession);
2101
- const uploadedPackages = rawUploadedPackages.map((entry)=>{
2102
- let version;
2103
- try {
2104
- version = parseVersionFromNumericVersion(entry.numericVersion);
2105
- } catch (err) {
2106
- throw new Error(`Encountered invalid format for version ${entry.numericVersion}`);
2107
- }
2108
- if (version.buildNumber < 100) {
2109
- version.preRelease = {
2110
- type: "beta",
2111
- version: version.buildNumber
2112
- };
2113
- } else if (version.buildNumber > 100) {
2114
- version.preRelease = {
2115
- type: "patch",
2116
- version: version.buildNumber - 100
2117
- };
2118
- }
2119
- return {
2120
- ...entry,
2121
- version
2122
- };
2123
- });
2124
- for (const libraryLocation of libraries){
2125
- const libraryManifest = readPublishedPackageNpmManifest(libraryLocation);
2126
- const libraryCreatorPackage = readPublishedPackageCreatorManifest(libraryLocation);
2127
- if (libraryCreatorPackage === undefined || libraryManifest.main === undefined || libraryCreatorPackage.Package === creatorPackage.Package) {
2128
- continue;
2129
- }
2130
- const libraryVersion = PackageVersion.extractFromLine(libraryManifest.version);
2131
- if (libraryVersion.preRelease) {
2132
- libraryVersion.buildNumber = libraryVersion.preRelease.version;
2133
- libraryVersion.preRelease = undefined;
2134
- } else {
2135
- libraryVersion.buildNumber = 100;
2136
- }
2137
- let uploadedPackageInBasics;
2138
- let uploadedPackageInTarget;
2139
- for (const uploadedPackage of uploadedPackages){
2140
- if (uploadedPackage.scope === libraryCreatorPackage.Package) {
2141
- if (uploadedPackage.support) {
2142
- uploadedPackageInBasics = uploadedPackage;
2143
- } else {
2144
- uploadedPackageInTarget = uploadedPackage;
2145
- }
2146
- }
2147
- }
2148
- const validInBasics = uploadedPackageInBasics !== undefined && !uploadedPackageInBasics.version.isLesserThan(libraryVersion);
2149
- const validInTarget = uploadedPackageInTarget !== undefined && !uploadedPackageInTarget.version.isLesserThan(libraryVersion);
2150
- if (validInBasics || validInTarget) {
2151
- if (targetSession.subDomain !== "Basics" && uploadedPackageInBasics !== undefined && uploadedPackageInTarget !== undefined) {
2152
- logPackageMessage(creatorPackage.Package, `Package ${libraryCreatorPackage.Package} is uploaded both for Basics and ${targetSession.subDomain}. The package within ${targetSession.subDomain} will be used.`);
2153
- }
2154
- continue;
2155
- }
2156
- const possibleTargets = [];
2157
- if (uploadedPackageInBasics) {
2158
- const version = uploadedPackageInBasics.version.toVersionString({
2159
- buildNumber: true
2160
- });
2161
- possibleTargets.push({
2162
- value: "Basics",
2163
- name: `Basics (Current: ${version})`
2164
- });
2165
- } else {
2166
- possibleTargets.push({
2167
- value: "Basics",
2168
- name: "Basics (Current: None)"
2169
- });
2170
- }
2171
- if (targetSession.subDomain !== "Basics") {
2172
- if (uploadedPackageInTarget) {
2173
- const version = uploadedPackageInTarget.version.toVersionString({
2174
- buildNumber: true
2175
- });
2176
- possibleTargets.push({
2177
- value: targetSession.subDomain,
2178
- name: `${targetSession.subDomain} (Current: ${version})`
2179
- });
2180
- } else {
2181
- possibleTargets.push({
2182
- value: targetSession.subDomain,
2183
- name: `${targetSession.subDomain} (Current: None)`
2184
- });
2185
- }
2186
- }
2187
- const libraryVersionString = libraryVersion.toVersionString({
2188
- buildNumber: true
2189
- });
2190
- const uploadTargetScope = await prompter.ask({
2191
- message: `Version ${libraryVersionString} of dependency ${libraryCreatorPackage.Package} is required but not available. Please select a subdomain to upload the correct dependency version to`,
2192
- options: [
2193
- ...possibleTargets,
2194
- {
2195
- name: "Skip upload",
2196
- value: "Skip"
2197
- }
2198
- ],
2199
- default: possibleTargets[0].value
2200
- });
2201
- if (uploadTargetScope === "Skip") {
2202
- continue;
2203
- }
2204
- const archive = buildArchiveFromPublishedPackage(libraryLocation, libraryManifest, libraryCreatorPackage);
2205
- const newVersionString = libraryVersion.toVersionString({
2206
- buildNumber: true
2207
- });
2208
- const session = uploadTargetScope === "Basics" ? await sessionManager.getBasicsSession() : targetSession;
2209
- logPackageMessage(creatorPackage.Package, `Uploading package ${libraryCreatorPackage.Package} with version ${newVersionString} to ${session.domain}.${session.subDomain}`);
2210
- await uploadPackageFromStream(session, {
2211
- name: libraryCreatorPackage.Package,
2212
- version: newVersionString
2213
- }, archive.generateNodeStream());
2214
- }
2215
- };
2216
- const createSessionManager = async (params)=>{
2217
- const targetSession = await startSession(params);
2218
- let basicsSession;
2219
- return {
2220
- getBasicsSession: async ()=>{
2221
- if (targetSession.subDomain === "Basics") {
2222
- return targetSession;
2223
- }
2224
- if (basicsSession === undefined) {
2225
- basicsSession = await startSession({
2226
- ...params,
2227
- subDomain: "Basics"
2228
- });
2229
- }
2230
- return basicsSession;
2231
- },
2232
- getTargetSession: ()=>targetSession,
2233
- destroy: async ()=>{
2234
- await closeSession(targetSession);
2235
- if (basicsSession !== undefined) {
2236
- await closeSession(basicsSession);
2237
- }
2238
- }
2239
- };
2240
- };
2241
-
2242
- /**
2243
- * Extracts and returns script array for _Index.json from a src folder
2244
- *
2245
- * @param folderPath path to a src folder
2246
- */ function generateIndex({ location, ignore = [], strictOptional = false }) {
2247
- const files = getPackageTypescriptFiles(location);
2248
- const filtered = files.filter((path)=>{
2249
- return !ignore.some((suffix)=>path.endsWith(suffix));
2250
- });
2251
- const arr = [];
2252
- const existingIndex = readPackageCreatorIndex(location) ?? [];
2253
- const program = ts.createProgram(filtered, {
2254
- allowJs: true
2255
- });
2256
- const typeChecker = program.getTypeChecker();
2257
- filtered.forEach((file)=>{
2258
- // Create a Program to represent the project, then pull out the
2259
- // source file to parse its AST.
2260
- const sourceFile = program.getSourceFile(file);
2261
- // Loop through the root AST nodes of the file
2262
- ts.forEachChild(sourceFile, (node)=>{
2263
- for (const scriptingClass of findScriptingClasses(node)){
2264
- if (scriptingClass.node.name === undefined) {
2265
- throw new Error(`Expected ${scriptingClass.type} class to have a name`);
2266
- }
2267
- const name = typeChecker.getFullyQualifiedName(typeChecker.getSymbolAtLocation(scriptingClass.node.name));
2268
- if (name.length > 45) {
2269
- throw new Error(`Package name length >45 '${name}'`);
2270
- }
2271
- const parameterDeclaration = getScriptingClassParameterdeclaration(scriptingClass);
2272
- const parametersType = parameterDeclaration === undefined ? undefined : typeChecker.getTypeAtLocation(parameterDeclaration);
2273
- if (parametersType === undefined) {
2274
- console.log(`Failed to find parameters type declaration for ${scriptingClass.type} ${name}. Skipping parameter list generation`);
2275
- }
2276
- const existingIndexEntry = existingIndex.find((entry)=>entry.Name === name);
2277
- const obj = {
2278
- Name: name,
2279
- Description: (existingIndexEntry == null ? void 0 : existingIndexEntry.Description) ?? name,
2280
- Type: scriptingClass.type === "evaluator" ? "Evaluator" : "Interactor",
2281
- Parameters: []
2282
- };
2283
- const rawDocTags = ts.getJSDocTags(scriptingClass.node);
2284
- const dict = getTagDict(rawDocTags);
2285
- if (dict.summary) {
2286
- obj.Description = dict.summary;
2287
- } else {
2288
- const comment = typeChecker.getTypeAtLocation(scriptingClass.node).symbol.getDocumentationComment(typeChecker).map((comment)=>comment.text).join(" ");
2289
- if (comment) {
2290
- obj.Description = comment;
2291
- }
2292
- }
2293
- if (parametersType !== undefined) {
2294
- obj.Parameters = parseParametersList(typeChecker.getPropertiesOfType(parametersType), strictOptional);
2295
- if (obj.Parameters.length === 0 && parametersType.getStringIndexType() !== undefined) {
2296
- obj.Parameters = (existingIndexEntry == null ? void 0 : existingIndexEntry.Parameters) ?? [];
2297
- }
2298
- } else if (existingIndexEntry !== undefined) {
2299
- obj.Parameters = existingIndexEntry.Parameters;
2300
- }
2301
- arr.push(obj);
2302
- }
2303
- });
2304
- });
2305
- arr.sort((a, b)=>a.Name.localeCompare(b.Name));
2306
- writePackageCreatorIndex(location, arr);
2307
- }
2308
- function capitalizeFirstLetter(string) {
2309
- return (string == null ? void 0 : string.charAt(0).toUpperCase()) + (string == null ? void 0 : string.slice(1));
2310
- }
2311
- const parseDefault = (value, type)=>{
2312
- const uType = capitalizeFirstLetter(type);
2313
- if (value === "null") return null;
2314
- switch(uType){
2315
- case "LengthM":
2316
- case "ArcDEG":
2317
- case "Float":
2318
- return parseFloat(value);
2319
- case "Integer":
2320
- case "Int":
2321
- return parseInt(value);
2322
- case "Boolean":
2323
- case "Bool":
2324
- return value === "true";
2325
- case "Material":
2326
- case "String":
2327
- case "Geometry":
2328
- default:
2329
- return value.replace(/^"/, "").replace(/"$/, "");
2330
- }
2331
- };
2332
- const parseTypeFromName = (name)=>{
2333
- const parts = name.split(".");
2334
- const identifier = parts[parts.length - 1];
2335
- switch(identifier){
2336
- case "LengthM":
2337
- case "ArcDEG":
2338
- case "Float":
2339
- case "Integer":
2340
- return identifier;
2341
- case "GeometryReference":
2342
- return "Geometry";
2343
- case "MaterialReference":
2344
- return "Material";
2345
- case "AnimationReference":
2346
- return "Animation";
2347
- case "InteractorReference":
2348
- return "Interactor";
2349
- case "EvaluatorReference":
2350
- return "Evaluator";
2351
- case "String":
2352
- case "string":
2353
- return "String";
2354
- case "number":
2355
- case "Number":
2356
- return "Float";
2357
- case "boolean":
2358
- case "Boolean":
2359
- return "Boolean";
2360
- }
2361
- };
2362
- const parseParametersList = (properties, strictOptional)=>{
2363
- return properties.map((symbol, i)=>{
2364
- var _symbol_getDeclarations;
2365
- const parameter = {
2366
- Name: symbol.name,
2367
- Description: undefined,
2368
- Type: "String",
2369
- Default: undefined,
2370
- DisplayIndex: i + 1
2371
- };
2372
- if (parameter.Name.length > 45) {
2373
- throw new Error(`Parameter name length >45 '${parameter.Name}'`);
2374
- }
2375
- let declaration = (_symbol_getDeclarations = symbol.getDeclarations()) == null ? void 0 : _symbol_getDeclarations[0];
2376
- let documentationComment = symbol.getDocumentationComment(undefined);
2377
- let checkLinksSymbol = symbol;
2378
- while(checkLinksSymbol !== undefined && declaration === undefined){
2379
- const links = checkLinksSymbol.links;
2380
- if (links == null ? void 0 : links.syntheticOrigin) {
2381
- var _links_syntheticOrigin_getDeclarations;
2382
- declaration = (_links_syntheticOrigin_getDeclarations = links.syntheticOrigin.getDeclarations()) == null ? void 0 : _links_syntheticOrigin_getDeclarations[0];
2383
- if (documentationComment.length === 0) {
2384
- documentationComment = links.syntheticOrigin.getDocumentationComment(undefined);
2385
- }
2386
- checkLinksSymbol = links.syntheticOrigin;
2387
- }
2388
- }
2389
- if (declaration !== undefined) {
2390
- const rawDocTags = ts.getJSDocTags(declaration);
2391
- const dict = getTagDict(rawDocTags);
2392
- if (dict.summary) {
2393
- parameter.Description = dict.summary;
2394
- } else {
2395
- const comment = documentationComment.map((comment)=>comment.text).join(" ");
2396
- if (comment) {
2397
- parameter.Description = comment;
2398
- }
2399
- }
2400
- if (dict.creatorType) {
2401
- parameter.Type = dict.creatorType;
2402
- } else {
2403
- const propertySignature = declaration;
2404
- if (propertySignature.type !== undefined) {
2405
- const parsedType = parseTypeFromName(propertySignature.type.getText());
2406
- if (parsedType !== undefined) {
2407
- parameter.Type = parsedType;
2408
- }
2409
- }
2410
- }
2411
- if (dict.default) {
2412
- parameter.Default = parseDefault(dict.default, parameter.Type);
2413
- }
2414
- if (strictOptional && declaration.kind === ts.SyntaxKind.PropertySignature) {
2415
- const propertySignature = declaration;
2416
- if (propertySignature.questionToken === undefined) {
2417
- parameter.Required = true;
2418
- }
2419
- }
2420
- }
2421
- return parameter;
2422
- });
2423
- };
2424
- function getTagDict(tags) {
2425
- const dict = {};
2426
- for (const tag of tags){
2427
- dict[tag.tagName.text] = tag.comment;
2428
- }
2429
- return dict;
2430
- }
2431
- const getScriptingClassParameterdeclaration = (scriptingClass)=>{
2432
- for (const member of scriptingClass.node.members){
2433
- if (ts.isMethodDeclaration(member)) {
2434
- for(let index = 0; index < member.parameters.length; index++){
2435
- const parameter = member.parameters[index];
2436
- if (isScriptingClassParameterDeclaration(scriptingClass, member, index)) {
2437
- return parameter;
2438
- }
2439
- }
2440
- }
2441
- if (ts.isConstructorDeclaration(member)) {
2442
- for(let index = 0; index < member.parameters.length; index++){
2443
- const parameter = member.parameters[index];
2444
- if (isScriptingClassParameterDeclaration(scriptingClass, member, index)) {
2445
- return parameter;
2446
- }
2447
- }
2448
- }
2449
- }
2450
- };
2451
- const isScriptingClassParameterDeclaration = (scriptingClass, memberNode, parameterIndex)=>{
2452
- if (scriptingClass.type === "evaluator") {
2453
- var _memberNode_name;
2454
- return (memberNode == null ? void 0 : (_memberNode_name = memberNode.name) == null ? void 0 : _memberNode_name.getText()) == "Create" && parameterIndex === 2;
2455
- }
2456
- if (scriptingClass.type === "interactor") {
2457
- return memberNode.kind === ts.SyntaxKind.Constructor && parameterIndex === 0;
2458
- }
2459
- return false;
2460
- };
2461
- /**
2462
- * Finds interactors and evaluators within a script file
2463
- *
2464
- * @param {ts.Node} node
2465
- * @return {*}
2466
- */ const findScriptingClasses = (node)=>{
2467
- let body;
2468
- if (ts.isModuleDeclaration(node)) {
2469
- body = node.body;
2470
- }
2471
- if (body !== undefined && ts.isModuleDeclaration(body)) {
2472
- body = body.body;
2473
- }
2474
- const classes = [];
2475
- if (body !== undefined) {
2476
- ts.forEachChild(body, (child)=>{
2477
- if (!ts.isClassDeclaration(child)) {
2478
- return;
2479
- }
2480
- const scriptingClass = detectScriptingClass(child);
2481
- if (scriptingClass !== undefined) {
2482
- classes.push(scriptingClass);
2483
- }
2484
- });
2485
- }
2486
- return classes;
2487
- };
2488
- const detectScriptingClass = (node)=>{
2489
- var _node_heritageClauses, _node_heritageClauses1;
2490
- const isEvaluator = (_node_heritageClauses = node.heritageClauses) == null ? void 0 : _node_heritageClauses.some((clause)=>{
2491
- if (clause.token !== ts.SyntaxKind.ExtendsKeyword && clause.token !== ts.SyntaxKind.ImplementsKeyword) {
2492
- return false;
2493
- }
2494
- return clause.types.some((type)=>type.getText().includes("Evaluator"));
2495
- });
2496
- if (isEvaluator) {
2497
- return {
2498
- node,
2499
- type: "evaluator"
2500
- };
2501
- }
2502
- const isInteractor = (_node_heritageClauses1 = node.heritageClauses) == null ? void 0 : _node_heritageClauses1.some((clause)=>{
2503
- if (clause.token !== ts.SyntaxKind.ExtendsKeyword) {
2504
- return false;
2505
- }
2506
- return clause.types.some((type)=>type.getText().includes("Interactor"));
2507
- });
2508
- if (isInteractor) {
2509
- return {
2510
- node,
2511
- type: "interactor"
2512
- };
2513
- }
2514
- };
2515
-
2516
- export { buildFolders, buildFoldersWatch, generateIndex, releaseFolder };
10
+ import 'axios';
11
+ import 'typescript';
12
+ import 'typedoc';
13
+ import 'events';
14
+ import 'source-map-js';
15
+ import 'ajv';
16
+ import 'stream/promises';
17
+ import 'child_process';
18
+ import 'util';
19
+ import 'simple-git';
20
+ import 'jszip';
2517
21
  //# sourceMappingURL=lib.mjs.map