@classcad/client 0.0.0-stage → 3.0.0-beta.20261119090857

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 (108) hide show
  1. package/README.md +20 -2
  2. package/bin/buerli-classcad.cjs +23 -0
  3. package/build/cjs/BuerliCadFacade.js +718 -0
  4. package/build/cjs/cclass/utils/assembly.js +687 -0
  5. package/build/cjs/cclass/utils/base.js +136 -0
  6. package/build/cjs/cclass/utils/index.js +99 -0
  7. package/build/cjs/cclass/utils/part.js +153 -0
  8. package/build/cjs/classcadEngine.js +33 -0
  9. package/build/cjs/createApi.js +71 -0
  10. package/build/cjs/createUnwrappedApi.js +43 -0
  11. package/build/cjs/facade.js +103 -0
  12. package/build/cjs/globals.js +157 -0
  13. package/build/cjs/index.js +102 -0
  14. package/build/cjs/io/AwvNodeClient.js +290 -0
  15. package/build/cjs/io/SocketIOClient.js +339 -0
  16. package/build/cjs/io/Transaction.js +134 -0
  17. package/build/cjs/io/WASMClient.js +433 -0
  18. package/build/cjs/io/WSClient.js +646 -0
  19. package/build/cjs/io/engineKey.js +202 -0
  20. package/build/cjs/re-export.js +35 -0
  21. package/build/cjs/session/host.js +479 -0
  22. package/build/cjs/session/identity.js +38 -0
  23. package/build/cjs/session/selection.js +283 -0
  24. package/build/cjs/session/share.js +229 -0
  25. package/build/cjs/session/types.js +23 -0
  26. package/build/cjs/test/SocketIOClient.spec.js +178 -0
  27. package/build/cjs/types/ComClient.js +10 -0
  28. package/build/cjs/utils/createRecursiveBufferGeometry.js +55 -0
  29. package/build/cjs/utils/createRecursiveScene.js +140 -0
  30. package/build/cjs/utils/getDifferentColoredMeshesFromEntity.js +24 -0
  31. package/build/cjs/utils/index.js +20 -0
  32. package/build/cjs/utils/polyline.js +65 -0
  33. package/build/cjs/utils/waitForSelect.js +29 -0
  34. package/build/esm/BuerliCadFacade.js +714 -0
  35. package/build/esm/cclass/utils/assembly.js +665 -0
  36. package/build/esm/cclass/utils/base.js +127 -0
  37. package/build/esm/cclass/utils/index.js +62 -0
  38. package/build/esm/cclass/utils/part.js +144 -0
  39. package/build/esm/classcadEngine.js +30 -0
  40. package/build/esm/createApi.js +66 -0
  41. package/build/esm/createUnwrappedApi.js +39 -0
  42. package/build/esm/facade.js +98 -0
  43. package/build/esm/globals.js +150 -0
  44. package/build/esm/index.js +80 -0
  45. package/build/esm/io/AwvNodeClient.js +286 -0
  46. package/build/esm/io/SocketIOClient.js +332 -0
  47. package/build/esm/io/Transaction.js +130 -0
  48. package/build/esm/io/WASMClient.js +429 -0
  49. package/build/esm/io/WSClient.js +642 -0
  50. package/build/esm/io/engineKey.js +196 -0
  51. package/build/esm/re-export.js +3 -0
  52. package/build/esm/session/host.js +474 -0
  53. package/build/esm/session/identity.js +34 -0
  54. package/build/esm/session/selection.js +277 -0
  55. package/build/esm/session/share.js +221 -0
  56. package/build/esm/session/types.js +20 -0
  57. package/build/esm/test/SocketIOClient.spec.js +178 -0
  58. package/build/esm/types/ComClient.js +7 -0
  59. package/build/esm/utils/createRecursiveBufferGeometry.js +51 -0
  60. package/build/esm/utils/createRecursiveScene.js +136 -0
  61. package/build/esm/utils/getDifferentColoredMeshesFromEntity.js +20 -0
  62. package/build/esm/utils/index.js +4 -0
  63. package/build/esm/utils/polyline.js +60 -0
  64. package/build/esm/utils/waitForSelect.js +23 -0
  65. package/build/types/BuerliCadFacade.d.ts +410 -0
  66. package/build/types/cclass/utils/assembly.d.ts +180 -0
  67. package/build/types/cclass/utils/base.d.ts +55 -0
  68. package/build/types/cclass/utils/index.d.ts +46 -0
  69. package/build/types/cclass/utils/part.d.ts +46 -0
  70. package/build/types/classcadEngine.d.ts +40 -0
  71. package/build/types/createApi.d.ts +65 -0
  72. package/build/types/createUnwrappedApi.d.ts +36 -0
  73. package/build/types/facade.d.ts +9 -0
  74. package/build/types/globals.d.ts +79 -0
  75. package/build/types/index.d.ts +82 -0
  76. package/build/types/io/AwvNodeClient.d.ts +182 -0
  77. package/build/types/io/SocketIOClient.d.ts +84 -0
  78. package/build/types/io/Transaction.d.ts +56 -0
  79. package/build/types/io/WASMClient.d.ts +239 -0
  80. package/build/types/io/WSClient.d.ts +242 -0
  81. package/build/types/io/engineKey.d.ts +137 -0
  82. package/build/types/re-export.d.ts +6 -0
  83. package/build/types/session/host.d.ts +108 -0
  84. package/build/types/session/identity.d.ts +46 -0
  85. package/build/types/session/selection.d.ts +164 -0
  86. package/build/types/session/share.d.ts +131 -0
  87. package/build/types/session/types.d.ts +113 -0
  88. package/build/types/test/SocketIOClient.spec.d.ts +0 -0
  89. package/build/types/types/ComClient.d.ts +307 -0
  90. package/build/types/utils/createRecursiveBufferGeometry.d.ts +8 -0
  91. package/build/types/utils/createRecursiveScene.d.ts +24 -0
  92. package/build/types/utils/getDifferentColoredMeshesFromEntity.d.ts +14 -0
  93. package/build/types/utils/index.d.ts +4 -0
  94. package/build/types/utils/polyline.d.ts +43 -0
  95. package/build/types/utils/waitForSelect.d.ts +4 -0
  96. package/doc/api/advanced/connection.md +488 -0
  97. package/doc/api/clients.md +2045 -0
  98. package/doc/api/engine-keys.md +230 -0
  99. package/doc/api/index.md +58 -0
  100. package/doc/api/modeling.md +682 -0
  101. package/doc/api/other.md +33 -0
  102. package/doc/api/session-sharing.md +706 -0
  103. package/package.json +59 -4
  104. package/test/classcadEngine.test.cjs +44 -0
  105. package/test/connect.test.cjs +81 -0
  106. package/test/engineKey.test.cjs +80 -0
  107. package/test/onClient.test.cjs +82 -0
  108. package/typedoc.json +8 -0
