-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathccm.js
More file actions
3021 lines (2721 loc) · 108 KB
/
ccm.js
File metadata and controls
3021 lines (2721 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/**
* @overview
* Provides the ccmjs core framework, including component loading, instance creation, and dependency resolution,
* and defines the global namespace {@link ccm}.
*
* See the {@link https://github.com/ccmjs/framework/wiki ccmjs Wiki} for more information.
*
* @author André Kless <andre.kless@web.de> (https://github.com/akless)
* @copyright 2014–2026 André Kless
* @license The MIT License (MIT)
* @version 28.0.0
*/
{
/**
* The global ccmjs namespace providing access to the core framework API.
*
* @global
* @namespace
*/
const ccm = {
// -----------------------------------------------------------------------------
// Core API
// -----------------------------------------------------------------------------
/**
* Retrieves the current version of ccmjs.
*
* Returns the version number of ccmjs as a string following Semantic Versioning 2.0.0.
* Use this as a synchronous, stable accessor for the ccmjs version.
*
* @returns {ccm.types.versionNr} Version number of ccmjs.
*/
version: "28.0.0",
/**
* Asynchronous Loading of Resources
*
* Loads resources such as HTML, CSS, images, JavaScript, modules, JSON, or XML asynchronously.
* Supports sequential and parallel loading of resources.
*
* See [this wiki page]{@link https://github.com/ccmjs/framework/wiki/Loading-Resources}
* to learn more about loading resources in ccmjs.
*
* @param {...(string|ccm.types.resourceObj)} resources - Resources to load. Either the URL or a [resource object]{@link ccm.types.resourceObj} can be passed for a resource.
* @returns {Promise<*>} A promise that resolves with the loaded resources or rejects if loading of at least one resource fails.
*/
load: async (...resources) => {
let results = []; // Stores the results of loaded resources.
let counter = 1; // Tracks the number of resources still loading.
let failed = false; // Indicates if loading of at least one resource failed.
return new Promise((resolve, reject) => {
resources.forEach((resource, i) => {
counter++; // Increment the counter for each resource.
// Handle sequential loading of resources.
if (Array.isArray(resource)) {
results[i] = [];
sequential(null);
return;
}
// Convert string URLs to resource objects.
if (typeof resource === "string") resource = { url: resource };
// By default, a resource is loaded in the <head> of the web page.
if (!resource.context) resource.context = document.head;
// Handle loading in the Shadow DOM of a ccmjs instance.
if (ccm.helper.isInstance(resource.context))
resource.context = resource.context.element.parentElement;
// Determine and call the operation to load the resource based on its type or file extension.
getOperation()();
/**
* Recursively loads a resource one after the other.
*
* This function ensures that resources are loaded sequentially, maintaining the order of execution.
* If a resource fails to load, it marks the operation as failed but continues loading the remaining resources.
* Nested arrays allow precise control over whether resources are loaded in parallel or sequentially.
*
* @param {*} result - The result of the last successfully loaded resource.
*/
function sequential(result) {
// Add the result of the last loaded resource to the result array if it exists.
if (result !== null) results[i].push(result);
// Check if all resources have been loaded; if so, then treat the loading of these resources as complete.
if (!resource.length) return check();
// Retrieve the next resource to be loaded.
let next = resource.shift();
// Ensure the next resource is wrapped in an array for consistent processing.
if (!Array.isArray(next)) next = [next];
// Load the next resource and recursively call `sequential` upon success or failure.
ccm.load
.apply(null, next)
.then(sequential)
.catch((result) => {
failed = true; // Mark the operation as failed if an error occurs.
sequential(result); // Continue loading the remaining resources.
});
}
/**
* Returns the operation to load resource according to its type.
*
* @returns {Function}
*/
function getOperation() {
switch (resource.type) {
case "css":
return loadCSS;
case "image":
return loadImage;
case "js":
return loadJS;
case "module":
return loadModule;
case "json":
return loadJSON;
case "xml":
return loadXML;
}
// Infer the type from the file extension of the resource URL when no type is given.
const fileExtension = resource.url
.split(/[#?]/)[0] // Remove query parameters and hash from URL.
.split(".") // Split the URL by dots to get the file extension.
.at(-1) // Get the last part as the file extension.
.trim(); // Remove any surrounding whitespace.
// Match the file extension to the corresponding loading operation.
switch (fileExtension) {
case "css":
return loadCSS;
case "jpg":
case "jpeg":
case "png":
case "gif":
case "svg":
case "webp":
case "avif":
case "apng":
return loadImage;
case "js":
return loadJS;
case "mjs":
return loadModule;
case "xml":
return loadXML;
default:
return loadJSON;
}
}
/**
* Loads a CSS file via a `<link>` tag.
*
* Creates a `<link>` element to load the CSS file. Additional attributes can be set via the `resource.attr` property.
* The CSS file is loaded in the specified context, and success or error callbacks are triggered accordingly.
*/
function loadCSS() {
const element = document.createElement("link");
element.rel = "stylesheet";
element.type = "text/css";
element.href = resource.url;
// additional attributes
if (resource.attr) {
for (const key in resource.attr) {
element.setAttribute(key, resource.attr[key]);
}
}
element.onload = () => success(resource.url);
element.onerror = error;
resource.context.appendChild(element);
}
/**
* Preloads an image.
*
* Creates an `Image` object to preload the image. The `src` attribute of the image is set to the URL provided in the `resource` object.
* When the image is successfully loaded, the `success` callback is triggered with the image URL.
* If an error occurs during loading, the `error` callback is triggered.
*/
function loadImage() {
const image = new Image();
image.src = resource.url;
image.onload = () => success(resource.url);
image.onerror = error;
}
/**
* Loads JavaScript via a <script> tag.
*
* Creates a <script> element to load the JavaScript file. The filename is extracted and used to handle result data.
* The script is loaded asynchronously, and success or error callbacks are triggered accordingly.
*/
function loadJS() {
const element = document.createElement("script");
element.src = resource.url;
element.async = true;
// additional attributes
if (resource.attr) {
for (const key in resource.attr) {
element.setAttribute(key, resource.attr[key]);
}
}
element.onload = () => {
element.remove();
success(resource.url);
};
element.onerror = () => {
element.remove();
error();
};
resource.context.appendChild(element);
}
/**
* Loads a JavaScript module via dynamic import.
*
* This function dynamically imports an ES module from a given URL. It supports Subresource Integrity (SRI) checks
* to ensure the module's integrity. If specific properties of the module are requested (indicated by hash signs in the URL),
* only those properties are included in the result. The function also clones the imported module to avoid caching issues.
*/
async function loadModule() {
// Extract optional property keys from URL hash.
let [url, ...keys] = resource.url.split("#");
// Resolve relative URLs to absolute URLs.
url = new URL(url, location.href).href;
let result;
// Handle SRI verification.
if (resource.attr?.integrity) {
// Fetch module source.
const text = await (await fetch(url)).text();
// Compute SRI hash.
const prefix = resource.attr.integrity.slice(
0,
resource.attr.integrity.indexOf("-"),
);
const algorithm = prefix.toUpperCase().replace("SHA", "SHA-");
const data = new TextEncoder().encode(text);
const hash = await crypto.subtle.digest(algorithm, data);
const base64 = btoa(String.fromCharCode(...new Uint8Array(hash)));
const sri = `${prefix}-${base64}`;
// Verify integrity.
if (sri !== resource.attr.integrity) return error();
// Create blob URL for dynamic import.
const blobUrl = URL.createObjectURL(
new Blob([text], { type: "text/javascript" }),
);
result = await import(blobUrl);
URL.revokeObjectURL(blobUrl);
} else {
result = await import(url);
}
// If only one specific deeper value has to be the result.
if (keys.length === 1)
result = ccm.helper.deepValue(result, keys[0]);
// If multiple properties should be returned.
if (keys.length > 1) {
const obj = {};
keys.forEach((key) => (obj[key] = result[key]));
result = obj;
}
// Dynamic import returns cached module references → clone to avoid mutation.
if (ccm.helper.isObject(result)) result = ccm.helper.clone(result);
success(result);
}
/**
* Loads JSON data via Fetch API.
*
* Sends an HTTP request to fetch the JSON data and handles the response.
* Supports both `GET` and `POST` methods, with optional parameters. Default is `GET`.
*/
function loadJSON() {
// Prepare the URL or request body based on the HTTP method.
if (resource.params)
resource.method === "POST"
? (resource.body = JSON.stringify(resource.params))
: (resource.url = buildURL(resource.url, resource.params));
// Perform the fetch request and handle the response.
fetch(resource.url, resource)
.then((response) => response.text())
.then(success)
.catch(error);
}
/**
* Builds a URL with query parameters.
*
* Appends the provided query parameters to the base URL.
* Supports nested objects and arrays for complex query structures.
*
* @param {string} url - Base URL
* @param {Object} data - Query parameters to append
* @returns {string} - URL with appended query parameters.
*/
function buildURL(url, data) {
// Append query parameters to the URL.
return data ? url + "?" + params(data).slice(0, -1) : url;
/**
* Converts an object to query string parameters.
*
* Recursively processes nested objects and arrays to generate query strings.
*
* @param {Object} obj - Object to convert
* @param {string} [prefix] - Prefix for nested keys
* @returns {string} - Generated query string.
*/
function params(obj, prefix) {
let result = "";
for (const i in obj) {
const key = prefix
? prefix + "[" + encodeURIComponent(i) + "]"
: encodeURIComponent(i);
if (typeof obj[i] === "object") result += params(obj[i], key);
else result += key + "=" + encodeURIComponent(obj[i]) + "&";
}
return result;
}
}
/**
* Loads XML via Fetch API as an XML document.
*
* Sets the resource type to `xml` and delegates the loading process to the `loadJSON` function.
* The loaded XML content is parsed into an XML document.
*/
function loadXML() {
resource.type = "xml";
loadJSON();
}
/**
* Callback when loading of a resource was successful.
*
* Processes the loaded data based on its type (e.g., XML) and updates the results array.
* Triggers the next step in the loading process.
*
* @param {*} data - Loaded resource data
*/
function success(data) {
// If the data is not defined, then treat the loading of this resource as complete.
if (data === undefined) return check();
// Attempt to parse the data as JSON if it is not already an object.
try {
if (typeof data !== "object") data = JSON.parse(data);
} catch (e) {}
// Process XML resources by parsing the data into an XML document.
if (resource.type === "xml")
data = new window.DOMParser().parseFromString(data, "text/xml");
// Update the result array with the processed data.
if (Array.isArray(results)) results[i] = data;
// Treat the loading of this resource as complete and check if all resources have been loaded.
check();
}
/**
* Callback when loading of a resource failed.
*
* Marks the loading process as failed and updates the results array with an error object.
* Triggers the next step in the loading process.
*/
function error(e) {
// Indicate that at least one resource failed to load.
failed = true;
// Add an error object to the `results` array for the failed resource, including its URL.
results[i] = e || new Error(`loading of ${resource.url} failed`);
// Treat the loading of this resource as complete and check if all resources have been loaded, even if some failed.
check();
}
});
// Check if all resources already have been loaded.
check();
/**
* Callback function to handle the completion of resource loading.
*
* This function is called whenever a resource is finished loading and checks whether all resources have been loaded. If not, it waits for the remaining resources.
* Once all resources are loaded, it resolves or rejects the promise based on the loading status.
*/
function check() {
if (--counter) return; // If there are still resources loading, wait for them to finish.
if (results.length <= 1) results = results[0]; // If only one resource was loaded, return it directly.
(failed ? reject : resolve)(results); // Resolve or reject the promise based on the loading status.
}
});
},
/**
* Registers a ccmjs component.
*
* This method registers a component, ensuring compatibility with different ccmjs versions.
* It retrieves the component object, validates it, adjusts the ccmjs version, and registers the component.
* If the component uses a different ccmjs version, it handles backwards compatibility.
* The method also prepares the default instance configuration and adds methods for creating and starting ccmjs instances.
*
* See [this wiki page]{@link https://github.com/ccmjs/framework/wiki/Embedding-Components}
* to learn more about embedding components with ccmjs.
*
* @param {ccm.types.componentObj|string} component - Component object, index, or URL of the component to register
* @param {ccm.types.config} [config={}] - Priority data for the component's default instance configuration
* @returns {Promise<ccm.types.componentObj>} Clone of the registered component object.
* @throws {Error} If the provided component is not valid.
*/
component: async (component, config = {}) => {
// Retrieve the component object via index, URL or directly as JavaScript object.
component = await getComponentObject();
// If the component is not a valid object, throw an error.
if (!ccm.helper.isComponent(component))
throw new Error("invalid component: " + component);
// Adjust the ccmjs version used by the component via config.
if (config.ccm) component.ccm = config.ccm;
delete config.ccm;
// Determine the ccmjs version the component must use (considering backwards compatibility).
let version;
if (ccm.helper.isFramework(component.ccm)) {
const v = component.ccm.version;
version = typeof v === "function" ? v() : v;
} else version = component.ccm.match(/-(\d+\.\d+\.\d+)/)?.at(1);
// Load the required ccmjs version if not already present in the web page.
if (!window.ccm[version]) {
// The ccmjs version is loaded with SRI when the SRI hash is appended to the URL with “#”.
const [url, sri] = component.ccm.split("#");
await ccm.load(
sri
? { url, attr: { integrity: sri, crossorigin: "anonymous" } }
: url,
);
}
// If the component uses a different ccmjs version, handle backwards compatibility.
if (version && version !== ccm.version)
return backwardsCompatibility(version, "component", component, config);
// Set the component index based on its name and version.
component.index =
component.name +
(component.version ? "-" + component.version.join("-") : "");
// Register the component if it is not already registered.
if (!_components[component.index]) {
_components[component.index] = component; // Store the component object encapsulated in ccmjs.
component.instances = 0; // Add a counter for component instances.
component.ready && (await component.ready.call(component)); // Execute the "ready" callback if defined.
delete component.ready; // Remove the "ready" callback after execution.
}
// Clone the registered component object to avoid direct modifications.
component = ccm.helper.clone(_components[component.index]);
// Set the reference to the used ccmjs version.
component.ccm = window.ccm[version] || ccm;
// Prepare the default instance configuration.
component.config = await ccm.helper.prepareConfig(
config,
component.config,
);
// Add methods for creating and starting instances of the component.
component.instance = async (config = {}, area) =>
ccm.instance(
component,
await ccm.helper.prepareConfig(config, component.config),
area,
);
component.start = async (config = {}, area) =>
ccm.start(
component,
await ccm.helper.prepareConfig(config, component.config),
area,
);
return component;
/**
* Retrieves the component object via index, URL or directly as JavaScript object.
*
* @returns {Promise<ccm.types.componentObj>} Component object
*/
async function getComponentObject() {
// Return the component directly if it is not a string.
if (typeof component !== "string") return component;
/**
* Extracts metadata from the component URL.
* @type {{name: string, index: string, version: string, filename: string, url: string, minified: boolean, sri: string}}
*/
const urlData = /\.m?js(#.*)?$/.test(component)
? ccm.helper.parseComponentURL(component)
: null;
/**
* Index of the component
* @type {ccm.types.componentIndex}
*/
const index = urlData?.index || component;
// Return a clone of the registered component object if already registered.
if (_components[index]) return ccm.helper.clone(_components[index]);
// Abort if the component URL is not provided.
if (!urlData) return component;
// Load the component from the URL.
let result = await ccm.load({
url: urlData.url,
type: "module",
// If the SRI hash is provided, load the component with SRI.
attr: urlData.sri && {
integrity: urlData.sri,
crossorigin: "anonymous",
},
});
if (result?.component) result = result.component;
else {
// Component file did not return the component object => try to get the component from window.ccm.files. (backwards compatibility)
const filename = `ccm.${urlData.name}.js`;
if (!window.ccm.files) window.ccm.files = {};
window.ccm.files[filename] = null; // marks the component as 'loading'
window.ccm.files = new Proxy(window.ccm.files, {
set(obj, key, value) {
if (key === filename) {
result = value;
window.ccm.files = obj; // restore original files object
}
return Reflect.set(...arguments);
},
});
await ccm.load(urlData.url);
delete window.ccm.files[filename];
}
result.url = urlData.url; // A component remembers its URL.
return result;
}
},
/**
* Creates and initializes a ccmjs instance from a given component.
*
* This method registers a ccmjs component, prepares its configuration, and creates an instance.
* It resolves dependencies, sets up the instance's DOM structure, and initializes the instance.
* If the component uses a different ccmjs version, it handles backwards compatibility.
*
* See [this wiki page]{@link https://github.com/ccmjs/framework/wiki/Embedding-Components}
* to learn more about embedding components in ccmjs.
*
* @param {ccm.types.componentObj|string} component - Component object, index, or URL of the component to register
* @param {ccm.types.config} [config={}] - Priority data for instance configuration
* @param {Element} [area=document.createElement("div")] - Web page area where the component instance will be embedded (default: on-the-fly `<div>`)
* @returns {Promise<ccm.types.instance>} A promise that resolves to the created instance.
* @throws {Error} If the provided component is not valid.
*/
instance: async (
component,
config = {},
area = document.createElement("div"),
) => {
// Register the component.
component = await ccm.component(component, { ccm: config?.ccm });
// Abort if the component is not valid.
if (!ccm.helper.isComponent(component)) return component;
// Handle backwards compatibility if the component uses another ccmjs version.
const version =
typeof component.ccm.version === "function"
? component.ccm.version()
: component.ccm.version;
if (version && version !== ccm.version)
return backwardsCompatibility(
version,
"instance",
component,
config,
area,
);
// Render a loading icon in the web page area.
const loading = ccm.helper.loading();
area.replaceChildren(loading);
// Prepare the instance configuration.
config = await ccm.helper.prepareConfig(config, component.config);
/**
* Created ccmjs instance
* @type {ccm.types.instance}
*/
const instance = new component.Instance();
// Set ccmjs-specific properties for the instance.
instance.ccm = component.ccm; // Reference to the used ccmjs version
instance.component = component; // Component the instance is created from
instance.id = ++_components[component.index].instances; // Instance ID. Unique within the component.
instance.index = component.index + "-" + instance.id; // Instance index. Unique within the web page.
if (!instance.init) instance.init = async () => {}; // Ensure the instance has an init method.
instance.children = {}; // Store child instances used by this instance.
instance.parent = config.parent; // Reference to parent instance
delete config.parent; // Prevent cyclic recursion when resolving dependencies.
instance.config = ccm.helper.stringify(config); // Store the original configuration.
// Add the instance as a child to its parent instance.
if (instance.parent) instance.parent.children[instance.index] = instance;
// Create the host element for the instance.
instance.host = document.createElement("div");
// Create a shadow root for the instance if required.
if (config.root !== false)
instance.root = instance.host.attachShadow({
mode: config.root || "open",
});
delete config.root;
// Create the content element, which lies directly within the shadow root of the host element.
(instance.root || instance.host).appendChild(
(instance.element = document.createElement("div")),
);
// Temporarily move the host element to <head> for resolving dependencies.
document.head.appendChild(instance.host);
config = await ccm.helper.solveDependencies(config, instance); // Resolve all dependencies in the instance configuration.
area.appendChild(instance.host); // Move the host element back to the target web page area.
instance.element.appendChild(loading); // Move the loading icon to the content element.
// Apply configuration mapper if defined.
const mapper = config.mapper;
delete config.mapper;
if (mapper) config = ccm.helper.mapObject(config, mapper);
// Remove reserved properties from the configuration to prevent conflicts with instance properties.
const reserved = new Set([
"children",
"component",
"element",
"host",
"init",
"instance",
"parent",
"ready",
"root",
"start",
]);
for (const key of reserved) {
if (key in config) {
console.warn(
`[ccmjs] config property '${key}' is reserved and was ignored.`,
);
delete config[key];
}
}
// Integrate configuration into instance.
Object.assign(instance, config);
// Initialize created and dependent instances if necessary.
if (!instance.parent?.init) await initialize();
// Remove loading icon from content element
loading.remove();
return instance;
/**
* Initializes the created instance and all dependent ccmjs instances.
*
* @returns {Promise<void>} A promise that resolves when initialization is complete.
*/
function initialize() {
return new Promise((resolve) => {
/**
* Stores all found ccmjs instances.
* @type {ccm.types.instance[]}
*/
const instances = [instance];
// Find all sub-instances dependent on the created instance.
find(instance);
// Call init methods of all found ccmjs instances.
let i = 0;
init();
/**
* Finds all dependent ccmjs instances (breadth-first-order, recursive).
*
* @param {Array|Object} obj - Array or object to search
*/
function find(obj) {
/**
* Stores relevant inner objects/arrays for breadth-first-order.
* @type {Array.<Array|Object>}
*/
const relevant = [];
// Search the object/array.
for (const key in obj)
if (Object.hasOwn(obj, key)) {
const value = obj[key];
// Add ccmjs instances to the list of found instances.
if (ccm.helper.isInstance(value) && key !== "parent") {
instances.push(value);
relevant.push(value);
}
// Add relevant inner arrays/objects for further searching.
else if (Array.isArray(value) || ccm.helper.isObject(value)) {
// relevant object type? => add to relevant inner arrays/objects
if (!ccm.helper.isNonCloneable(value)) relevant.push(value);
}
}
// Recursively search relevant inner arrays/objects.
relevant.forEach(find);
}
/**
* Calls the `init` methods of all ccmjs instances in sequence.
*
* This function processes a list of ccmjs instances and calls their `init` methods asynchronously.
* Once all `init` methods are called, it proceeds to the `ready` method.
* If an instance does not have an `init` method, it skips to the next instance.
*/
function init() {
// If all init methods are called, proceed to ready methods.
if (i === instances.length) return ready();
/**
* Next ccmjs instance to call the init method.
* @type {ccm.types.instance}
*/
const next = instances[i++];
// Call and delete the init method, then continue with the next instance.
next.init
? next.init().then(() => {
delete next.init;
init();
})
: init();
}
/**
* Calls the `ready` methods of all ccmjs instances in reverse order.
*
* This function processes a stack of ccmjs instances, calling their `ready` methods asynchronously.
* Once all `ready` methods are called, the promise is resolved.
* If an instance does not have a `ready` method, it proceeds to the next instance.
*/
function ready() {
// If all ready methods are called, resolve the promise.
if (!instances.length) return resolve();
/**
* Next ccmjs instance to call the `ready` method.
* @type {ccm.types.instance}
*/
const next = instances.pop();
// Call and delete the ready method, then proceed to the next instance.
next.ready
? next.ready().then(() => {
delete next.ready;
proceed();
})
: proceed();
/**
* Handles the next step after the instance is ready.
*
* If the instance is marked to start directly, it calls its `start` method.
* Otherwise, it continues with the next instance in the stack.
*/
function proceed() {
// If configured for immediate execution, start the instance first, then call ready.
if (next._start) {
delete next._start;
next.start().then(ready);
} else ready();
}
}
});
}
},
/**
* Registers a ccmjs component, creates an instance out of it, and starts the instance.
*
* This function handles the registration of a ccmjs component, creates an instance from it, and starts the instance.
* It ensures compatibility with different ccmjs versions and initializes the instance if required.
*
* See [this wiki page]{@link https://github.com/ccmjs/framework/wiki/Embedding-Components}
* to learn more about embedding components in ccmjs.
*
* @param {ccm.types.componentObj|string} component - Component object, index, or URL of the component to register
* @param {ccm.types.config} [config={}] - Priority data for instance configuration
* @param {Element} [area=document.createElement("div")] - Web page area where the component instance will be embedded (default: on-the-fly `<div>`).
* @returns {Promise<ccm.types.instance>} A promise that resolves to the created and started instance.
* @throws {Error} If the provided component is not valid.
*/
start: async (component, config = {}, area) => {
// Register component.
component = await ccm.component(component, { ccm: config?.ccm });
// Abort if the component is not valid.
if (!ccm.helper.isComponent(component)) return component;
// Handle backwards compatibility if the component uses another ccmjs version.
const version =
typeof component.ccm.version === "function"
? component.ccm.version()
: component.ccm.version;
if (version && version !== ccm.version)
return backwardsCompatibility(
version,
"start",
component,
config,
area,
);
// Create an instance out of the component.
const instance = await ccm.instance(component, config, area);
// Abort if the instance is not valid.
if (!ccm.helper.isInstance(instance)) return instance;
// Start the instance directly (is standalone) or mark it for starting after initialization (is child instance).
instance.init ? (instance._start = true) : await instance.start();
// Return the created and started instance.
return instance;
},
/**
* Creates and initializes a datastore accessor.
*
* Factory method that provides a unified abstraction for data persistence.
* Based on the provided configuration, the appropriate datastore implementation is selected automatically:
*
* 1. **InMemoryStore** – Volatile, stored in a JavaScript object.
* 2. **OfflineStore** – Persistent in browser storage (IndexedDB).
* 3. **RemoteStore** – Persistent on a remote server via HTTP(S) or WebSocket API.
*
* The selection logic is purely configuration-driven:
* - No `config.name` → InMemoryStore
* - `config.name` only → OfflineStore
* - `config.name` + `config.url` → RemoteStore
*
* The configuration is fully resolved before initialization
* (including declarative CCM dependencies).
*
* Each invocation creates and initializes a fresh datastore instance.
* No internal caching or global registry of datastore accessors exists.
*
* The returned object implements the common {@link Datastore} API,
* independent of the underlying storage mechanism.
*
* Use {@link ccm.get} for one-time reads without needing direct
* access to the datastore instance.
*
* See [this wiki page]{@link https://github.com/ccmjs/framework/wiki/Data-Management}
* to learn more about data management in ccmjs.
*
* @param {ccm.types.storeConfig} [config={}] - Datastore configuration
* @param {string} [config.name] - Logical name of the datastore (required for OfflineStore and RemoteStore)
* @param {string} [config.url] - Remote endpoint URL. Used together with `name` to create a RemoteStore.
* @param {string} [config.db] - (RemoteStore only) Optional database identifier if the server supports multiple databases.
* @param {Object.<string,ccm.types.dataset>|ccm.types.dataset[]} [config.datasets] - (InMemoryStore only) Initial datasets, either as associative object `{ key: dataset }` or array `[ { key, ... }, ... ]`.
* @param {Object} [config.observe] - (RemoteStore only) Query defining which datasets should be observed via WebSocket.
* @param {function(Object):void} [config.onchange] - (RemoteStore only) Callback invoked when an observed dataset changes.
* @param {Object} [config.user] - (RemoteStore only) Component instance used for authentication.
* @returns {Promise<Datastore>} Resolves to an initialized datastore accessor implementing the common datastore API.
*/
store: async (config = {}) => {
// Resolve the configuration if it is a dependency.
config = await ccm.helper.solveDependency(config);
// Resolve any nested dependencies in the configuration.
await ccm.helper.solveDependencies(config);
// If a RemoteStore is specified, ensure the store name is provided.
if (config.url && !config.name)
throw new Error(
`RemoteStore "${config.url}" requires a store name (config.name).`,
);
// Determine the type of datastore to use based on the configuration.
const store = new (
config.name ? (config.url ? RemoteStore : OfflineStore) : InMemoryStore
)();
// Assign the resolved configuration properties to the datastore instance.
Object.assign(store, config);
// Initialize the datastore.
await store.init();
// Return the initialized datastore instance.
return store;
},
/**
* Loads dataset(s) from a datastore in a single step.
*
* Convenience method that creates a transient datastore accessor via {@link ccm.store} and immediately executes a `get()` operation.
*
* This method is primarily intended for declarative data dependencies in
* instance configurations. It allows datasets to be loaded without exposing
* the underlying datastore instance.
*
* Unlike {@link ccm.store}, this method does not return the datastore accessor.
* Use {@link ccm.store} if further interaction (e.g. `set()`, `del()`, `count()`)
* with the datastore is required.
*
* Store instances are not cached. Each call creates and initializes a fresh
* datastore accessor based on the provided configuration.
*
* See [this wiki page]{@link https://github.com/ccmjs/framework/wiki/Data-Management}
* to learn more about data management in ccmjs.
*
* @param {ccm.types.storeConfig} [config={}] - Datastore configuration (same as {@link ccm.store})
* @param {ccm.types.key|Object} [keyOrQuery={}]
* Either a dataset key or a query object.
* If omitted or an empty object is provided, all datasets are returned.
* @param {Object} [projection]
* Optional field projection that limits which dataset properties are returned.
* Support for this parameter depends on the datastore implementation.
* Currently intended for use with {@link RemoteStore}.
* @param {Object} [options]
* Optional datastore-specific query options (e.g. sorting, pagination, server-side modifiers).
* Interpretation depends on the datastore implementation and may be ignored by some store types.
* @returns {Promise<ccm.types.dataset|ccm.types.dataset[]>} Resolves to the requested dataset or an array of datasets.
*/
get: (config = {}, keyOrQuery = {}, projection, options) =>
ccm
.store(config)
.then((store) => store.get(keyOrQuery, projection, options)),
/**
* Contains ccmjs-relevant helper functions.
*
* These are also useful for component developers.
*
* @namespace
*/
helper: {
/**
* Creates a deep copy of a value.
*
* Arrays and plain objects are recursively cloned.
* Primitive values are returned unchanged.
*
* Special objects such as DOM nodes, CCM instances, datastores,
* the CCM core, or the global window object are not cloned and
* are returned as references.
*
* Cyclic references are detected using an internal hash set and
* are not traversed again to avoid infinite recursion.