@pure-ds/core 0.7.3 → 0.7.4

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 (44) hide show
  1. package/dist/types/pds.d.ts +1 -0
  2. package/dist/types/public/assets/js/pds-ask.d.ts +2 -1
  3. package/dist/types/public/assets/js/pds-ask.d.ts.map +1 -1
  4. package/dist/types/public/assets/js/pds-autocomplete.d.ts +25 -36
  5. package/dist/types/public/assets/js/pds-autocomplete.d.ts.map +1 -1
  6. package/dist/types/public/assets/js/pds-enhancers.d.ts +4 -4
  7. package/dist/types/public/assets/js/pds-enhancers.d.ts.map +1 -1
  8. package/dist/types/public/assets/js/pds-manager.d.ts +444 -159
  9. package/dist/types/public/assets/js/pds-manager.d.ts.map +1 -1
  10. package/dist/types/public/assets/js/pds-toast.d.ts +7 -6
  11. package/dist/types/public/assets/js/pds-toast.d.ts.map +1 -1
  12. package/dist/types/public/assets/js/pds.d.ts +4 -3
  13. package/dist/types/public/assets/js/pds.d.ts.map +1 -1
  14. package/dist/types/src/js/pds-core/pds-start-helpers.d.ts.map +1 -1
  15. package/package.json +1 -1
  16. package/packages/pds-cli/bin/pds-static.js +5 -1
  17. package/packages/pds-cli/bin/sync-assets.js +7 -1
  18. package/public/assets/js/app.js +4 -1543
  19. package/public/assets/js/lit.js +3 -1078
  20. package/public/assets/js/pds-ask.js +9 -239
  21. package/public/assets/js/pds-autocomplete.js +7 -590
  22. package/public/assets/js/pds-enhancers.js +1 -689
  23. package/public/assets/js/pds-manager.js +3160 -15973
  24. package/public/assets/js/pds-toast.js +1 -30
  25. package/public/assets/js/pds.js +2 -1409
  26. package/public/assets/pds/core/pds-ask.js +9 -239
  27. package/public/assets/pds/core/pds-autocomplete.js +7 -590
  28. package/public/assets/pds/core/pds-enhancers.js +1 -689
  29. package/public/assets/pds/core/pds-manager.js +3160 -15973
  30. package/public/assets/pds/core/pds-toast.js +1 -30
  31. package/public/assets/pds/core.js +2 -1409
  32. package/public/assets/pds/external/lit.js +3 -1078
  33. package/readme.md +2 -0
  34. package/src/js/pds-core/pds-start-helpers.js +60 -2
  35. package/src/js/pds.d.ts +1 -0
  36. package/public/assets/js/app.js.map +0 -7
  37. package/public/assets/js/lit.js.map +0 -7
  38. package/public/assets/js/pds-ask.js.map +0 -7
  39. package/public/assets/js/pds-autocomplete.js.map +0 -7
  40. package/public/assets/js/pds-enhancers.js.map +0 -7
  41. package/public/assets/js/pds-manager.js.map +0 -7
  42. package/public/assets/js/pds-toast.js.map +0 -7
  43. package/public/assets/js/pds.js.map +0 -7
  44. package/public/assets/pds/core/pds-auto-definer.js +0 -306