@@ -0,0 +1,127 @@
1
+ import { getDrawing } from '@classcad/sdkjs';
2
+ import { CCClasses, classMap } from '../../re-export';
3
+ /**
4
+ * Checks if the given class is equal to the provided type or derives from it.
5
+ *
6
+ * @param objClass The class to check.
7
+ * @param type The type to be checked for.
8
+ * @returns true if objClass is of type or derived from type, false else.
9
+ */
10
+ export const isA = (objClass, type) => {
11
+ if (objClass && type) {
12
+ if (objClass === type) {
13
+ return true;
14
+ }
15
+ const clazz = classMap[objClass];
16
+ if (clazz && clazz.superClasses) {
17
+ return clazz.superClasses.includes(type);
18
+ }
19
+ }
20
+ return false;
21
+ };
22
+ /**
23
+ * Gets all children of the given object with the provided type.
24
+ *
25
+ * @param objId The id of the object to get children from.
26
+ * @param type The type of children to search for.
27
+ * @param tree The structure tree.
28
+ * @returns An array of object ids of the found children.
29
+ */
30
+ export const getChildren = (objId, type, tree) => {
31
+ var _a, _b;
32
+ return ((_b = (_a = tree[objId]) === null || _a === void 0 ? void 0 : _a.children) === null || _b === void 0 ? void 0 : _b.filter(c => isA(tree[c].class, type))) || [];
33
+ };
34
+ /**
35
+ * Searches for an object's ancestor of specified class.
36
+ * @param drawingId The drawing id.
37
+ * @param objectId The id of the object to search for its ancestor.
38
+ * @param parentClass The CCClass of the ancestor to search for.
39
+ * @returns first found object of specified class.
40
+ */
41
+ export const getAncestorIdByClass = (drawingId, objectId, parentClass) => {
42
+ var _a;
43
+ const tree = getDrawing(drawingId).structure.tree;
44
+ let object = tree[((_a = tree[objectId]) === null || _a === void 0 ? void 0 : _a.parent) || -1];
45
+ while (object && object.class !== parentClass) {
46
+ object = tree[object.parent || -1];
47
+ }
48
+ return (object === null || object === void 0 ? void 0 : object.id) || null;
49
+ };
50
+ /**
51
+ * Gets all ancestors of the given object.
52
+ * @param drawingId The drawing id.
53
+ * @param objectId The id of the object to get ancestors from.
54
+ * @returns an array of object's ancestors.
55
+ */
56
+ export const getAncestors = (drawingId, objectId) => {
57
+ var _a, _b;
58
+ const tree = getDrawing(drawingId).structure.tree;
59
+ let curId = (_a = tree[objectId]) === null || _a === void 0 ? void 0 : _a.parent;
60
+ const ancestors = [];
61
+ while (curId) {
62
+ ancestors.push(curId);
63
+ curId = (_b = tree[curId]) === null || _b === void 0 ? void 0 : _b.parent;
64
+ }
65
+ return ancestors;
66
+ };
67
+ /**
68
+ * Gets all descendants of the given object.
69
+ * @param drawingId The drawing id.
70
+ * @param objectId The id of the object to get descendants from.
71
+ * @returns an array of object's descendants.
72
+ */
73
+ export const getDescendants = (drawingId, objectId) => {
74
+ const object = getDrawing(drawingId).structure.tree[objectId];
75
+ const descendants = [];
76
+ (object === null || object === void 0 ? void 0 : object.children) &&
77
+ object.children.forEach(child => {
78
+ descendants.push(child, ...getDescendants(drawingId, child));
79
+ });
80
+ return descendants;
81
+ };
82
+ /**
83
+ * Find first object which can be identified by given identifier or name.
84
+ * If both optional parameters has been set, the identifier is treated with priority.
85
+ * If no object with given identifier will be found, the name is used to find an object, if available.
86
+ * @param drawingId The drawing id.
87
+ * @param options Optional parameters to identify to find object.
88
+ * @param options.ident Identifier to find the object by an identifier
89
+ * @param options.name Name to find the object by its name
90
+ * @returns first found object which meets the searching conditions
91
+ */
92
+ export const findObject = (drawingId, options) => {
93
+ const drw = getDrawing(drawingId);
94
+ const tree = drw.structure.tree;
95
+ if (!options.ident && !options.name) {
96
+ throw 'Neither an identifier nor a name has been set to find object';
97
+ }
98
+ if (options.ident) {
99
+ const instance = findObjectByIdent(drawingId, options.ident);
100
+ if (instance) {
101
+ return instance;
102
+ }
103
+ }
104
+ if (options.name) {
105
+ const result = drw.api.structure.findTree(tree, obj => obj.name === options.name);
106
+ return result ? result.id : undefined;
107
+ }
108
+ };
109
+ /**
110
+ * Helperfunction to find any object by identifier which
111
+ * can eventually be found in the ident map
112
+ *
113
+ * @param drawingId The drawing id.
114
+ * @param objectIdent Identification of the object to find
115
+ * @returns Id of the found object or undefined
116
+ */
117
+ const findObjectByIdent = (drawingId, objectIdent) => {
118
+ var _a;
119
+ const structure = getDrawing(drawingId).structure;
120
+ const [identMapId] = getChildren(structure.root, CCClasses.IdentToIdMap, structure.tree);
121
+ const identMap = identMapId && structure.tree[identMapId];
122
+ if (identMap) {
123
+ const map = (_a = identMap.members) === null || _a === void 0 ? void 0 : _a.map;
124
+ const keyValuePair = map.members.find(mem => mem.members[0].value === objectIdent);
125
+ return keyValuePair && keyValuePair.members[1].value;
126
+ }
127
+ };
@@ -0,0 +1,62 @@
1
+ import * as assembly from './assembly';
2
+ import * as base from './base';
3
+ import * as part from './part';
4
+ /**
5
+ * The message type (`'info'`, `'warning'`, `'error'`) for errors in the form older engines report them.
6
+ *
7
+ * @internal
8
+ */
9
+ export const getMessageTypeForErrors = (errors) => {
10
+ let maxErrorState = 0;
11
+ errors.map(e => {
12
+ maxErrorState = Math.max(maxErrorState, e.errorState);
13
+ });
14
+ switch (maxErrorState) {
15
+ case 0:
16
+ return 'info';
17
+ case 1:
18
+ return 'warning';
19
+ case 2:
20
+ return 'warning';
21
+ case 3:
22
+ return 'error';
23
+ default:
24
+ return 'info';
25
+ }
26
+ };
27
+ /**
28
+ * Helpers that look things up in a drawing's structure tree: classes, ancestors, work geometry, sketches, constraints.
29
+ *
30
+ * They read the tree in the buerli store; none of them calls the engine.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { ccUtils, ScgClassType } from '@classcad/client'
35
+ *
36
+ * // The part a picked solid belongs to, and that part's sketches
37
+ * const partId = ccUtils.base.getAncestorIdByClass(facade.drawingId, solidId, ScgClassType.CCPart)
38
+ * if (partId !== null) {
39
+ * const sketches = ccUtils.part.getSketch(facade.drawingId, partId)
40
+ * const tree = await facade.tree()
41
+ * console.log(tree[partId].name, sketches.map(id => tree[id].name))
42
+ * }
43
+ * ```
44
+ * @advanced
45
+ * @category Modeling
46
+ */
47
+ export const ccUtils = {
48
+ /**
49
+ * Class checks and tree walks: `isA` (a class or one derived from it), `getChildren`, `getAncestors`,
50
+ * `getAncestorIdByClass`, `getDescendants`, `findObject` (by identifier or name).
51
+ */
52
+ base,
53
+ /**
54
+ * Assemblies: `findProduct` (of an instance), `getInstance`, `getPartTemplate`, `getAssemblyTemplate`,
55
+ * `getTransformation`, `getMatePath`, `getWorkGeometry`, and the constraints (`getConstraint`,
56
+ * `getFastenedConstraint`, `getRevoluteConstraint`, …).
57
+ */
58
+ assembly,
59
+ /** Parts: `getWorkGeometry`, `getSketch`, `getSketchRegion`, `getSketchlines`. */
60
+ part,
61
+ };
62
+ export default ccUtils;
@@ -0,0 +1,144 @@
1
+ import { getDrawing, NOID } from '@classcad/sdkjs';
2
+ import { CCClasses } from '../../re-export';
3
+ import { findProduct } from './assembly';
4
+ import { getChildren, isA } from './base';
5
+ /**
6
+ * Helperfunction to get objects like work geometry or sketch regions from given product references
7
+ *
8
+ * @param drawingId The drawing id.
9
+ * @param refId Product reference to look for the object
10
+ * @param type Type of the object to look for
11
+ * @param objectName name of the object to look for (optional)
12
+ * @returns Array containing all the found objects. The array is empty if nothing was found
13
+ */
14
+ const getObjectsfromProdRef = (drawingId, refId, type, objectName) => {
15
+ const drw = getDrawing(drawingId);
16
+ const tree = drw.structure.tree;
17
+ const productId = findProduct(refId, tree) || NOID;
18
+ const product = tree[productId];
19
+ const result = [];
20
+ if (product) {
21
+ // This is an inner helper function to collect the objects of given type.
22
+ const collectObjIds = (setId, _type) => {
23
+ const allObjIds = getChildren(setId, _type, tree);
24
+ if (!objectName) {
25
+ return allObjIds;
26
+ }
27
+ else {
28
+ return allObjIds.filter(w => { var _a; return objectName === ((_a = tree[w]) === null || _a === void 0 ? void 0 : _a.name); });
29
+ }
30
+ };
31
+ if (isA(product.class, CCClasses.CCPart)) {
32
+ const geometrySetId = getChildren(productId, CCClasses.CCGeometrySet, tree).pop() || NOID;
33
+ result.push(...collectObjIds(geometrySetId, type));
34
+ const sketchSetId = getChildren(productId, CCClasses.CCSketchSet, tree).pop() || NOID;
35
+ result.push(...collectObjIds(sketchSetId, type));
36
+ }
37
+ else {
38
+ const allProdRefIds = getChildren(refId, CCClasses.CCProductReferenceET, tree);
39
+ for (const prodRefId of allProdRefIds) {
40
+ const prod = findProduct(prodRefId, tree);
41
+ if (prod) {
42
+ const geometrySetId = getChildren(productId, CCClasses.CCGeometrySet, tree).pop() || NOID;
43
+ result.push(...collectObjIds(geometrySetId, type));
44
+ const sketchSetId = getChildren(productId, CCClasses.CCSketchSet, tree).pop() || NOID;
45
+ result.push(...collectObjIds(sketchSetId, type));
46
+ }
47
+ }
48
+ }
49
+ }
50
+ return result;
51
+ };
52
+ /**
53
+ * @deprecated use getWorkGeometry() instead, getWorkCoordSystem() will be removed in a future release.
54
+ *
55
+ * Returns all workcoordsystems of given reference with specified name.
56
+ * If _wcsName_ is undefined, all workcoordsystems of given reference will be returned.
57
+ *
58
+ * @param drawingId The drawing id.
59
+ * @param refId The product reference to look for wcs.
60
+ * @param wcsName The name of wcs to look for.
61
+ * @returns An array of ids of all workcoordsystems found. The array is empty if nothing was found.
62
+ */
63
+ export const getWorkCoordSystem = (drawingId, refId, wcsName) => {
64
+ console.warn('getWorkCoordSystem() is deprecated and will be removed in a future release. Use getWorkGeometry() instead.');
65
+ return getObjectsfromProdRef(drawingId, refId, CCClasses.CCWorkCSys, wcsName);
66
+ };
67
+ /**
68
+ * Returns all work geometry of given type and given reference with specified name.
69
+ * If wgName is undefined, all work geometry of given reference will be returned.
70
+ *
71
+ * @param drawingId The drawing id.
72
+ * @param refId The product reference to look for work geometry.
73
+ * @param type The type of work geometry to look for
74
+ * @param wgName The name of work geometry to look for.
75
+ * @returns An array of ids of all found work geometry. The array is empty if nothing was found.
76
+ */
77
+ export const getWorkGeometry = (drawingId, refId, type, wgName) => {
78
+ return getObjectsfromProdRef(drawingId, refId, type, wgName);
79
+ };
80
+ /**
81
+ * Returns all sketch regions of given reference with specified name.
82
+ * If sketchRegionName is undefined, all sketch regions of given reference will be returned.
83
+ *
84
+ * @param drawingId The drawing id.
85
+ * @param refId The product reference to look for sketch region.
86
+ * @param sketchRegionName The name of sketch region to look for.
87
+ * @returns An array of ids of all found sketch regions. The array is empty if nothing was found.
88
+ */
89
+ export const getSketchRegion = (drawingId, refId, sketchRegionName) => {
90
+ return getObjectsfromProdRef(drawingId, refId, CCClasses.CCSketchRegion, sketchRegionName);
91
+ };
92
+ export const getSketch = (drawingId, refId, sketchName) => {
93
+ return getObjectsfromProdRef(drawingId, refId, CCClasses.CCSketch, sketchName);
94
+ };
95
+ /**
96
+ * Returns all sketch lines from a sketch or sketch regions
97
+ * @param sketchOrRegionIds id of the sketch or ids of the sketch regions
98
+ * @returns the sketchlines as array or undefined if empty
99
+ */
100
+ export const getSketchlines = (drawingId, sketchOrRegionIds) => {
101
+ var _a;
102
+ const cDrawing = getDrawing(drawingId);
103
+ const tree = cDrawing.structure.tree;
104
+ const sketchLines = [];
105
+ // if its an array, all ids must be of type sketch region
106
+ if (Array.isArray(sketchOrRegionIds)) {
107
+ sketchOrRegionIds.forEach(sRId => {
108
+ var _a;
109
+ const sketchRegion = tree[sRId];
110
+ if (sketchRegion && isA(sketchRegion.class, CCClasses.CCSketchRegion)) {
111
+ sketchLines.push(...((_a = sketchRegion.members) === null || _a === void 0 ? void 0 : _a.curves).members.map(mem => mem.value));
112
+ }
113
+ else {
114
+ throw new Error('Not all ids in the given array are of type sketch region');
115
+ }
116
+ });
117
+ // if not, it can be both, sketch or sketch region
118
+ }
119
+ else {
120
+ const sketchOrRegion = tree[sketchOrRegionIds];
121
+ // TODO: Which sketch lines need to be included, is CCClasses.CCCurve and its derivation enough?
122
+ if (sketchOrRegion && isA(sketchOrRegion.class, CCClasses.CCSketch)) {
123
+ sketchLines.push(...getChildren(sketchOrRegionIds, CCClasses.CCCurve, tree));
124
+ }
125
+ else if (sketchOrRegion && isA(sketchOrRegion.class, CCClasses.CCSketchRegion)) {
126
+ sketchLines.push(...((_a = sketchOrRegion.members) === null || _a === void 0 ? void 0 : _a.curves).members.map(mem => mem.value));
127
+ }
128
+ else {
129
+ throw new Error('The id used to get sketchlines from is not of type sketch or sketch region.');
130
+ }
131
+ }
132
+ return sketchLines.length > 0 ? sketchLines : undefined;
133
+ };
134
+ export const calculateRollbackMovement = (oldIndex, newIndex, featureIds, offset = 4) => {
135
+ const index = newIndex < offset ? offset : newIndex;
136
+ // If the rollback bar moves downwards, the index has to be incremented by 1.
137
+ const inc = newIndex > oldIndex ? 1 : 0;
138
+ if (index >= featureIds.length - 1) {
139
+ return { moveTo: 'end', featureId: -1, index };
140
+ }
141
+ else {
142
+ return { moveTo: 'before', featureId: featureIds[index + inc], index };
143
+ }
144
+ };
@@ -0,0 +1,30 @@
1
+ import { CLASSCAD_VERSION, CLASSCAD_VERSION_QUALITY } from '@classcad/api-js';
2
+ const url = `https://awvstatic.com/classcad/download/${CLASSCAD_VERSION_QUALITY}/${CLASSCAD_VERSION}`;
3
+ /**
4
+ * The ClassCAD engine this package is built against: its version, its quality, and where its bundle is.
5
+ *
6
+ * `@classcad/api-js`, the ClassCAD API this package calls, is generated by the ClassCAD engine, and carries the
7
+ * version and the quality of the bundle it belongs to. That bundle is the engine this version of buerli is made
8
+ * for: {@link WASMClient} loads its WebAssembly from `wasmUrl`, and a host that runs the engine behind a server
9
+ * ({@link WSClient}, {@link SocketIOClient}) installs the same version, from `url`. A beta of buerli is built
10
+ * against an `alpha` build, a stable release against a `release`.
11
+ *
12
+ * `npx @classcad/client info` prints the same (`--json` for the object).
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { classcadEngine } from '@classcad/client'
17
+ *
18
+ * console.log(`Built against ClassCAD ${classcadEngine.version} (${classcadEngine.quality}): ${classcadEngine.url}`)
19
+ * ```
20
+ *
21
+ * @category Clients
22
+ */
23
+ export const classcadEngine = Object.freeze({
24
+ version: CLASSCAD_VERSION,
25
+ quality: CLASSCAD_VERSION_QUALITY,
26
+ url,
27
+ metadataUrl: `${url}/metadata.json`,
28
+ wasmUrl: `${url}/wasm`,
29
+ apiUrl: `${url}/js/classcad-api-js-${CLASSCAD_VERSION}.tgz`,
30
+ });
@@ -0,0 +1,66 @@
1
+ import { v0, v1 } from '@classcad/api-js';
2
+ import { facade } from './facade';
3
+ const cache = {};
4
+ /**
5
+ * The low-level facade a drawing's API calls go through: one ClassCAD function, called by its name.
6
+ *
7
+ * `callSafeApiV(version, namespace, func, args, options)` runs `<version>.<namespace>.<func>` and resolves to the
8
+ * engine's reply, `{ result, messages, maxLevel }`; `callSafeApi` takes the namespace with its version
9
+ * (`'v1.part'`). `fetchTree` loads the structure tree anew, `callUnsafeApi` sends a command as it is. Replies are
10
+ * handled as in {@link createApi}. Use it for a function the typed API does not have, or one picked at runtime.
11
+ *
12
+ * @param drawingId - The drawing whose client the calls go to.
13
+ * @example
14
+ * ```ts
15
+ * import { getApiFacade } from '@classcad/client'
16
+ *
17
+ * // A call named at runtime, e.g. by a script or a tool an AI agent calls
18
+ * async function call(name: string, args: Record<string, unknown>) {
19
+ * const [namespace, func] = name.split('.') // 'part.box'
20
+ * const { result, messages } = await getApiFacade(drawingId).callSafeApiV('v1', namespace, func, args)
21
+ * return { result, messages }
22
+ * }
23
+ *
24
+ * const { result: part } = await call('part.create', { name: 'Part' })
25
+ * await call('part.box', { id: part, length: 50 })
26
+ * ```
27
+ * @advanced
28
+ * @category Modeling
29
+ */
30
+ export const getApiFacade = (drawingId) => facade(drawingId);
31
+ /**
32
+ * The ClassCAD API of a drawing; every call resolves to the engine's reply, `{ result, messages, maxLevel }`.
33
+ *
34
+ * `v1` holds the namespaces (`part`, `sketch`, `assembly`, `solid`, `curve`, `common`, `drawing2d`); they are also
35
+ * on the object itself, so `createApi(id).part` is `createApi(id).v1.part`. A call rejects when the reply carries an
36
+ * error, with that reply, and when the drawing has no client. Warnings and errors are logged and shown as messages
37
+ * of the drawing. `v0`, the old API, is deprecated. {@link createUnwrappedApi} gives the results without the reply
38
+ * around them.
39
+ *
40
+ * @param drawingId - A drawing that is connected, for example by {@link BuerliCadFacade.connect}.
41
+ * @param cached - `true` (default) returns the same object for the drawing on every call, `false` makes a new one.
42
+ * @example
43
+ * ```ts
44
+ * import { BuerliCadFacade, createApi, MessageLevel } from '@classcad/client'
45
+ *
46
+ * const drawingId = await BuerliCadFacade.utils.connect('Bracket')
47
+ * if (drawingId) {
48
+ * const api = createApi(drawingId)
49
+ * const part = (await api.v1.part.create({ name: 'Bracket' })).result!
50
+ * // The reply carries the engine's messages; a warning does not reject
51
+ * const { messages } = await api.v1.part.box({ id: part, length: 80, width: 40, height: 5 })
52
+ * const warnings = messages?.filter(m => m.level === MessageLevel.warning) ?? []
53
+ * if (warnings.length) console.warn(warnings.map(m => m.message))
54
+ * }
55
+ * ```
56
+ * @advanced
57
+ * @category Modeling
58
+ */
59
+ export const createApi = (drawingId, cached = true) => {
60
+ const f = getApiFacade(drawingId);
61
+ if (cached) {
62
+ cache[drawingId] = cache[drawingId] || Object.assign({ v0: v0(f), v1: v1(f) }, v1(f));
63
+ return cache[drawingId];
64
+ }
65
+ return Object.assign({ v0: v0(f), v1: v1(f) }, v1(f));
66
+ };
@@ -0,0 +1,39 @@
1
+ import { v0, v1Unwrap } from '@classcad/api-js';
2
+ import { getApiFacade } from './createApi';
3
+ const cache = {};
4
+ /**
5
+ * The ClassCAD API of a drawing, unwrapped: calls resolve to their result and reject on an engine error.
6
+ *
7
+ * The same namespaces as {@link createApi} (`v1.part`, `v1.sketch`, …, also on the object itself); this is what
8
+ * {@link BuerliCadFacade.api} is. A rejection carries the engine's reply (`{ result, messages, maxLevel }`).
9
+ * Warnings are logged and shown as messages of the drawing.
10
+ *
11
+ * @param drawingId - A drawing that is connected, for example by {@link BuerliCadFacade.connect}.
12
+ * @param cached - `true` (default) returns the same object for the drawing on every call, `false` makes a new one.
13
+ * @example
14
+ * ```ts
15
+ * import { BuerliCadFacade, createUnwrappedApi } from '@classcad/client'
16
+ *
17
+ * const drawingId = await BuerliCadFacade.utils.connect('Plate')
18
+ * if (drawingId) {
19
+ * const api = createUnwrappedApi(drawingId)
20
+ * try {
21
+ * const part = (await api.v1.part.create({ name: 'Plate' }))!
22
+ * await api.v1.part.box({ id: part, length: 200, width: 100, height: 8 })
23
+ * } catch (reply) {
24
+ * // The engine's reply, with the error in its messages
25
+ * console.error(reply)
26
+ * }
27
+ * }
28
+ * ```
29
+ * @advanced
30
+ * @category Modeling
31
+ */
32
+ export const createUnwrappedApi = (drawingId, cached = true) => {
33
+ const f = getApiFacade(drawingId);
34
+ if (cached) {
35
+ cache[drawingId] = cache[drawingId] || Object.assign({ v0: v0(f), v1: v1Unwrap(f) }, v1Unwrap(f));
36
+ return cache[drawingId];
37
+ }
38
+ return Object.assign({ v0: v0(f), v1: v1Unwrap(f) }, v1Unwrap(f));
39
+ };
@@ -0,0 +1,98 @@
1
+ import { getDrawing, showMessage } from '@classcad/sdkjs';
2
+ import { MessageLevel } from '@classcad/api-js';
3
+ import { Globals } from './globals';
4
+ export const __callAPI = async (drawingId, task, options) => {
5
+ const comClient = Globals.clientCache[drawingId];
6
+ if (!comClient) {
7
+ throw new Error('API call not possible, ClassCAD is not connected.');
8
+ }
9
+ const drawing = getDrawing(drawingId);
10
+ if (!drawing) {
11
+ throw new Error('API call not possible, buerli drawing does not exist.');
12
+ }
13
+ const usedSolidsBefore = drawing.api.structure.collectUsedSolidIds();
14
+ const streamMap = options === null || options === void 0 ? void 0 : options.streamMap;
15
+ options === null || options === void 0 ? true : delete options.streamMap;
16
+ const handleClassCadMessages = (fr) => {
17
+ var _a;
18
+ const errors = (_a = fr.messages) === null || _a === void 0 ? void 0 : _a.filter(m => m.level >= MessageLevel.warning);
19
+ if (errors && errors.length > 0) {
20
+ const toBuerliMessageType = (level) => {
21
+ switch (level) {
22
+ case MessageLevel.error:
23
+ case MessageLevel.fatal:
24
+ return 'error';
25
+ default:
26
+ return 'warning';
27
+ }
28
+ };
29
+ for (const e of errors) {
30
+ if (e.level === MessageLevel.warning) {
31
+ console.warn(`ClassCAD API Warning${e.api ? ` | ${e.api}` : ''} | ${e.message}`);
32
+ }
33
+ else {
34
+ console.error(`ClassCAD API Error${e.api ? ` | ${e.api}` : ''} | ${e.message}`);
35
+ }
36
+ const msg = { title: e.api, type: toBuerliMessageType(e.level), text: e.message, code: e.code, drawingId };
37
+ // It needs a timeout here to give the ui a bit of time to display each message
38
+ setTimeout(async () => showMessage(msg), 0); // TODO: there must be better ways than timeouts
39
+ }
40
+ }
41
+ };
42
+ try {
43
+ const fr = {};
44
+ const resp = await comClient.executeRequest(task, streamMap, options);
45
+ fr.result = resp.result;
46
+ fr.messages = resp.messages;
47
+ fr.maxLevel = resp.maxLevel;
48
+ if (resp.streamData) {
49
+ fr.streamData = resp.streamData;
50
+ }
51
+ handleClassCadMessages(fr);
52
+ return fr;
53
+ }
54
+ catch (err) {
55
+ const fr = err;
56
+ delete fr.streamData;
57
+ handleClassCadMessages(fr);
58
+ throw err;
59
+ }
60
+ finally {
61
+ const usedSolidsAfter = drawing.api.structure.collectUsedSolidIds();
62
+ // 2. cleanup data, only do this if the used solids did change
63
+ // TODO: Is there a better way to compare arrays?
64
+ if (usedSolidsBefore.sort().join() !== usedSolidsAfter.sort().join()) {
65
+ // TODO: When is the correct time to cleanup the graphic data
66
+ drawing.api.graphic.cleanupGraphicRecords();
67
+ }
68
+ // console.log('graphicContainers after command:', Object.getOwnPropertyNames(get().graphic.containers))
69
+ // console.log('geometryCache after command:', Object.getOwnPropertyNames(get().geometry.cache))
70
+ }
71
+ };
72
+ export const facade = (drawingId) => {
73
+ return {
74
+ callSafeApi: async (namespace, func, args, options) => {
75
+ let id;
76
+ try {
77
+ const command = [{ [`${namespace}.${func}`]: args ? (Array.isArray(args) ? args : [args]) : [] }];
78
+ const promise = __callAPI(drawingId, command, options);
79
+ id = getDrawing(drawingId).api.cad.addPending(`${namespace}.${func}`, { args, promise });
80
+ return (await promise); // TODO
81
+ }
82
+ finally {
83
+ id && getDrawing(drawingId).api.cad.removePending(id);
84
+ }
85
+ },
86
+ callSafeApiV: async (version, namespace, func, args, options) => {
87
+ const p = typeof args === 'undefined' || version === 'v0' ? args : [args]; // TODO: is this the correct place to do this?
88
+ return facade(drawingId).callSafeApi(`${version}.${namespace}`, func, p, options);
89
+ },
90
+ callUnsafeApi: async (command) => {
91
+ return __callAPI(drawingId, command);
92
+ },
93
+ fetchTree: async () => {
94
+ const comClient = Globals.clientCache[drawingId];
95
+ await comClient.requestTree();
96
+ },
97
+ };
98
+ };