@lokascript/core 1.2.1 → 1.3.0

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lokascript/core",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "description": "Multilingual, tree-shakeable hyperscript",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -108,6 +108,8 @@ import { createRenderCommand } from '../commands/templates/render';
108
108
 
109
109
  // NO PARSER IMPORT - uses @lokascript/semantic package instead
110
110
 
111
+ import { debug } from '../utils/debug';
112
+
111
113
  // =============================================================================
112
114
  // Semantic Module Access (from browser global)
113
115
  // =============================================================================
@@ -392,14 +394,188 @@ const api = {
392
394
  * Bundle type identifier
393
395
  */
394
396
  bundleType: 'multilingual' as const,
397
+
398
+ /**
399
+ * Manually process a DOM element or the entire document.
400
+ * Uses the semantic parser to compile _ attributes.
401
+ */
402
+ processNode: async (element: Element | Document): Promise<void> => {
403
+ if (element === document || element === document.documentElement) {
404
+ await scanAndProcessAll();
405
+ } else if (element instanceof HTMLElement) {
406
+ await processElementSemantic(element);
407
+ }
408
+ },
409
+
410
+ /**
411
+ * Alias for processNode.
412
+ */
413
+ process: async (element: Element | Document): Promise<void> => {
414
+ return api.processNode(element);
415
+ },
395
416
  };
396
417
 
418
+ // =============================================================================
419
+ // DOM Attribute Auto-Processing (using semantic parser path)
420
+ // =============================================================================
421
+
422
+ const processedElements = new WeakSet<HTMLElement>();
423
+ let domObserver: MutationObserver | null = null;
424
+
425
+ /**
426
+ * Detect language for an element by checking data-lang, lang attributes,
427
+ * or walking up the DOM tree. Falls back to 'en'.
428
+ */
429
+ function detectLanguage(element: HTMLElement): string {
430
+ // Check data-lang first (explicit lokascript language override)
431
+ const dataLang = element.getAttribute('data-lang');
432
+ if (dataLang && SUPPORTED_LANGUAGES.includes(dataLang as any)) {
433
+ return dataLang;
434
+ }
435
+
436
+ // Walk up the DOM checking lang attributes
437
+ let current: HTMLElement | null = element;
438
+ while (current) {
439
+ const lang = current.getAttribute('lang');
440
+ if (lang) {
441
+ // Normalize lang attribute (e.g., "ja-JP" → "ja")
442
+ const code = lang.split('-')[0].toLowerCase();
443
+ if (SUPPORTED_LANGUAGES.includes(code as any)) {
444
+ return code;
445
+ }
446
+ }
447
+ current = current.parentElement;
448
+ }
449
+
450
+ return 'en';
451
+ }
452
+
453
+ /**
454
+ * Process a single element's _ attribute using the semantic parser.
455
+ */
456
+ async function processElementSemantic(element: HTMLElement): Promise<void> {
457
+ if (processedElements.has(element)) return;
458
+
459
+ const code = element.getAttribute('_');
460
+ if (!code) return;
461
+
462
+ try {
463
+ const lang = detectLanguage(element);
464
+ debug.parse(`ATTR-ML: Processing element with lang="${lang}":`, code.substring(0, 60));
465
+
466
+ const semantic = getSemanticModule();
467
+ const analyzer = semantic.createSemanticAnalyzer();
468
+ const result = analyzer.analyze(code, lang);
469
+
470
+ if (result.confidence < 0.5 || !result.node) {
471
+ debug.parse(`ATTR-ML: Low confidence (${result.confidence.toFixed(2)}) for: ${code}`);
472
+ return;
473
+ }
474
+
475
+ const buildResult = semantic.buildAST(result.node);
476
+ const ctx = ensureContext(element);
477
+ await runtime.execute(buildResult.ast as unknown as ASTNode, ctx);
478
+
479
+ processedElements.add(element);
480
+ debug.parse(`ATTR-ML: Successfully processed element`);
481
+ } catch (error) {
482
+ debug.parse('ATTR-ML: Error processing element:', (error as Error).message);
483
+ }
484
+ }
485
+
486
+ /**
487
+ * Scan and process all elements with _ attributes.
488
+ */
489
+ async function scanAndProcessAll(): Promise<void> {
490
+ const elements = document.querySelectorAll('[_]');
491
+ debug.parse(`ATTR-ML: Found ${elements.length} elements with _ attributes`);
492
+
493
+ const promises: Promise<void>[] = [];
494
+ elements.forEach(el => {
495
+ if (el instanceof HTMLElement) {
496
+ promises.push(processElementSemantic(el));
497
+ }
498
+ });
499
+ await Promise.all(promises);
500
+
501
+ debug.parse('ATTR-ML: All elements processed');
502
+
503
+ // Dispatch ready event
504
+ if (typeof window !== 'undefined') {
505
+ window.dispatchEvent(
506
+ new CustomEvent('lokascript:initialized', {
507
+ detail: { elementsProcessed: elements.length },
508
+ })
509
+ );
510
+ }
511
+ }
512
+
513
+ /**
514
+ * Set up MutationObserver to process dynamically added elements.
515
+ */
516
+ function setupMutationObserver(): void {
517
+ if (typeof MutationObserver === 'undefined') return;
518
+
519
+ domObserver = new MutationObserver(mutations => {
520
+ for (const mutation of mutations) {
521
+ mutation.addedNodes.forEach(node => {
522
+ if (node.nodeType !== Node.ELEMENT_NODE) return;
523
+ const element = node as HTMLElement;
524
+
525
+ // Process the element itself
526
+ if (element.getAttribute?.('_')) {
527
+ processElementSemantic(element).catch(err => {
528
+ debug.parse('ATTR-ML: Error processing dynamic element:', err);
529
+ });
530
+ }
531
+
532
+ // Process descendants with _ attributes
533
+ const descendants = element.querySelectorAll?.('[_]');
534
+ descendants?.forEach(desc => {
535
+ if (desc instanceof HTMLElement) {
536
+ processElementSemantic(desc).catch(err => {
537
+ debug.parse('ATTR-ML: Error processing dynamic descendant:', err);
538
+ });
539
+ }
540
+ });
541
+ });
542
+ }
543
+ });
544
+
545
+ domObserver.observe(document.body, { childList: true, subtree: true });
546
+ }
547
+
397
548
  // =============================================================================
398
549
  // Global Export
399
550
  // =============================================================================
400
551
 
401
552
  if (typeof window !== 'undefined') {
402
- (window as any).hyperfixi = api;
553
+ // Primary: lokascript (new name)
554
+ (window as any).lokascript = api;
555
+
556
+ // Compatibility: hyperfixi (deprecated alias)
557
+ if (typeof (window as any).hyperfixi === 'undefined') {
558
+ Object.defineProperty(window, 'hyperfixi', {
559
+ get() {
560
+ console.warn(
561
+ '[DEPRECATED] window.hyperfixi is deprecated and will be removed in v2.0.0. ' +
562
+ 'Please use window.lokascript instead.'
563
+ );
564
+ return (window as any).lokascript;
565
+ },
566
+ enumerable: true,
567
+ configurable: true,
568
+ });
569
+ }
570
+
571
+ // Auto-process _ attributes when DOM is ready
572
+ if (document.readyState === 'loading') {
573
+ document.addEventListener('DOMContentLoaded', () => {
574
+ scanAndProcessAll().then(() => setupMutationObserver());
575
+ });
576
+ } else {
577
+ scanAndProcessAll().then(() => setupMutationObserver());
578
+ }
403
579
  }
404
580
 
405
581
  export default api;