@@ -1,1409 +1,2 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/js/pds-core/pds-registry.js
8
- var PDSRegistry = class {
9
- constructor() {
10
- this._mode = "static";
11
- this._staticPaths = {
12
- tokens: "/assets/pds/styles/pds-tokens.css.js",
13
- primitives: "/assets/pds/styles/pds-primitives.css.js",
14
- components: "/assets/pds/styles/pds-components.css.js",
15
- utilities: "/assets/pds/styles/pds-utilities.css.js",
16
- styles: "/assets/pds/styles/pds-styles.css.js"
17
- };
18
- }
19
- /**
20
- * Switch to live mode
21
- */
22
- setLiveMode() {
23
- this._mode = "live";
24
- }
25
- /**
26
- * Switch to static mode with custom paths
27
- * Called by consumers who want to use static CSS files
28
- */
29
- setStaticMode(paths = {}) {
30
- this._mode = "static";
31
- this._staticPaths = { ...this._staticPaths, ...paths };
32
- }
33
- /**
34
- * Get stylesheet for adoption in shadow DOM
35
- * Returns CSSStyleSheet object (constructable stylesheet)
36
- */
37
- async getStylesheet(layer) {
38
- if (this._mode === "live") {
39
- return null;
40
- } else {
41
- try {
42
- const module = await import(
43
- /* @vite-ignore */
44
- this._staticPaths[layer]
45
- );
46
- return module[layer];
47
- } catch (error) {
48
- console.error(`[PDS Registry] Failed to load static ${layer}:`, error);
49
- console.error(`[PDS Registry] Looking for: ${this._staticPaths[layer]}`);
50
- console.error(`[PDS Registry] Make sure you've run 'npm run pds:build' and configured PDS.start() with the correct static.root path`);
51
- const fallback = new CSSStyleSheet();
52
- fallback.replaceSync("/* Failed to load " + layer + " */");
53
- return fallback;
54
- }
55
- }
56
- }
57
- /**
58
- * Get current mode
59
- */
60
- get mode() {
61
- return this._mode;
62
- }
63
- /**
64
- * Check if in live mode
65
- */
66
- get isLive() {
67
- return this._mode === "live";
68
- }
69
- };
70
- var registry = new PDSRegistry();
71
-
72
- // src/js/pds-core/pds-runtime.js
73
- async function adoptPrimitives(shadowRoot, additionalSheets = [], generator = null) {
74
- try {
75
- const primitives = generator?.primitivesStylesheet ? generator.primitivesStylesheet : await registry.getStylesheet("primitives");
76
- shadowRoot.adoptedStyleSheets = [primitives, ...additionalSheets];
77
- } catch (error) {
78
- const componentName = shadowRoot.host?.tagName?.toLowerCase() || "unknown";
79
- console.error(
80
- `[PDS Adopter] <${componentName}> failed to adopt primitives:`,
81
- error
82
- );
83
- shadowRoot.adoptedStyleSheets = additionalSheets;
84
- }
85
- }
86
- async function adoptLayers(shadowRoot, layers = ["primitives"], additionalSheets = [], generator = null) {
87
- try {
88
- const stylesheets = await Promise.all(
89
- layers.map(async (layer) => {
90
- if (generator) {
91
- switch (layer) {
92
- case "tokens":
93
- return generator.tokensStylesheet;
94
- case "primitives":
95
- return generator.primitivesStylesheet;
96
- case "components":
97
- return generator.componentsStylesheet;
98
- case "utilities":
99
- return generator.utilitiesStylesheet;
100
- default:
101
- break;
102
- }
103
- }
104
- return registry.getStylesheet(layer);
105
- })
106
- );
107
- const validStylesheets = stylesheets.filter((sheet) => sheet !== null);
108
- shadowRoot.adoptedStyleSheets = [...validStylesheets, ...additionalSheets];
109
- } catch (error) {
110
- const componentName = shadowRoot.host?.tagName?.toLowerCase() || "unknown";
111
- console.error(
112
- `[PDS Adopter] <${componentName}> failed to adopt layers:`,
113
- error
114
- );
115
- shadowRoot.adoptedStyleSheets = additionalSheets;
116
- }
117
- }
118
- function createStylesheet(css) {
119
- const sheet = new CSSStyleSheet();
120
- sheet.replaceSync(css);
121
- return sheet;
122
- }
123
-
124
- // src/js/pds-core/pds-enums.js
125
- var enums = {
126
- FontWeights: {
127
- light: 300,
128
- normal: 400,
129
- medium: 500,
130
- semibold: 600,
131
- bold: 700
132
- },
133
- LineHeights: {
134
- tight: 1.25,
135
- normal: 1.5,
136
- relaxed: 1.75
137
- },
138
- BorderWidths: {
139
- hairline: 0.5,
140
- thin: 1,
141
- medium: 2,
142
- thick: 3
143
- },
144
- RadiusSizes: {
145
- none: 0,
146
- small: 4,
147
- medium: 8,
148
- large: 16,
149
- xlarge: 24,
150
- xxlarge: 32
151
- },
152
- ShadowDepths: {
153
- none: "none",
154
- light: "0 1px 2px 0 rgba(0, 0, 0, 0.05)",
155
- medium: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
156
- deep: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",
157
- extreme: "0 25px 50px -12px rgba(0, 0, 0, 0.25)"
158
- },
159
- TransitionSpeeds: {
160
- fast: 150,
161
- normal: 250,
162
- slow: 350
163
- },
164
- AnimationEasings: {
165
- linear: "linear",
166
- ease: "ease",
167
- "ease-in": "ease-in",
168
- "ease-out": "ease-out",
169
- "ease-in-out": "ease-in-out",
170
- bounce: "cubic-bezier(0.68, -0.55, 0.265, 1.55)"
171
- },
172
- TouchTargetSizes: {
173
- compact: 36,
174
- standard: 44,
175
- // iOS/Android accessibility standard
176
- comfortable: 48,
177
- spacious: 56
178
- },
179
- LinkStyles: {
180
- inline: "inline",
181
- // Normal inline text links
182
- block: "block",
183
- // Block-level links
184
- button: "button"
185
- // Button-like links (flex with touch target)
186
- },
187
- FocusStyles: {
188
- ring: "ring",
189
- // Box-shadow ring (default)
190
- outline: "outline",
191
- // Browser outline
192
- border: "border",
193
- // Border change
194
- glow: "glow"
195
- // Subtle glow effect
196
- },
197
- TabSizes: {
198
- compact: 2,
199
- standard: 4,
200
- wide: 8
201
- },
202
- SelectIcons: {
203
- chevron: "chevron",
204
- // Standard chevron down
205
- arrow: "arrow",
206
- // Simple arrow
207
- caret: "caret",
208
- // Triangle caret
209
- none: "none"
210
- // No icon
211
- },
212
- IconSizes: {
213
- xs: 16,
214
- sm: 20,
215
- md: 24,
216
- lg: 32,
217
- xl: 48,
218
- "2xl": 64,
219
- "3xl": 96
220
- }
221
- };
222
-
223
- // src/js/common/common.js
224
- var common_exports = {};
225
- __export(common_exports, {
226
- deepMerge: () => deepMerge,
227
- fragmentFromTemplateLike: () => fragmentFromTemplateLike,
228
- isObject: () => isObject,
229
- parseHTML: () => parseHTML
230
- });
231
- function isObject(item) {
232
- return item && typeof item === "object" && !Array.isArray(item);
233
- }
234
- function deepMerge(target, source) {
235
- const output = { ...target };
236
- if (isObject(target) && isObject(source)) {
237
- Object.keys(source).forEach((key) => {
238
- if (isObject(source[key])) {
239
- if (!(key in target))
240
- Object.assign(output, { [key]: source[key] });
241
- else
242
- output[key] = deepMerge(target[key], source[key]);
243
- } else {
244
- Object.assign(output, { [key]: source[key] });
245
- }
246
- });
247
- }
248
- return output;
249
- }
250
- function fragmentFromTemplateLike(templateLike) {
251
- const strings = Array.isArray(templateLike?.strings) ? templateLike.strings : [];
252
- const values = Array.isArray(templateLike?.values) ? templateLike.values : [];
253
- const consumedValues = /* @__PURE__ */ new Set();
254
- const htmlParts = [];
255
- const propBindingPattern = /(\s)(\.[\w-]+)=\s*$/;
256
- for (let i = 0; i < strings.length; i += 1) {
257
- let chunk = strings[i] ?? "";
258
- const match = chunk.match(propBindingPattern);
259
- if (match && i < values.length) {
260
- const propToken = match[2];
261
- const propName = propToken.slice(1);
262
- const marker = `pds-val-${i}`;
263
- chunk = chunk.replace(
264
- propBindingPattern,
265
- `$1data-pds-prop="${propName}:${marker}"`
266
- );
267
- consumedValues.add(i);
268
- }
269
- htmlParts.push(chunk);
270
- if (i < values.length && !consumedValues.has(i)) {
271
- htmlParts.push(`<!--pds-val-${i}-->`);
272
- }
273
- }
274
- const tpl = document.createElement("template");
275
- tpl.innerHTML = htmlParts.join("");
276
- const replaceValueAtMarker = (markerNode, value) => {
277
- const parent = markerNode.parentNode;
278
- if (!parent)
279
- return;
280
- if (value == null) {
281
- parent.removeChild(markerNode);
282
- return;
283
- }
284
- const insertValue = (val) => {
285
- if (val == null)
286
- return;
287
- if (val instanceof Node) {
288
- parent.insertBefore(val, markerNode);
289
- return;
290
- }
291
- if (Array.isArray(val)) {
292
- val.forEach((item) => insertValue(item));
293
- return;
294
- }
295
- parent.insertBefore(document.createTextNode(String(val)), markerNode);
296
- };
297
- insertValue(value);
298
- parent.removeChild(markerNode);
299
- };
300
- const walker = document.createTreeWalker(tpl.content, NodeFilter.SHOW_COMMENT);
301
- const markers = [];
302
- while (walker.nextNode()) {
303
- const node = walker.currentNode;
304
- if (node?.nodeValue?.startsWith("pds-val-")) {
305
- markers.push(node);
306
- }
307
- }
308
- markers.forEach((node) => {
309
- const index = Number(node.nodeValue.replace("pds-val-", ""));
310
- replaceValueAtMarker(node, values[index]);
311
- });
312
- const elements = tpl.content.querySelectorAll("*");
313
- elements.forEach((el) => {
314
- const propAttr = el.getAttribute("data-pds-prop");
315
- if (!propAttr)
316
- return;
317
- const [propName, markerValue] = propAttr.split(":");
318
- const index = Number(String(markerValue).replace("pds-val-", ""));
319
- if (propName && Number.isInteger(index)) {
320
- el[propName] = values[index];
321
- }
322
- el.removeAttribute("data-pds-prop");
323
- });
324
- return tpl.content;
325
- }
326
- function parseHTML(html) {
327
- return new DOMParser().parseFromString(html, "text/html").body.childNodes;
328
- }
329
-
330
- // src/js/pds-core/pds-paths.js
331
- var DEFAULT_SEGMENT = "pds";
332
- var URL_PATTERN = /^([a-z][a-z0-9+\-.]*:)?\/\//i;
333
- var DRIVE_PATTERN = /^[a-z]:/i;
334
- function ensureTrailingSlash(value = "") {
335
- return value.endsWith("/") ? value : `${value}/`;
336
- }
337
- function appendSegmentIfMissing(input = "", segment = DEFAULT_SEGMENT) {
338
- const trimmed = input.replace(/\/+$/, "");
339
- const regex = new RegExp(`(?:^|/)${segment}$`, "i");
340
- if (regex.test(trimmed)) {
341
- return trimmed;
342
- }
343
- return `${trimmed}/${segment}`;
344
- }
345
- function stripLeadingDotSlash(value) {
346
- return value.replace(/^\.\/+/, "");
347
- }
348
- function stripDriveLetter(value) {
349
- if (DRIVE_PATTERN.test(value)) {
350
- return value.replace(DRIVE_PATTERN, "").replace(/^\/+/, "");
351
- }
352
- return value;
353
- }
354
- function stripPublicPrefix(value) {
355
- if (value.startsWith("public/")) {
356
- return value.substring("public/".length);
357
- }
358
- return value;
359
- }
360
- function resolvePublicAssetURL(config, options = {}) {
361
- const segment = options.segment || DEFAULT_SEGMENT;
362
- const defaultRoot = options.defaultRoot || `/assets/${segment}/`;
363
- const candidate = config?.public && config.public?.root || config?.static && config.static?.root || null;
364
- if (!candidate || typeof candidate !== "string") {
365
- return ensureTrailingSlash(defaultRoot);
366
- }
367
- let normalized = candidate.trim();
368
- if (!normalized) {
369
- return ensureTrailingSlash(defaultRoot);
370
- }
371
- normalized = normalized.replace(/\\/g, "/");
372
- normalized = appendSegmentIfMissing(normalized, segment);
373
- normalized = ensureTrailingSlash(normalized);
374
- if (URL_PATTERN.test(normalized)) {
375
- return normalized;
376
- }
377
- normalized = stripLeadingDotSlash(normalized);
378
- normalized = stripDriveLetter(normalized);
379
- if (normalized.startsWith("/")) {
380
- return ensureTrailingSlash(normalized);
381
- }
382
- normalized = stripPublicPrefix(normalized);
383
- if (!normalized.startsWith("/")) {
384
- normalized = `/${normalized}`;
385
- }
386
- normalized = normalized.replace(
387
- /\/+/g,
388
- (match, offset) => offset === 0 ? match : "/"
389
- );
390
- return ensureTrailingSlash(normalized);
391
- }
392
-
393
- // node_modules/pure-web/src/js/auto-definer.js
394
- async function defineWebComponents(...args) {
395
- let opts = {};
396
- if (args.length && typeof args[args.length - 1] === "object") {
397
- opts = args.pop() || {};
398
- }
399
- const tags = args;
400
- const {
401
- baseURL,
402
- mapper = (tag) => `${tag}.js`,
403
- onError = (tag, err) => console.error(`[defineWebComponents] ${tag}:`, err)
404
- } = opts;
405
- const base = baseURL ? new URL(
406
- baseURL,
407
- typeof location !== "undefined" ? location.href : import.meta.url
408
- ) : new URL("./", import.meta.url);
409
- const toPascal = (tag) => tag.toLowerCase().replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase());
410
- const loadOne = async (tag) => {
411
- try {
412
- if (customElements.get(tag))
413
- return { tag, status: "already-defined" };
414
- const spec = mapper(tag);
415
- const href = spec instanceof URL ? spec.href : new URL(spec, base).href;
416
- const mod = await import(href);
417
- const Named = mod?.default ?? mod?.[toPascal(tag)];
418
- if (!Named) {
419
- if (customElements.get(tag))
420
- return { tag, status: "self-defined" };
421
- throw new Error(
422
- `No export found for ${tag}. Expected default export or named export "${toPascal(
423
- tag
424
- )}".`
425
- );
426
- }
427
- if (!customElements.get(tag)) {
428
- customElements.define(tag, Named);
429
- return { tag, status: "defined" };
430
- }
431
- return { tag, status: "race-already-defined" };
432
- } catch (err) {
433
- onError(tag, err);
434
- throw err;
435
- }
436
- };
437
- return Promise.all(tags.map(loadOne));
438
- }
439
- var AutoDefiner = class {
440
- constructor(options = {}) {
441
- const {
442
- baseURL,
443
- mapper,
444
- onError,
445
- predicate = () => true,
446
- attributeModule = "data-module",
447
- root = document,
448
- scanExisting = true,
449
- debounceMs = 16,
450
- observeShadows = true,
451
- enhancers = [],
452
- // [{String selector, Function run(elem)}]
453
- patchAttachShadow = true
454
- } = options;
455
- const pending = /* @__PURE__ */ new Set();
456
- const inFlight = /* @__PURE__ */ new Set();
457
- const knownMissing = /* @__PURE__ */ new Set();
458
- const perTagModulePath = /* @__PURE__ */ new Map();
459
- const shadowObservers = /* @__PURE__ */ new WeakMap();
460
- const enhancerApplied = /* @__PURE__ */ new WeakMap();
461
- let timer = 0;
462
- let stopped = false;
463
- let restoreAttachShadow = null;
464
- const applyEnhancers = (element) => {
465
- if (!element || !enhancers.length)
466
- return;
467
- let appliedEnhancers = enhancerApplied.get(element);
468
- if (!appliedEnhancers) {
469
- appliedEnhancers = /* @__PURE__ */ new Set();
470
- enhancerApplied.set(element, appliedEnhancers);
471
- }
472
- for (const enhancer of enhancers) {
473
- if (!enhancer.selector || !enhancer.run)
474
- continue;
475
- if (appliedEnhancers.has(enhancer.selector))
476
- continue;
477
- try {
478
- if (element.matches && element.matches(enhancer.selector)) {
479
- enhancer.run(element);
480
- appliedEnhancers.add(enhancer.selector);
481
- }
482
- } catch (err) {
483
- console.warn(
484
- `[AutoDefiner] Error applying enhancer for selector "${enhancer.selector}":`,
485
- err
486
- );
487
- }
488
- }
489
- };
490
- const queueTag = (tag, el) => {
491
- if (stopped)
492
- return;
493
- if (!tag || !tag.includes("-"))
494
- return;
495
- if (customElements.get(tag))
496
- return;
497
- if (inFlight.has(tag))
498
- return;
499
- if (knownMissing.has(tag))
500
- return;
501
- if (el && el.getAttribute) {
502
- const override = el.getAttribute(attributeModule);
503
- if (override && !perTagModulePath.has(tag)) {
504
- perTagModulePath.set(tag, override);
505
- }
506
- }
507
- pending.add(tag);
508
- schedule();
509
- };
510
- const schedule = () => {
511
- if (timer)
512
- return;
513
- timer = setTimeout(flush, debounceMs);
514
- };
515
- const crawlTree = (rootNode) => {
516
- if (!rootNode)
517
- return;
518
- if (rootNode.nodeType === 1) {
519
- const el = (
520
- /** @type {Element} */
521
- rootNode
522
- );
523
- const tag = el.tagName?.toLowerCase();
524
- if (tag && tag.includes("-") && !customElements.get(tag) && predicate(tag, el)) {
525
- queueTag(tag, el);
526
- }
527
- applyEnhancers(el);
528
- if (observeShadows && el.shadowRoot) {
529
- observeShadowRoot(el.shadowRoot);
530
- }
531
- }
532
- if (rootNode.querySelectorAll) {
533
- rootNode.querySelectorAll("*").forEach((e) => {
534
- const t = e.tagName?.toLowerCase();
535
- if (t && t.includes("-") && !customElements.get(t) && predicate(t, e)) {
536
- queueTag(t, e);
537
- }
538
- applyEnhancers(e);
539
- if (observeShadows && e.shadowRoot) {
540
- observeShadowRoot(e.shadowRoot);
541
- }
542
- });
543
- }
544
- };
545
- const observeShadowRoot = (sr) => {
546
- if (!sr || shadowObservers.has(sr))
547
- return;
548
- crawlTree(sr);
549
- const mo = new MutationObserver((mutations) => {
550
- for (const m of mutations) {
551
- m.addedNodes?.forEach((n) => {
552
- crawlTree(n);
553
- });
554
- if (m.type === "attributes" && m.target) {
555
- crawlTree(m.target);
556
- }
557
- }
558
- });
559
- mo.observe(sr, {
560
- childList: true,
561
- subtree: true,
562
- attributes: true,
563
- attributeFilter: [
564
- attributeModule,
565
- ...enhancers.map((e) => e.selector).filter((s) => s.startsWith("data-"))
566
- ]
567
- });
568
- shadowObservers.set(sr, mo);
569
- };
570
- async function flush() {
571
- clearTimeout(timer);
572
- timer = 0;
573
- if (!pending.size)
574
- return;
575
- const tags = Array.from(pending);
576
- pending.clear();
577
- tags.forEach((t) => inFlight.add(t));
578
- try {
579
- const effectiveMapper = (tag) => perTagModulePath.get(tag) ?? (mapper ? mapper(tag) : `${tag}.js`);
580
- await defineWebComponents(...tags, {
581
- baseURL,
582
- mapper: effectiveMapper,
583
- onError: (tag, err) => {
584
- knownMissing.add(tag);
585
- onError?.(tag, err);
586
- }
587
- });
588
- } catch {
589
- } finally {
590
- tags.forEach((t) => inFlight.delete(t));
591
- }
592
- }
593
- const mountNode = root === document ? document.documentElement : root;
594
- const obs = new MutationObserver((mutations) => {
595
- for (const m of mutations) {
596
- m.addedNodes?.forEach((n) => {
597
- crawlTree(n);
598
- });
599
- if (m.type === "attributes" && m.target) {
600
- crawlTree(m.target);
601
- }
602
- }
603
- });
604
- obs.observe(mountNode, {
605
- childList: true,
606
- subtree: true,
607
- attributes: true,
608
- attributeFilter: [
609
- attributeModule,
610
- ...enhancers.map((e) => e.selector).filter((s) => s.startsWith("data-"))
611
- ]
612
- });
613
- if (observeShadows && patchAttachShadow && Element.prototype.attachShadow) {
614
- const orig = Element.prototype.attachShadow;
615
- Element.prototype.attachShadow = function patchedAttachShadow(init) {
616
- const sr = orig.call(this, init);
617
- if (init && init.mode === "open") {
618
- observeShadowRoot(sr);
619
- const tag = this.tagName?.toLowerCase();
620
- if (tag && tag.includes("-") && !customElements.get(tag)) {
621
- queueTag(tag, this);
622
- }
623
- }
624
- return sr;
625
- };
626
- restoreAttachShadow = () => Element.prototype.attachShadow = orig;
627
- }
628
- if (scanExisting) {
629
- crawlTree(mountNode);
630
- }
631
- return {
632
- stop() {
633
- stopped = true;
634
- obs.disconnect();
635
- if (restoreAttachShadow)
636
- restoreAttachShadow();
637
- if (timer) {
638
- clearTimeout(timer);
639
- timer = 0;
640
- }
641
- shadowObservers.forEach((mo) => mo.disconnect());
642
- },
643
- flush
644
- };
645
- }
646
- /**
647
- * Dynamically load and (idempotently) define a set of web components by tag name.
648
- */
649
- static async define(...args) {
650
- let opts = {};
651
- if (args.length && typeof args[args.length - 1] === "object") {
652
- opts = args.pop() || {};
653
- }
654
- const tags = args;
655
- const {
656
- baseURL,
657
- mapper = (tag) => `${tag}.js`,
658
- onError = (tag, err) => console.error(`[defineWebComponents] ${tag}:`, err)
659
- } = opts;
660
- const base = baseURL ? new URL(
661
- baseURL,
662
- typeof location !== "undefined" ? location.href : import.meta.url
663
- ) : new URL("./", import.meta.url);
664
- const toPascal = (tag) => tag.toLowerCase().replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase());
665
- const loadOne = async (tag) => {
666
- try {
667
- if (customElements.get(tag))
668
- return { tag, status: "already-defined" };
669
- const spec = mapper(tag);
670
- const href = spec instanceof URL ? spec.href : new URL(spec, base).href;
671
- const mod = await import(href);
672
- const Named = mod?.default ?? mod?.[toPascal(tag)];
673
- if (!Named) {
674
- if (customElements.get(tag))
675
- return { tag, status: "self-defined" };
676
- throw new Error(
677
- `No export found for ${tag}. Expected default export or named export "${toPascal(
678
- tag
679
- )}".`
680
- );
681
- }
682
- if (!customElements.get(tag)) {
683
- customElements.define(tag, Named);
684
- return { tag, status: "defined" };
685
- }
686
- return { tag, status: "race-already-defined" };
687
- } catch (err) {
688
- onError(tag, err);
689
- throw err;
690
- }
691
- };
692
- return Promise.all(tags.map(loadOne));
693
- }
694
- };
695
-
696
- // src/js/pds-core/pds-start-helpers.js
697
- var __ABSOLUTE_URL_PATTERN__ = /^[a-z][a-z0-9+\-.]*:\/\//i;
698
- var __MODULE_URL__ = (() => {
699
- try {
700
- return import.meta.url;
701
- } catch (e) {
702
- return void 0;
703
- }
704
- })();
705
- var ensureTrailingSlash2 = (value) => typeof value === "string" && value.length && !value.endsWith("/") ? `${value}/` : value;
706
- function ensureAbsoluteAssetURL(value, options = {}) {
707
- if (!value || __ABSOLUTE_URL_PATTERN__.test(value)) {
708
- return value;
709
- }
710
- const { preferModule = true } = options;
711
- const tryModule = () => {
712
- if (!__MODULE_URL__)
713
- return null;
714
- try {
715
- return new URL(value, __MODULE_URL__).href;
716
- } catch (e) {
717
- return null;
718
- }
719
- };
720
- const tryWindow = () => {
721
- if (typeof window === "undefined" || !window.location?.origin) {
722
- return null;
723
- }
724
- try {
725
- return new URL(value, window.location.origin).href;
726
- } catch (e) {
727
- return null;
728
- }
729
- };
730
- const resolved = preferModule ? tryModule() || tryWindow() : tryWindow() || tryModule();
731
- return resolved || value;
732
- }
733
- var __MODULE_DEFAULT_ASSET_ROOT__ = (() => {
734
- if (!__MODULE_URL__)
735
- return void 0;
736
- try {
737
- const parsed = new URL(__MODULE_URL__);
738
- if (/\/public\/assets\/js\//.test(parsed.pathname)) {
739
- return new URL("../pds/", __MODULE_URL__).href;
740
- }
741
- } catch (e) {
742
- return void 0;
743
- }
744
- return void 0;
745
- })();
746
- var __foucListenerAttached = false;
747
- function attachFoucListener(PDS2) {
748
- if (__foucListenerAttached || typeof document === "undefined")
749
- return;
750
- __foucListenerAttached = true;
751
- PDS2.addEventListener("pds:ready", (event) => {
752
- const mode = event.detail?.mode;
753
- if (mode) {
754
- document.documentElement.classList.add(`pds-${mode}`, "pds-ready");
755
- }
756
- });
757
- }
758
- function resolveThemeAndApply({ manageTheme, themeStorageKey, applyResolvedTheme: applyResolvedTheme2, setupSystemListenerIfNeeded: setupSystemListenerIfNeeded2 }) {
759
- let resolvedTheme = "light";
760
- let storedTheme = null;
761
- if (manageTheme && typeof window !== "undefined") {
762
- try {
763
- storedTheme = localStorage.getItem(themeStorageKey) || null;
764
- } catch (e) {
765
- storedTheme = null;
766
- }
767
- try {
768
- applyResolvedTheme2?.(storedTheme);
769
- setupSystemListenerIfNeeded2?.(storedTheme);
770
- } catch (e) {
771
- }
772
- if (storedTheme) {
773
- if (storedTheme === "system") {
774
- const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
775
- resolvedTheme = prefersDark ? "dark" : "light";
776
- } else {
777
- resolvedTheme = storedTheme;
778
- }
779
- } else {
780
- const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
781
- resolvedTheme = prefersDark ? "dark" : "light";
782
- }
783
- }
784
- return { resolvedTheme, storedTheme };
785
- }
786
- function resolveRuntimeAssetRoot(config, { resolvePublicAssetURL: resolvePublicAssetURL2 }) {
787
- const hasCustomRoot = Boolean(config?.public?.root || config?.static?.root);
788
- let candidate = resolvePublicAssetURL2(config);
789
- if (!hasCustomRoot && __MODULE_DEFAULT_ASSET_ROOT__) {
790
- candidate = __MODULE_DEFAULT_ASSET_ROOT__;
791
- }
792
- return ensureTrailingSlash2(ensureAbsoluteAssetURL(candidate));
793
- }
794
- async function setupAutoDefinerAndEnhancers(options, { baseEnhancers = [] } = {}) {
795
- const {
796
- autoDefineBaseURL = "/auto-define/",
797
- autoDefinePreload = [],
798
- autoDefineMapper = null,
799
- enhancers = [],
800
- autoDefineOverrides = null,
801
- autoDefinePreferModule = true
802
- } = options;
803
- const mergedEnhancers = (() => {
804
- const map = /* @__PURE__ */ new Map();
805
- (baseEnhancers || []).forEach((e) => map.set(e.selector, e));
806
- (enhancers || []).forEach((e) => map.set(e.selector, e));
807
- return Array.from(map.values());
808
- })();
809
- let autoDefiner = null;
810
- if (typeof window !== "undefined" && typeof document !== "undefined") {
811
- const AutoDefinerCtor = AutoDefiner;
812
- const defaultMapper = (tag) => {
813
- switch (tag) {
814
- case "pds-tabpanel":
815
- return "pds-tabstrip.js";
816
- default:
817
- return `${tag}.js`;
818
- }
819
- };
820
- const { mapper: _overrideMapperIgnored, ...restAutoDefineOverrides } = autoDefineOverrides && typeof autoDefineOverrides === "object" ? autoDefineOverrides : {};
821
- const normalizedBaseURL = autoDefineBaseURL ? ensureTrailingSlash2(
822
- ensureAbsoluteAssetURL(autoDefineBaseURL, {
823
- preferModule: autoDefinePreferModule
824
- })
825
- ) : autoDefineBaseURL;
826
- const autoDefineConfig = {
827
- baseURL: normalizedBaseURL,
828
- predefine: autoDefinePreload,
829
- scanExisting: true,
830
- observeShadows: true,
831
- patchAttachShadow: true,
832
- debounceMs: 16,
833
- enhancers: mergedEnhancers,
834
- onError: (tag, err) => {
835
- if (typeof tag === "string" && tag.startsWith("pds-")) {
836
- const litDependentComponents = ["pds-form", "pds-drawer"];
837
- const isLitComponent = litDependentComponents.includes(tag);
838
- const isMissingLitError = err?.message?.includes("#pds/lit") || err?.message?.includes("Failed to resolve module specifier");
839
- if (isLitComponent && isMissingLitError) {
840
- console.error(
841
- `\u274C PDS component <${tag}> requires Lit but #pds/lit is not in import map.
842
- See: https://github.com/Pure-Web-Foundation/pure-ds/blob/main/readme.md#lit-components-not-working`
843
- );
844
- } else {
845
- console.warn(
846
- `\u26A0\uFE0F PDS component <${tag}> not found. Assets may not be installed.`
847
- );
848
- }
849
- } else {
850
- console.error(`\u274C Auto-define error for <${tag}>:`, err);
851
- }
852
- },
853
- // Apply all user overrides except mapper so we can still wrap it
854
- ...restAutoDefineOverrides,
855
- mapper: (tag) => {
856
- if (customElements.get(tag))
857
- return null;
858
- if (typeof autoDefineMapper === "function") {
859
- try {
860
- const mapped = autoDefineMapper(tag);
861
- if (mapped === void 0) {
862
- return defaultMapper(tag);
863
- }
864
- return mapped;
865
- } catch (e) {
866
- console.warn(
867
- "Custom autoDefine.mapper error; falling back to default:",
868
- e?.message || e
869
- );
870
- return defaultMapper(tag);
871
- }
872
- }
873
- return defaultMapper(tag);
874
- }
875
- };
876
- autoDefiner = new AutoDefinerCtor(autoDefineConfig);
877
- if (autoDefinePreload.length > 0 && typeof AutoDefinerCtor.define === "function") {
878
- await AutoDefinerCtor.define(...autoDefinePreload, {
879
- baseURL: autoDefineBaseURL,
880
- mapper: autoDefineConfig.mapper,
881
- onError: autoDefineConfig.onError
882
- });
883
- }
884
- }
885
- return { autoDefiner, mergedEnhancers };
886
- }
887
-
888
- // src/js/pds-core/pds-theme-utils.js
889
- var DEFAULT_THEMES = ["light", "dark"];
890
- var VALID_THEMES = new Set(DEFAULT_THEMES);
891
- function normalizePresetThemes(preset) {
892
- const themes = Array.isArray(preset?.themes) ? preset.themes.map((theme) => String(theme).toLowerCase()) : DEFAULT_THEMES;
893
- const normalized = themes.filter((theme) => VALID_THEMES.has(theme));
894
- return normalized.length ? normalized : DEFAULT_THEMES;
895
- }
896
- function resolveThemePreference(preference, { preferDocument = true } = {}) {
897
- const normalized = String(preference || "").toLowerCase();
898
- if (VALID_THEMES.has(normalized))
899
- return normalized;
900
- if (preferDocument && typeof document !== "undefined") {
901
- const applied = document.documentElement?.getAttribute("data-theme");
902
- if (VALID_THEMES.has(applied))
903
- return applied;
904
- }
905
- if (typeof window !== "undefined" && window.matchMedia) {
906
- const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
907
- return prefersDark ? "dark" : "light";
908
- }
909
- return "light";
910
- }
911
- function isPresetThemeCompatible(preset, themePreference) {
912
- const resolvedTheme = resolveThemePreference(themePreference);
913
- const themes = normalizePresetThemes(preset);
914
- return themes.includes(resolvedTheme);
915
- }
916
-
917
- // src/js/pds.js
918
- var PDSBase = class extends EventTarget {
919
- };
920
- var PDS = new PDSBase();
921
- PDS.initializing = false;
922
- PDS.currentPreset = null;
923
- PDS.debug = false;
924
- var __autoCompletePromise = null;
925
- var __askPromise = null;
926
- var __toastPromise = null;
927
- var __defaultEnhancersPromise = null;
928
- function __resolveExternalRuntimeModuleURL(filename, overrideURL) {
929
- if (overrideURL && typeof overrideURL === "string") {
930
- return overrideURL;
931
- }
932
- const assetRootURL = resolveRuntimeAssetRoot(PDS.currentConfig || {}, {
933
- resolvePublicAssetURL
934
- });
935
- return `${assetRootURL}core/${filename}`;
936
- }
937
- async function __loadDefaultEnhancers() {
938
- if (Array.isArray(PDS.defaultEnhancers) && PDS.defaultEnhancers.length > 0) {
939
- return PDS.defaultEnhancers;
940
- }
941
- if (!__defaultEnhancersPromise) {
942
- const enhancersModuleURL = __resolveExternalRuntimeModuleURL(
943
- "pds-enhancers.js",
944
- PDS.currentConfig?.enhancersURL
945
- );
946
- __defaultEnhancersPromise = import(enhancersModuleURL).then((mod) => {
947
- const enhancers = Array.isArray(mod?.defaultPDSEnhancers) ? mod.defaultPDSEnhancers : [];
948
- PDS.defaultEnhancers = enhancers;
949
- return enhancers;
950
- }).catch((error) => {
951
- __defaultEnhancersPromise = null;
952
- throw error;
953
- });
954
- }
955
- return __defaultEnhancersPromise;
956
- }
957
- async function __loadAsk() {
958
- if (typeof PDS.ask === "function" && PDS.ask !== __lazyAsk) {
959
- return PDS.ask;
960
- }
961
- if (!__askPromise) {
962
- const askModuleURL = __resolveExternalRuntimeModuleURL(
963
- "pds-ask.js",
964
- PDS.currentConfig?.askURL
965
- );
966
- __askPromise = import(askModuleURL).then((mod) => {
967
- const impl = mod?.ask;
968
- if (typeof impl !== "function") {
969
- throw new Error("Failed to load ask helper");
970
- }
971
- PDS.ask = impl;
972
- return impl;
973
- }).catch((error) => {
974
- __askPromise = null;
975
- throw error;
976
- });
977
- }
978
- return __askPromise;
979
- }
980
- async function __loadToast() {
981
- if (typeof PDS.toast === "function" && PDS.toast !== __lazyToast) {
982
- return PDS.toast;
983
- }
984
- if (!__toastPromise) {
985
- const toastModuleURL = __resolveExternalRuntimeModuleURL(
986
- "pds-toast.js",
987
- PDS.currentConfig?.toastURL
988
- );
989
- __toastPromise = import(toastModuleURL).then((mod) => {
990
- const impl = mod?.toast;
991
- if (typeof impl !== "function") {
992
- throw new Error("Failed to load toast helper");
993
- }
994
- PDS.toast = impl;
995
- return impl;
996
- }).catch((error) => {
997
- __toastPromise = null;
998
- throw error;
999
- });
1000
- }
1001
- return __toastPromise;
1002
- }
1003
- async function __lazyAsk(...args) {
1004
- const askImpl = await __loadAsk();
1005
- return askImpl(...args);
1006
- }
1007
- async function __lazyToast(...args) {
1008
- const toastImpl = await __loadToast();
1009
- return toastImpl(...args);
1010
- }
1011
- __lazyToast.success = async (...args) => {
1012
- const toastImpl = await __loadToast();
1013
- return toastImpl.success(...args);
1014
- };
1015
- __lazyToast.error = async (...args) => {
1016
- const toastImpl = await __loadToast();
1017
- return toastImpl.error(...args);
1018
- };
1019
- __lazyToast.warning = async (...args) => {
1020
- const toastImpl = await __loadToast();
1021
- return toastImpl.warning(...args);
1022
- };
1023
- __lazyToast.info = async (...args) => {
1024
- const toastImpl = await __loadToast();
1025
- return toastImpl.info(...args);
1026
- };
1027
- var __defaultLog = function(level = "log", message, ...data) {
1028
- const isStaticMode = Boolean(PDS.registry && !PDS.registry.isLive);
1029
- const debug = (this?.debug || this?.design?.debug || PDS.debug || false) === true;
1030
- if (isStaticMode) {
1031
- if (!PDS.debug)
1032
- return;
1033
- } else if (!debug && level !== "error" && level !== "warn") {
1034
- return;
1035
- }
1036
- const method = console[level] || console.log;
1037
- if (data.length > 0) {
1038
- method(message, ...data);
1039
- } else {
1040
- method(message);
1041
- }
1042
- };
1043
- function __stripFunctionsForClone(value) {
1044
- if (value === null || value === void 0)
1045
- return value;
1046
- if (typeof value === "function")
1047
- return void 0;
1048
- if (typeof value !== "object")
1049
- return value;
1050
- if (Array.isArray(value)) {
1051
- return value.map((item) => __stripFunctionsForClone(item)).filter((item) => item !== void 0);
1052
- }
1053
- const result = {};
1054
- for (const [key, entry] of Object.entries(value)) {
1055
- const stripped = __stripFunctionsForClone(entry);
1056
- if (stripped !== void 0) {
1057
- result[key] = stripped;
1058
- }
1059
- }
1060
- return result;
1061
- }
1062
- async function __loadRuntimeConfig(assetRootURL, config = {}) {
1063
- if (config?.runtimeConfig === false)
1064
- return null;
1065
- if (typeof fetch !== "function")
1066
- return null;
1067
- const runtimeUrl = config?.runtimeConfigURL || `${assetRootURL}pds-runtime-config.json`;
1068
- try {
1069
- const res = await fetch(runtimeUrl, { cache: "no-store" });
1070
- if (!res.ok)
1071
- return null;
1072
- return await res.json();
1073
- } catch (e) {
1074
- return null;
1075
- }
1076
- }
1077
- PDS.registry = registry;
1078
- PDS.enums = enums;
1079
- PDS.adoptLayers = adoptLayers;
1080
- PDS.adoptPrimitives = adoptPrimitives;
1081
- PDS.parse = parseHTML;
1082
- PDS.createStylesheet = createStylesheet;
1083
- PDS.isLiveMode = () => registry.isLive;
1084
- PDS.ask = __lazyAsk;
1085
- PDS.toast = __lazyToast;
1086
- PDS.common = common_exports;
1087
- PDS.AutoComplete = null;
1088
- PDS.loadAutoComplete = async () => {
1089
- if (PDS.AutoComplete && typeof PDS.AutoComplete.connect === "function") {
1090
- return PDS.AutoComplete;
1091
- }
1092
- const autoCompleteModuleURL = __resolveExternalRuntimeModuleURL(
1093
- "pds-autocomplete.js",
1094
- PDS.currentConfig?.autoCompleteURL
1095
- );
1096
- if (!__autoCompletePromise) {
1097
- __autoCompletePromise = import(autoCompleteModuleURL).then((mod) => {
1098
- const autoCompleteCtor = mod?.AutoComplete || mod?.default?.AutoComplete || mod?.default || null;
1099
- if (!autoCompleteCtor) {
1100
- throw new Error("AutoComplete export not found in module");
1101
- }
1102
- PDS.AutoComplete = autoCompleteCtor;
1103
- return autoCompleteCtor;
1104
- }).catch((error) => {
1105
- __autoCompletePromise = null;
1106
- throw error;
1107
- });
1108
- }
1109
- return __autoCompletePromise;
1110
- };
1111
- function __emitPDSReady(detail) {
1112
- const hasCustomEvent = typeof CustomEvent === "function";
1113
- try {
1114
- const readyEvent = hasCustomEvent ? new CustomEvent("pds:ready", { detail }) : new Event("pds:ready");
1115
- PDS.dispatchEvent(readyEvent);
1116
- } catch (e) {
1117
- }
1118
- if (typeof document !== "undefined") {
1119
- if (hasCustomEvent) {
1120
- const eventOptions = { detail, bubbles: true, composed: true };
1121
- try {
1122
- document.dispatchEvent(new CustomEvent("pds:ready", eventOptions));
1123
- } catch (e) {
1124
- }
1125
- try {
1126
- document.dispatchEvent(new CustomEvent("pds-ready", eventOptions));
1127
- } catch (e) {
1128
- }
1129
- } else {
1130
- try {
1131
- document.dispatchEvent(new Event("pds:ready"));
1132
- } catch (e) {
1133
- }
1134
- try {
1135
- document.dispatchEvent(new Event("pds-ready"));
1136
- } catch (e) {
1137
- }
1138
- }
1139
- }
1140
- }
1141
- function __emitPDSConfigChanged(detail = {}) {
1142
- const hasCustomEvent = typeof CustomEvent === "function";
1143
- const payload = {
1144
- at: Date.now(),
1145
- ...detail
1146
- };
1147
- try {
1148
- const changedEvent = hasCustomEvent ? new CustomEvent("pds:config-changed", { detail: payload }) : new Event("pds:config-changed");
1149
- PDS.dispatchEvent(changedEvent);
1150
- } catch (e) {
1151
- }
1152
- if (typeof document !== "undefined") {
1153
- if (hasCustomEvent) {
1154
- const eventOptions = { detail: payload, bubbles: true, composed: true };
1155
- try {
1156
- document.dispatchEvent(
1157
- new CustomEvent("pds:config-changed", eventOptions)
1158
- );
1159
- } catch (e) {
1160
- }
1161
- } else {
1162
- try {
1163
- document.dispatchEvent(new Event("pds:config-changed"));
1164
- } catch (e) {
1165
- }
1166
- }
1167
- }
1168
- }
1169
- var __themeStorageKey = "pure-ds-theme";
1170
- var __themeMQ = null;
1171
- var __themeMQListener = null;
1172
- function __applyResolvedTheme(raw) {
1173
- try {
1174
- if (typeof document === "undefined")
1175
- return;
1176
- let resolved = "light";
1177
- if (!raw) {
1178
- const prefersDark = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
1179
- resolved = prefersDark ? "dark" : "light";
1180
- } else if (raw === "system") {
1181
- const prefersDark = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
1182
- resolved = prefersDark ? "dark" : "light";
1183
- } else {
1184
- resolved = raw;
1185
- }
1186
- document.documentElement.setAttribute("data-theme", resolved);
1187
- } catch (e) {
1188
- }
1189
- }
1190
- function __setupSystemListenerIfNeeded(raw) {
1191
- try {
1192
- if (__themeMQ && __themeMQListener) {
1193
- try {
1194
- if (typeof __themeMQ.removeEventListener === "function")
1195
- __themeMQ.removeEventListener("change", __themeMQListener);
1196
- else if (typeof __themeMQ.removeListener === "function")
1197
- __themeMQ.removeListener(__themeMQListener);
1198
- } catch (e) {
1199
- }
1200
- __themeMQ = null;
1201
- __themeMQListener = null;
1202
- }
1203
- if (raw === "system" && typeof window !== "undefined" && window.matchMedia) {
1204
- const mq = window.matchMedia("(prefers-color-scheme: dark)");
1205
- const listener = (e) => {
1206
- const isDark = e?.matches === void 0 ? mq.matches : e.matches;
1207
- try {
1208
- const newTheme = isDark ? "dark" : "light";
1209
- document.documentElement.setAttribute("data-theme", newTheme);
1210
- PDS.dispatchEvent(
1211
- new CustomEvent("pds:theme:changed", {
1212
- detail: { theme: newTheme, source: "system" }
1213
- })
1214
- );
1215
- } catch (ex) {
1216
- }
1217
- };
1218
- __themeMQ = mq;
1219
- __themeMQListener = listener;
1220
- if (typeof mq.addEventListener === "function")
1221
- mq.addEventListener("change", listener);
1222
- else if (typeof mq.addListener === "function")
1223
- mq.addListener(listener);
1224
- }
1225
- } catch (e) {
1226
- }
1227
- }
1228
- Object.defineProperty(PDS, "theme", {
1229
- get() {
1230
- try {
1231
- if (typeof window === "undefined")
1232
- return null;
1233
- return localStorage.getItem(__themeStorageKey) || null;
1234
- } catch (e) {
1235
- return null;
1236
- }
1237
- },
1238
- set(value) {
1239
- try {
1240
- if (typeof window === "undefined")
1241
- return;
1242
- const currentPreset = PDS.currentConfig?.design || null;
1243
- const resolvedTheme = resolveThemePreference(value);
1244
- if (currentPreset && !isPresetThemeCompatible(currentPreset, resolvedTheme)) {
1245
- const presetName = currentPreset?.name || PDS.currentPreset?.name || PDS.currentConfig?.preset || "current preset";
1246
- console.warn(
1247
- `PDS theme "${resolvedTheme}" not supported by preset "${presetName}".`
1248
- );
1249
- PDS.dispatchEvent(
1250
- new CustomEvent("pds:theme:blocked", {
1251
- detail: { theme: value, resolvedTheme, preset: presetName }
1252
- })
1253
- );
1254
- return;
1255
- }
1256
- if (value === null || value === void 0) {
1257
- localStorage.removeItem(__themeStorageKey);
1258
- } else {
1259
- localStorage.setItem(__themeStorageKey, value);
1260
- }
1261
- __applyResolvedTheme(value);
1262
- __setupSystemListenerIfNeeded(value);
1263
- PDS.dispatchEvent(
1264
- new CustomEvent("pds:theme:changed", {
1265
- detail: { theme: value, source: "api" }
1266
- })
1267
- );
1268
- } catch (e) {
1269
- }
1270
- }
1271
- });
1272
- PDS.defaultEnhancers = [];
1273
- async function start(config) {
1274
- const mode = config && config.mode || "live";
1275
- const { mode: _omit, ...rest } = config || {};
1276
- if (mode === "static")
1277
- return staticInit(rest);
1278
- const assetRootURL = resolveRuntimeAssetRoot(rest, { resolvePublicAssetURL });
1279
- const managerUrl = rest?.managerURL || rest?.public?.managerURL || rest?.manager?.url || new URL("core/pds-manager.js", assetRootURL).href || new URL("./pds-manager.js", import.meta.url).href;
1280
- const { startLive } = await import(managerUrl);
1281
- return startLive(PDS, rest, {
1282
- emitReady: __emitPDSReady,
1283
- emitConfigChanged: __emitPDSConfigChanged,
1284
- applyResolvedTheme: __applyResolvedTheme,
1285
- setupSystemListenerIfNeeded: __setupSystemListenerIfNeeded
1286
- });
1287
- }
1288
- PDS.start = start;
1289
- async function staticInit(config) {
1290
- if (!config || typeof config !== "object") {
1291
- throw new Error(
1292
- "PDS.start({ mode: 'static', ... }) requires a valid configuration object"
1293
- );
1294
- }
1295
- const applyGlobalStyles = config.applyGlobalStyles ?? true;
1296
- const manageTheme = config.manageTheme ?? true;
1297
- const themeStorageKey = config.themeStorageKey ?? "pure-ds-theme";
1298
- let staticPaths = config.staticPaths ?? {};
1299
- const assetRootURL = resolveRuntimeAssetRoot(config, { resolvePublicAssetURL });
1300
- const cfgAuto = config && config.autoDefine || null;
1301
- let autoDefineBaseURL;
1302
- if (cfgAuto && cfgAuto.baseURL) {
1303
- autoDefineBaseURL = ensureTrailingSlash2(
1304
- ensureAbsoluteAssetURL(cfgAuto.baseURL, { preferModule: false })
1305
- );
1306
- } else {
1307
- autoDefineBaseURL = `${assetRootURL}components/`;
1308
- }
1309
- const autoDefinePreload = cfgAuto && Array.isArray(cfgAuto.predefine) && cfgAuto.predefine || [];
1310
- const autoDefineMapper = cfgAuto && typeof cfgAuto.mapper === "function" && cfgAuto.mapper || null;
1311
- try {
1312
- attachFoucListener(PDS);
1313
- const { resolvedTheme } = resolveThemeAndApply({
1314
- manageTheme,
1315
- themeStorageKey,
1316
- applyResolvedTheme: __applyResolvedTheme,
1317
- setupSystemListenerIfNeeded: __setupSystemListenerIfNeeded
1318
- });
1319
- const runtimeConfig = await __loadRuntimeConfig(assetRootURL, config);
1320
- const userEnhancers = Array.isArray(config?.enhancers) ? config.enhancers : config?.enhancers && typeof config.enhancers === "object" ? Object.values(config.enhancers) : [];
1321
- const resolvedConfig = runtimeConfig?.config ? {
1322
- ...runtimeConfig.config,
1323
- ...config,
1324
- design: config?.design || runtimeConfig.config.design,
1325
- preset: config?.preset || runtimeConfig.config.preset
1326
- } : { ...config };
1327
- const baseStaticPaths = {
1328
- tokens: `${assetRootURL}styles/pds-tokens.css.js`,
1329
- primitives: `${assetRootURL}styles/pds-primitives.css.js`,
1330
- components: `${assetRootURL}styles/pds-components.css.js`,
1331
- utilities: `${assetRootURL}styles/pds-utilities.css.js`,
1332
- styles: `${assetRootURL}styles/pds-styles.css.js`
1333
- };
1334
- const runtimePaths = runtimeConfig?.paths || {};
1335
- staticPaths = { ...baseStaticPaths, ...runtimePaths, ...staticPaths };
1336
- PDS.registry.setStaticMode(staticPaths);
1337
- if (applyGlobalStyles && typeof document !== "undefined") {
1338
- try {
1339
- const stylesSheet = await PDS.registry.getStylesheet("styles");
1340
- if (stylesSheet) {
1341
- stylesSheet._pds = true;
1342
- const others = (document.adoptedStyleSheets || []).filter(
1343
- (s) => s._pds !== true
1344
- );
1345
- document.adoptedStyleSheets = [...others, stylesSheet];
1346
- __emitPDSConfigChanged({
1347
- mode: "static",
1348
- source: "static:styles-applied"
1349
- });
1350
- }
1351
- } catch (e) {
1352
- __defaultLog.call(PDS, "warn", "Failed to apply static styles:", e);
1353
- }
1354
- }
1355
- let autoDefiner = null;
1356
- let mergedEnhancers = [];
1357
- try {
1358
- const defaultPDSEnhancers = await __loadDefaultEnhancers();
1359
- const res = await setupAutoDefinerAndEnhancers({
1360
- autoDefineBaseURL,
1361
- autoDefinePreload,
1362
- autoDefineMapper,
1363
- enhancers: userEnhancers,
1364
- autoDefineOverrides: cfgAuto || null,
1365
- autoDefinePreferModule: !(cfgAuto && cfgAuto.baseURL)
1366
- }, { baseEnhancers: defaultPDSEnhancers });
1367
- autoDefiner = res.autoDefiner;
1368
- mergedEnhancers = res.mergedEnhancers || [];
1369
- } catch (error) {
1370
- __defaultLog.call(
1371
- PDS,
1372
- "error",
1373
- "\u274C Failed to initialize AutoDefiner/Enhancers (static):",
1374
- error
1375
- );
1376
- }
1377
- const cloneableConfig = __stripFunctionsForClone(config);
1378
- PDS.currentConfig = Object.freeze({
1379
- mode: "static",
1380
- ...structuredClone(cloneableConfig),
1381
- design: structuredClone(resolvedConfig.design || {}),
1382
- preset: resolvedConfig.preset,
1383
- theme: resolvedTheme,
1384
- enhancers: mergedEnhancers
1385
- });
1386
- __emitPDSReady({
1387
- mode: "static",
1388
- config: resolvedConfig,
1389
- theme: resolvedTheme,
1390
- autoDefiner
1391
- });
1392
- return {
1393
- config: resolvedConfig,
1394
- theme: resolvedTheme,
1395
- autoDefiner
1396
- };
1397
- } catch (error) {
1398
- PDS.dispatchEvent(new CustomEvent("pds:error", { detail: { error } }));
1399
- throw error;
1400
- }
1401
- }
1402
- var applyResolvedTheme = __applyResolvedTheme;
1403
- var setupSystemListenerIfNeeded = __setupSystemListenerIfNeeded;
1404
- export {
1405
- PDS,
1406
- applyResolvedTheme,
1407
- setupSystemListenerIfNeeded
1408
- };
1409
- //# sourceMappingURL=pds.js.map
1
+ var De=Object.defineProperty;var Pe=(e,t)=>{for(var n in t)De(e,n,{get:t[n],enumerable:!0})};var Z=class{constructor(){this._mode="static",this._staticPaths={tokens:"/assets/pds/styles/pds-tokens.css.js",primitives:"/assets/pds/styles/pds-primitives.css.js",components:"/assets/pds/styles/pds-components.css.js",utilities:"/assets/pds/styles/pds-utilities.css.js",styles:"/assets/pds/styles/pds-styles.css.js"}}setLiveMode(){this._mode="live"}setStaticMode(t={}){this._mode="static",this._staticPaths={...this._staticPaths,...t}}async getStylesheet(t){if(this._mode==="live")return null;try{return(await import(this._staticPaths[t]))[t]}catch(n){console.error(`[PDS Registry] Failed to load static ${t}:`,n),console.error(`[PDS Registry] Looking for: ${this._staticPaths[t]}`),console.error("[PDS Registry] Make sure you've run 'npm run pds:build' and configured PDS.start() with the correct static.root path");let r=new CSSStyleSheet;return r.replaceSync("/* Failed to load "+t+" */"),r}}get mode(){return this._mode}get isLive(){return this._mode==="live"}},T=new Z;async function de(e,t=[],n=null){try{let r=n?.primitivesStylesheet?n.primitivesStylesheet:await T.getStylesheet("primitives");e.adoptedStyleSheets=[r,...t]}catch(r){let l=e.host?.tagName?.toLowerCase()||"unknown";console.error(`[PDS Adopter] <${l}> failed to adopt primitives:`,r),e.adoptedStyleSheets=t}}async function pe(e,t=["primitives"],n=[],r=null){try{let s=(await Promise.all(t.map(async c=>{if(r)switch(c){case"tokens":return r.tokensStylesheet;case"primitives":return r.primitivesStylesheet;case"components":return r.componentsStylesheet;case"utilities":return r.utilitiesStylesheet;default:break}return T.getStylesheet(c)}))).filter(c=>c!==null);e.adoptedStyleSheets=[...s,...n]}catch(l){let s=e.host?.tagName?.toLowerCase()||"unknown";console.error(`[PDS Adopter] <${s}> failed to adopt layers:`,l),e.adoptedStyleSheets=n}}function fe(e){let t=new CSSStyleSheet;return t.replaceSync(e),t}var me={FontWeights:{light:300,normal:400,medium:500,semibold:600,bold:700},LineHeights:{tight:1.25,normal:1.5,relaxed:1.75},BorderWidths:{hairline:.5,thin:1,medium:2,thick:3},RadiusSizes:{none:0,small:4,medium:8,large:16,xlarge:24,xxlarge:32},ShadowDepths:{none:"none",light:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",medium:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",deep:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",extreme:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"},TransitionSpeeds:{fast:150,normal:250,slow:350},AnimationEasings:{linear:"linear",ease:"ease","ease-in":"ease-in","ease-out":"ease-out","ease-in-out":"ease-in-out",bounce:"cubic-bezier(0.68, -0.55, 0.265, 1.55)"},TouchTargetSizes:{compact:36,standard:44,comfortable:48,spacious:56},LinkStyles:{inline:"inline",block:"block",button:"button"},FocusStyles:{ring:"ring",outline:"outline",border:"border",glow:"glow"},TabSizes:{compact:2,standard:4,wide:8},SelectIcons:{chevron:"chevron",arrow:"arrow",caret:"caret",none:"none"},IconSizes:{xs:16,sm:20,md:24,lg:32,xl:48,"2xl":64,"3xl":96}};var te={};Pe(te,{deepMerge:()=>he,fragmentFromTemplateLike:()=>Me,isObject:()=>I,parseHTML:()=>ee});function I(e){return e&&typeof e=="object"&&!Array.isArray(e)}function he(e,t){let n={...e};return I(e)&&I(t)&&Object.keys(t).forEach(r=>{I(t[r])?r in e?n[r]=he(e[r],t[r]):Object.assign(n,{[r]:t[r]}):Object.assign(n,{[r]:t[r]})}),n}function Me(e){let t=Array.isArray(e?.strings)?e.strings:[],n=Array.isArray(e?.values)?e.values:[],r=new Set,l=[],s=/(\s)(\.[\w-]+)=\s*$/;for(let a=0;a<t.length;a+=1){let w=t[a]??"",f=w.match(s);if(f&&a<n.length){let g=f[2].slice(1),L=`pds-val-${a}`;w=w.replace(s,`$1data-pds-prop="${g}:${L}"`),r.add(a)}l.push(w),a<n.length&&!r.has(a)&&l.push(`<!--pds-val-${a}-->`)}let c=document.createElement("template");c.innerHTML=l.join("");let S=(a,w)=>{let f=a.parentNode;if(!f)return;if(w==null){f.removeChild(a);return}let b=g=>{if(g!=null){if(g instanceof Node){f.insertBefore(g,a);return}if(Array.isArray(g)){g.forEach(L=>b(L));return}f.insertBefore(document.createTextNode(String(g)),a)}};b(w),f.removeChild(a)},_=document.createTreeWalker(c.content,NodeFilter.SHOW_COMMENT),m=[];for(;_.nextNode();){let a=_.currentNode;a?.nodeValue?.startsWith("pds-val-")&&m.push(a)}return m.forEach(a=>{let w=Number(a.nodeValue.replace("pds-val-",""));S(a,n[w])}),c.content.querySelectorAll("*").forEach(a=>{let w=a.getAttribute("data-pds-prop");if(!w)return;let[f,b]=w.split(":"),g=Number(String(b).replace("pds-val-",""));f&&Number.isInteger(g)&&(a[f]=n[g]),a.removeAttribute("data-pds-prop")}),c.content}function ee(e){return new DOMParser().parseFromString(e,"text/html").body.childNodes}var we="pds",Te=/^([a-z][a-z0-9+\-.]*:)?\/\//i,ye=/^[a-z]:/i;function C(e=""){return e.endsWith("/")?e:`${e}/`}function Ue(e="",t=we){let n=e.replace(/\/+$/,"");return new RegExp(`(?:^|/)${t}$`,"i").test(n)?n:`${n}/${t}`}function ke(e){return e.replace(/^\.\/+/,"")}function Ce(e){return ye.test(e)?e.replace(ye,"").replace(/^\/+/,""):e}function je(e){return e.startsWith("public/")?e.substring(7):e}function N(e,t={}){let n=t.segment||we,r=t.defaultRoot||`/assets/${n}/`,l=e?.public&&e.public?.root||e?.static&&e.static?.root||null;if(!l||typeof l!="string")return C(r);let s=l.trim();return s?(s=s.replace(/\\/g,"/"),s=Ue(s,n),s=C(s),Te.test(s)?s:(s=ke(s),s=Ce(s),s.startsWith("/")||(s=je(s),s.startsWith("/")||(s=`/${s}`),s=s.replace(/\/+/g,(c,S)=>S===0?c:"/")),C(s))):C(r)}async function $e(...e){let t={};e.length&&typeof e[e.length-1]=="object"&&(t=e.pop()||{});let n=e,{baseURL:r,mapper:l=m=>`${m}.js`,onError:s=(m,i)=>console.error(`[defineWebComponents] ${m}:`,i)}=t,c=r?new URL(r,typeof location<"u"?location.href:import.meta.url):new URL("./",import.meta.url),S=m=>m.toLowerCase().replace(/(^|-)([a-z])/g,(i,a,w)=>w.toUpperCase()),_=async m=>{try{if(customElements.get(m))return{tag:m,status:"already-defined"};let i=l(m),w=await import(i instanceof URL?i.href:new URL(i,c).href),f=w?.default??w?.[S(m)];if(!f){if(customElements.get(m))return{tag:m,status:"self-defined"};throw new Error(`No export found for ${m}. Expected default export or named export "${S(m)}".`)}return customElements.get(m)?{tag:m,status:"race-already-defined"}:(customElements.define(m,f),{tag:m,status:"defined"})}catch(i){throw s(m,i),i}};return Promise.all(n.map(_))}var z=class{constructor(t={}){let{baseURL:n,mapper:r,onError:l,predicate:s=()=>!0,attributeModule:c="data-module",root:S=document,scanExisting:_=!0,debounceMs:m=16,observeShadows:i=!0,enhancers:a=[],patchAttachShadow:w=!0}=t,f=new Set,b=new Set,g=new Set,L=new Map,R=new WeakMap,A=new WeakMap,E=0,h=!1,y=null,D=u=>{if(!u||!a.length)return;let p=A.get(u);p||(p=new Set,A.set(u,p));for(let d of a)if(!(!d.selector||!d.run)&&!p.has(d.selector))try{u.matches&&u.matches(d.selector)&&(d.run(u),p.add(d.selector))}catch(v){console.warn(`[AutoDefiner] Error applying enhancer for selector "${d.selector}":`,v)}},k=(u,p)=>{if(!h&&!(!u||!u.includes("-"))&&!customElements.get(u)&&!b.has(u)&&!g.has(u)){if(p&&p.getAttribute){let d=p.getAttribute(c);d&&!L.has(u)&&L.set(u,d)}f.add(u),X()}},X=()=>{E||(E=setTimeout(ce,m))},P=u=>{if(u){if(u.nodeType===1){let p=u,d=p.tagName?.toLowerCase();d&&d.includes("-")&&!customElements.get(d)&&s(d,p)&&k(d,p),D(p),i&&p.shadowRoot&&Y(p.shadowRoot)}u.querySelectorAll&&u.querySelectorAll("*").forEach(p=>{let d=p.tagName?.toLowerCase();d&&d.includes("-")&&!customElements.get(d)&&s(d,p)&&k(d,p),D(p),i&&p.shadowRoot&&Y(p.shadowRoot)})}},Y=u=>{if(!u||R.has(u))return;P(u);let p=new MutationObserver(d=>{for(let v of d)v.addedNodes?.forEach(M=>{P(M)}),v.type==="attributes"&&v.target&&P(v.target)});p.observe(u,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[c,...a.map(d=>d.selector).filter(d=>d.startsWith("data-"))]}),R.set(u,p)};async function ce(){if(clearTimeout(E),E=0,!f.size)return;let u=Array.from(f);f.clear(),u.forEach(p=>b.add(p));try{let p=d=>L.get(d)??(r?r(d):`${d}.js`);await $e(...u,{baseURL:n,mapper:p,onError:(d,v)=>{g.add(d),l?.(d,v)}})}catch{}finally{u.forEach(p=>b.delete(p))}}let le=S===document?document.documentElement:S,ue=new MutationObserver(u=>{for(let p of u)p.addedNodes?.forEach(d=>{P(d)}),p.type==="attributes"&&p.target&&P(p.target)});if(ue.observe(le,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[c,...a.map(u=>u.selector).filter(u=>u.startsWith("data-"))]}),i&&w&&Element.prototype.attachShadow){let u=Element.prototype.attachShadow;Element.prototype.attachShadow=function(d){let v=u.call(this,d);if(d&&d.mode==="open"){Y(v);let M=this.tagName?.toLowerCase();M&&M.includes("-")&&!customElements.get(M)&&k(M,this)}return v},y=()=>Element.prototype.attachShadow=u}return _&&P(le),{stop(){h=!0,ue.disconnect(),y&&y(),E&&(clearTimeout(E),E=0),R.forEach(u=>u.disconnect())},flush:ce}}static async define(...t){let n={};t.length&&typeof t[t.length-1]=="object"&&(n=t.pop()||{});let r=t,{baseURL:l,mapper:s=i=>`${i}.js`,onError:c=(i,a)=>console.error(`[defineWebComponents] ${i}:`,a)}=n,S=l?new URL(l,typeof location<"u"?location.href:import.meta.url):new URL("./",import.meta.url),_=i=>i.toLowerCase().replace(/(^|-)([a-z])/g,(a,w,f)=>f.toUpperCase()),m=async i=>{try{if(customElements.get(i))return{tag:i,status:"already-defined"};let a=s(i),f=await import(a instanceof URL?a.href:new URL(a,S).href),b=f?.default??f?.[_(i)];if(!b){if(customElements.get(i))return{tag:i,status:"self-defined"};throw new Error(`No export found for ${i}. Expected default export or named export "${_(i)}".`)}return customElements.get(i)?{tag:i,status:"race-already-defined"}:(customElements.define(i,b),{tag:i,status:"defined"})}catch(a){throw c(i,a),a}};return Promise.all(r.map(m))}};var Oe=/^[a-z][a-z0-9+\-.]*:\/\//i,j=(()=>{try{return import.meta.url}catch{return}})(),F=e=>typeof e=="string"&&e.length&&!e.endsWith("/")?`${e}/`:e;function W(e,t={}){if(!e||Oe.test(e))return e;let{preferModule:n=!0}=t,r=()=>{if(!j)return null;try{return new URL(e,j).href}catch{return null}},l=()=>{if(typeof window>"u"||!window.location?.origin)return null;try{return new URL(e,window.location.origin).href}catch{return null}};return(n?r()||l():l()||r())||e}var ge=(()=>{if(j)try{let e=new URL(j);if(/\/public\/assets\/js\//.test(e.pathname))return new URL("../pds/",j).href}catch{return}})(),Ee=!1;function Se(e){Ee||typeof document>"u"||(Ee=!0,e.addEventListener("pds:ready",t=>{let n=t.detail?.mode;n&&document.documentElement.classList.add(`pds-${n}`,"pds-ready")}))}function be({manageTheme:e,themeStorageKey:t,applyResolvedTheme:n,setupSystemListenerIfNeeded:r}){let l="light",s=null;if(e&&typeof window<"u"){try{s=localStorage.getItem(t)||null}catch{s=null}try{n?.(s),r?.(s)}catch{}s?s==="system"?l=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":l=s:l=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}return{resolvedTheme:l,storedTheme:s}}function B(e,{resolvePublicAssetURL:t}){let n=!!(e?.public?.root||e?.static?.root),r=t(e);return!n&&ge&&(r=ge),F(W(r))}async function Le(e,{baseEnhancers:t=[]}={}){let{autoDefineBaseURL:n="/auto-define/",autoDefinePreload:r=[],autoDefineMapper:l=null,enhancers:s=[],autoDefineOverrides:c=null,autoDefinePreferModule:S=!0}=e,_=(()=>{let i=new Map;return(t||[]).forEach(a=>i.set(a.selector,a)),(s||[]).forEach(a=>i.set(a.selector,a)),Array.from(i.values())})(),m=null;if(typeof window<"u"&&typeof document<"u"){let i=z,a=h=>{switch(h){case"pds-tabpanel":return"pds-tabstrip.js";default:return`${h}.js`}},{mapper:w,enhancers:f,...b}=c&&typeof c=="object"?c:{},g=f?Array.isArray(f)?f:typeof f=="object"?Object.values(f):[]:[],L=(()=>{let h=new Map;return(_||[]).forEach(y=>{y?.selector&&h.set(y.selector,y)}),(g||[]).forEach(y=>{if(!y?.selector)return;let D=h.get(y.selector)||null;h.set(y.selector,{...D||{},...y,run:typeof y?.run=="function"?y.run:D?.run})}),Array.from(h.values())})(),A={baseURL:n&&F(W(n,{preferModule:S})),predefine:r,scanExisting:!0,observeShadows:!0,patchAttachShadow:!0,debounceMs:16,enhancers:L,onError:(h,y)=>{if(typeof h=="string"&&h.startsWith("pds-")){let k=["pds-form","pds-drawer"].includes(h),X=y?.message?.includes("#pds/lit")||y?.message?.includes("Failed to resolve module specifier");k&&X?console.error(`\u274C PDS component <${h}> requires Lit but #pds/lit is not in import map.
2
+ See: https://github.com/Pure-Web-Foundation/pure-ds/blob/main/readme.md#lit-components-not-working`):console.warn(`\u26A0\uFE0F PDS component <${h}> not found. Assets may not be installed.`)}else console.error(`\u274C Auto-define error for <${h}>:`,y)},...b,mapper:h=>{if(customElements.get(h))return null;if(typeof l=="function")try{let y=l(h);return y===void 0?a(h):y}catch(y){return console.warn("Custom autoDefine.mapper error; falling back to default:",y?.message||y),a(h)}return a(h)}};if(!!(typeof window<"u"&&window.__PDS_DEBUG_AUTODEFINE__||c?.debugAutoDefine)){let h=L.filter(y=>typeof y?.run!="function").map(y=>y?.selector).filter(Boolean);console.info("[PDS][AutoDefiner] enhancer summary",{baseEnhancers:(t||[]).length,userEnhancers:(s||[]).length,overrideEnhancers:g.length,resolvedEnhancers:L.length,missingRun:h})}m=new i(A),r.length>0&&typeof i.define=="function"&&await i.define(...r,{baseURL:n,mapper:A.mapper,onError:A.onError})}return{autoDefiner:m,mergedEnhancers:_}}var ne=["light","dark"],re=new Set(ne);function Ie(e){let n=(Array.isArray(e?.themes)?e.themes.map(r=>String(r).toLowerCase()):ne).filter(r=>re.has(r));return n.length?n:ne}function se(e,{preferDocument:t=!0}={}){let n=String(e||"").toLowerCase();if(re.has(n))return n;if(t&&typeof document<"u"){let r=document.documentElement?.getAttribute("data-theme");if(re.has(r))return r}return typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function _e(e,t){let n=se(t);return Ie(e).includes(n)}var ae=class extends EventTarget{},o=new ae;o.initializing=!1;o.currentPreset=null;o.debug=!1;var q=null,V=null,H=null,G=null;function K(e,t){return t&&typeof t=="string"?t:`${B(o.currentConfig||{},{resolvePublicAssetURL:N})}core/${e}`}async function Ne(){return Array.isArray(o.defaultEnhancers)&&o.defaultEnhancers.length>0?o.defaultEnhancers:(G||(G=import(K("pds-enhancers.js",o.currentConfig?.enhancersURL)).then(t=>{let n=Array.isArray(t?.defaultPDSEnhancers)?t.defaultPDSEnhancers:[];return o.defaultEnhancers=n,n}).catch(t=>{throw G=null,t})),G)}async function ze(){return typeof o.ask=="function"&&o.ask!==Ae?o.ask:(V||(V=import(K("pds-ask.js",o.currentConfig?.askURL)).then(t=>{let n=t?.ask;if(typeof n!="function")throw new Error("Failed to load ask helper");return o.ask=n,n}).catch(t=>{throw V=null,t})),V)}async function O(){return typeof o.toast=="function"&&o.toast!==U?o.toast:(H||(H=import(K("pds-toast.js",o.currentConfig?.toastURL)).then(t=>{let n=t?.toast;if(typeof n!="function")throw new Error("Failed to load toast helper");return o.toast=n,n}).catch(t=>{throw H=null,t})),H)}async function Ae(...e){return(await ze())(...e)}async function U(...e){return(await O())(...e)}U.success=async(...e)=>(await O()).success(...e);U.error=async(...e)=>(await O()).error(...e);U.warning=async(...e)=>(await O()).warning(...e);U.info=async(...e)=>(await O()).info(...e);var ve=function(e="log",t,...n){let r=!!(o.registry&&!o.registry.isLive),l=(this?.debug||this?.design?.debug||o.debug||!1)===!0;if(r){if(!o.debug)return}else if(!l&&e!=="error"&&e!=="warn")return;let s=console[e]||console.log;n.length>0?s(t,...n):s(t)};function ie(e){if(e==null)return e;if(typeof e=="function")return;if(typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>ie(n)).filter(n=>n!==void 0);let t={};for(let[n,r]of Object.entries(e)){let l=ie(r);l!==void 0&&(t[n]=l)}return t}async function Fe(e,t={}){if(t?.runtimeConfig===!1||typeof fetch!="function")return null;let n=t?.runtimeConfigURL||`${e}pds-runtime-config.json`;try{let r=await fetch(n,{cache:"no-store"});return r.ok?await r.json():null}catch{return null}}o.registry=T;o.enums=me;o.adoptLayers=pe;o.adoptPrimitives=de;o.parse=ee;o.createStylesheet=fe;o.isLiveMode=()=>T.isLive;o.ask=Ae;o.toast=U;o.common=te;o.AutoComplete=null;o.loadAutoComplete=async()=>{if(o.AutoComplete&&typeof o.AutoComplete.connect=="function")return o.AutoComplete;let e=K("pds-autocomplete.js",o.currentConfig?.autoCompleteURL);return q||(q=import(e).then(t=>{let n=t?.AutoComplete||t?.default?.AutoComplete||t?.default||null;if(!n)throw new Error("AutoComplete export not found in module");return o.AutoComplete=n,n}).catch(t=>{throw q=null,t})),q};function Re(e){let t=typeof CustomEvent=="function";try{let n=t?new CustomEvent("pds:ready",{detail:e}):new Event("pds:ready");o.dispatchEvent(n)}catch{}if(typeof document<"u")if(t){let n={detail:e,bubbles:!0,composed:!0};try{document.dispatchEvent(new CustomEvent("pds:ready",n))}catch{}try{document.dispatchEvent(new CustomEvent("pds-ready",n))}catch{}}else{try{document.dispatchEvent(new Event("pds:ready"))}catch{}try{document.dispatchEvent(new Event("pds-ready"))}catch{}}}function xe(e={}){let t=typeof CustomEvent=="function",n={at:Date.now(),...e};try{let r=t?new CustomEvent("pds:config-changed",{detail:n}):new Event("pds:config-changed");o.dispatchEvent(r)}catch{}if(typeof document<"u")if(t){let r={detail:n,bubbles:!0,composed:!0};try{document.dispatchEvent(new CustomEvent("pds:config-changed",r))}catch{}}else try{document.dispatchEvent(new Event("pds:config-changed"))}catch{}}var oe="pure-ds-theme",x=null,$=null;function Q(e){try{if(typeof document>"u")return;let t="light";e?e==="system"?t=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":t=e:t=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",document.documentElement.setAttribute("data-theme",t)}catch{}}function J(e){try{if(x&&$){try{typeof x.removeEventListener=="function"?x.removeEventListener("change",$):typeof x.removeListener=="function"&&x.removeListener($)}catch{}x=null,$=null}if(e==="system"&&typeof window<"u"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=r=>{let l=r?.matches===void 0?t.matches:r.matches;try{let s=l?"dark":"light";document.documentElement.setAttribute("data-theme",s),o.dispatchEvent(new CustomEvent("pds:theme:changed",{detail:{theme:s,source:"system"}}))}catch{}};x=t,$=n,typeof t.addEventListener=="function"?t.addEventListener("change",n):typeof t.addListener=="function"&&t.addListener(n)}}catch{}}Object.defineProperty(o,"theme",{get(){try{return typeof window>"u"?null:localStorage.getItem(oe)||null}catch{return null}},set(e){try{if(typeof window>"u")return;let t=o.currentConfig?.design||null,n=se(e);if(t&&!_e(t,n)){let r=t?.name||o.currentPreset?.name||o.currentConfig?.preset||"current preset";console.warn(`PDS theme "${n}" not supported by preset "${r}".`),o.dispatchEvent(new CustomEvent("pds:theme:blocked",{detail:{theme:e,resolvedTheme:n,preset:r}}));return}e==null?localStorage.removeItem(oe):localStorage.setItem(oe,e),Q(e),J(e),o.dispatchEvent(new CustomEvent("pds:theme:changed",{detail:{theme:e,source:"api"}}))}catch{}}});o.defaultEnhancers=[];async function We(e){let t=e&&e.mode||"live",{mode:n,...r}=e||{};if(t==="static")return Be(r);let l=B(r,{resolvePublicAssetURL:N}),s=r?.managerURL||r?.public?.managerURL||r?.manager?.url||new URL("core/pds-manager.js",l).href||new URL("./pds-manager.js",import.meta.url).href,{startLive:c}=await import(s);return c(o,r,{emitReady:Re,emitConfigChanged:xe,applyResolvedTheme:Q,setupSystemListenerIfNeeded:J})}o.start=We;async function Be(e){if(!e||typeof e!="object")throw new Error("PDS.start({ mode: 'static', ... }) requires a valid configuration object");let t=e.applyGlobalStyles??!0,n=e.manageTheme??!0,r=e.themeStorageKey??"pure-ds-theme",l=e.staticPaths??{},s=B(e,{resolvePublicAssetURL:N}),c=e&&e.autoDefine||null,S;c&&c.baseURL?S=F(W(c.baseURL,{preferModule:!1})):S=`${s}components/`;let _=c&&Array.isArray(c.predefine)&&c.predefine||[],m=c&&typeof c.mapper=="function"&&c.mapper||null;try{Se(o);let{resolvedTheme:i}=be({manageTheme:n,themeStorageKey:r,applyResolvedTheme:Q,setupSystemListenerIfNeeded:J}),a=await Fe(s,e),w=Array.isArray(e?.enhancers)?e.enhancers:e?.enhancers&&typeof e.enhancers=="object"?Object.values(e.enhancers):[],f=a?.config?{...a.config,...e,design:e?.design||a.config.design,preset:e?.preset||a.config.preset}:{...e},b={tokens:`${s}styles/pds-tokens.css.js`,primitives:`${s}styles/pds-primitives.css.js`,components:`${s}styles/pds-components.css.js`,utilities:`${s}styles/pds-utilities.css.js`,styles:`${s}styles/pds-styles.css.js`},g=a?.paths||{};if(l={...b,...g,...l},o.registry.setStaticMode(l),t&&typeof document<"u")try{let E=await o.registry.getStylesheet("styles");if(E){E._pds=!0;let h=(document.adoptedStyleSheets||[]).filter(y=>y._pds!==!0);document.adoptedStyleSheets=[...h,E],xe({mode:"static",source:"static:styles-applied"})}}catch(E){ve.call(o,"warn","Failed to apply static styles:",E)}let L=null,R=[];try{let E=await Ne(),h=await Le({autoDefineBaseURL:S,autoDefinePreload:_,autoDefineMapper:m,enhancers:w,autoDefineOverrides:c||null,autoDefinePreferModule:!(c&&c.baseURL)},{baseEnhancers:E});L=h.autoDefiner,R=h.mergedEnhancers||[]}catch(E){ve.call(o,"error","\u274C Failed to initialize AutoDefiner/Enhancers (static):",E)}let A=ie(e);return o.currentConfig=Object.freeze({mode:"static",...structuredClone(A),design:structuredClone(f.design||{}),preset:f.preset,theme:i,enhancers:R}),Re({mode:"static",config:f,theme:i,autoDefiner:L}),{config:f,theme:i,autoDefiner:L}}catch(i){throw o.dispatchEvent(new CustomEvent("pds:error",{detail:{error:i}})),i}}var at=Q,it=J;export{o as PDS,at as applyResolvedTheme,it as setupSystemListenerIfNeeded};