@adartem/adlib-attributes 0.0.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/LICENSE +21 -0
- package/README.md +212 -0
- package/attributes.js +2 -0
- package/attributes.js.map +1 -0
- package/dist/attributes.js +2 -0
- package/dist/attributes.js.map +1 -0
- package/dist/core/index.cjs +201 -0
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.js +195 -0
- package/dist/core/index.js.map +1 -0
- package/dist/index.cjs +446 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +439 -0
- package/dist/index.js.map +1 -0
- package/package.json +68 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var adlibUtils = require('@adartem/adlib-utils');
|
|
6
|
+
|
|
7
|
+
// src/core/index.ts
|
|
8
|
+
function createLogger(debug = false) {
|
|
9
|
+
return {
|
|
10
|
+
debug: (...args) => {
|
|
11
|
+
if (!debug) return;
|
|
12
|
+
console.warn("[debug]", ...args);
|
|
13
|
+
},
|
|
14
|
+
warn: (...args) => {
|
|
15
|
+
console.warn("[warn]", ...args);
|
|
16
|
+
},
|
|
17
|
+
error: (...args) => {
|
|
18
|
+
console.error("[error]", ...args);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function isElement(value) {
|
|
23
|
+
return typeof Element !== "undefined" && value instanceof Element;
|
|
24
|
+
}
|
|
25
|
+
function safeMatches(el, selector) {
|
|
26
|
+
try {
|
|
27
|
+
return el.matches(selector);
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function findClosestMatching(target, selector) {
|
|
33
|
+
let cur = target;
|
|
34
|
+
while (cur) {
|
|
35
|
+
if (isElement(cur) && safeMatches(cur, selector)) return cur;
|
|
36
|
+
cur = isElement(cur) ? cur.parentElement : null;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
function createDelegatedListener(info) {
|
|
41
|
+
return (e) => {
|
|
42
|
+
const entries = info.entries.slice();
|
|
43
|
+
for (const entry of entries) {
|
|
44
|
+
const matched = findClosestMatching(e.target, entry.selector);
|
|
45
|
+
if (!matched) continue;
|
|
46
|
+
entry.handler(e, matched);
|
|
47
|
+
if (entry.once) {
|
|
48
|
+
const idx = info.entries.indexOf(entry);
|
|
49
|
+
if (idx >= 0) info.entries.splice(idx, 1);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function resolveObserverTarget(root) {
|
|
55
|
+
if (root instanceof Document) return root.documentElement ?? root;
|
|
56
|
+
return root;
|
|
57
|
+
}
|
|
58
|
+
function createCore(options = {}) {
|
|
59
|
+
const root = options.root ?? document;
|
|
60
|
+
const logger = createLogger(!!options.debug);
|
|
61
|
+
const defs = /* @__PURE__ */ new Map();
|
|
62
|
+
const instances = /* @__PURE__ */ new Map();
|
|
63
|
+
const listenersByType = /* @__PURE__ */ new Map();
|
|
64
|
+
function on(type, selector, handler, opts = {}) {
|
|
65
|
+
const capture = !!opts.capture;
|
|
66
|
+
const passive = !!opts.passive;
|
|
67
|
+
const existing = listenersByType.get(type);
|
|
68
|
+
if (existing) {
|
|
69
|
+
existing.entries.push({ selector, handler, once: !!opts.once });
|
|
70
|
+
return () => {
|
|
71
|
+
const idx = existing.entries.findIndex((e) => e.selector === selector && e.handler === handler);
|
|
72
|
+
if (idx >= 0) existing.entries.splice(idx, 1);
|
|
73
|
+
if (existing.entries.length === 0) {
|
|
74
|
+
root.removeEventListener(type, existing.listener, { capture: existing.capture });
|
|
75
|
+
listenersByType.delete(type);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
const info = {
|
|
80
|
+
capture,
|
|
81
|
+
passive,
|
|
82
|
+
entries: [{ selector, handler, once: !!opts.once }],
|
|
83
|
+
listener: () => {
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const listener = createDelegatedListener(info);
|
|
87
|
+
info.listener = listener;
|
|
88
|
+
listenersByType.set(type, info);
|
|
89
|
+
root.addEventListener(type, listener, { capture, passive });
|
|
90
|
+
return () => {
|
|
91
|
+
const cur = listenersByType.get(type);
|
|
92
|
+
if (!cur) return;
|
|
93
|
+
const idx = cur.entries.findIndex((e) => e.selector === selector && e.handler === handler);
|
|
94
|
+
if (idx >= 0) cur.entries.splice(idx, 1);
|
|
95
|
+
if (cur.entries.length === 0) {
|
|
96
|
+
root.removeEventListener(type, cur.listener, { capture: cur.capture });
|
|
97
|
+
listenersByType.delete(type);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function emit(el, name, detail) {
|
|
102
|
+
const ev = new CustomEvent(name, { detail, bubbles: true });
|
|
103
|
+
el.dispatchEvent(ev);
|
|
104
|
+
}
|
|
105
|
+
function register(def) {
|
|
106
|
+
defs.set(def.key, def);
|
|
107
|
+
}
|
|
108
|
+
function unregister(key) {
|
|
109
|
+
defs.delete(key);
|
|
110
|
+
}
|
|
111
|
+
function mount(key, _root) {
|
|
112
|
+
const def = defs.get(key);
|
|
113
|
+
if (!def) return;
|
|
114
|
+
if (instances.has(key)) return;
|
|
115
|
+
const inst = def.init(api);
|
|
116
|
+
instances.set(key, inst);
|
|
117
|
+
}
|
|
118
|
+
function unmount(key) {
|
|
119
|
+
const inst = instances.get(key);
|
|
120
|
+
if (!inst) return;
|
|
121
|
+
inst.destroy();
|
|
122
|
+
instances.delete(key);
|
|
123
|
+
}
|
|
124
|
+
function mountAll(_root) {
|
|
125
|
+
for (const key of defs.keys()) mount(key);
|
|
126
|
+
}
|
|
127
|
+
function unmountAll() {
|
|
128
|
+
for (const key of instances.keys()) unmount(key);
|
|
129
|
+
}
|
|
130
|
+
let observer = null;
|
|
131
|
+
function observe(observedRoot = root) {
|
|
132
|
+
if (observer) return () => {
|
|
133
|
+
};
|
|
134
|
+
observer = new MutationObserver((_mutations) => {
|
|
135
|
+
});
|
|
136
|
+
observer.observe(resolveObserverTarget(observedRoot), {
|
|
137
|
+
subtree: true,
|
|
138
|
+
childList: true,
|
|
139
|
+
attributes: false
|
|
140
|
+
});
|
|
141
|
+
return () => stopObserving();
|
|
142
|
+
}
|
|
143
|
+
function stopObserving() {
|
|
144
|
+
if (!observer) return;
|
|
145
|
+
observer.disconnect();
|
|
146
|
+
observer = null;
|
|
147
|
+
}
|
|
148
|
+
function destroy() {
|
|
149
|
+
stopObserving();
|
|
150
|
+
unmountAll();
|
|
151
|
+
for (const [type, info] of listenersByType.entries()) {
|
|
152
|
+
root.removeEventListener(type, info.listener, { capture: info.capture });
|
|
153
|
+
}
|
|
154
|
+
listenersByType.clear();
|
|
155
|
+
defs.clear();
|
|
156
|
+
instances.clear();
|
|
157
|
+
}
|
|
158
|
+
function getLogger() {
|
|
159
|
+
return logger;
|
|
160
|
+
}
|
|
161
|
+
const api = {
|
|
162
|
+
on,
|
|
163
|
+
emit,
|
|
164
|
+
register,
|
|
165
|
+
unregister,
|
|
166
|
+
mount,
|
|
167
|
+
unmount,
|
|
168
|
+
mountAll,
|
|
169
|
+
unmountAll,
|
|
170
|
+
observe,
|
|
171
|
+
stopObserving,
|
|
172
|
+
destroy,
|
|
173
|
+
getLogger
|
|
174
|
+
};
|
|
175
|
+
return api;
|
|
176
|
+
}
|
|
177
|
+
var singleton = null;
|
|
178
|
+
function getCoreSingleton(options = {}) {
|
|
179
|
+
if (singleton) return singleton;
|
|
180
|
+
singleton = createCore({ ...options });
|
|
181
|
+
const shouldAutoMount = options.autoMount ?? true;
|
|
182
|
+
if (shouldAutoMount && typeof document !== "undefined") {
|
|
183
|
+
if (document.readyState === "loading") {
|
|
184
|
+
document.addEventListener(
|
|
185
|
+
"DOMContentLoaded",
|
|
186
|
+
() => {
|
|
187
|
+
singleton?.mountAll();
|
|
188
|
+
},
|
|
189
|
+
{ once: true }
|
|
190
|
+
);
|
|
191
|
+
} else {
|
|
192
|
+
singleton.mountAll();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return singleton;
|
|
196
|
+
}
|
|
197
|
+
var core_default = createCore;
|
|
198
|
+
|
|
199
|
+
// src/runtime/module-map.ts
|
|
200
|
+
function normalizeOrigin(origin) {
|
|
201
|
+
return origin.trim().replace(/\/+$/, "");
|
|
202
|
+
}
|
|
203
|
+
function resolveOrigin(config) {
|
|
204
|
+
return normalizeOrigin(config.base ?? config.registry);
|
|
205
|
+
}
|
|
206
|
+
function resolveVersion(config) {
|
|
207
|
+
const v = (config.version ?? "").trim();
|
|
208
|
+
return v || "latest";
|
|
209
|
+
}
|
|
210
|
+
function makeEsmImportPath(origin, pkgName, version) {
|
|
211
|
+
return `${origin}/@adartem/${pkgName}@${version}/dist/index.js`;
|
|
212
|
+
}
|
|
213
|
+
var PACKAGE_BY_KEY = {
|
|
214
|
+
"ad-click": "ad-click"
|
|
215
|
+
};
|
|
216
|
+
function getImportPathForModule(key, config) {
|
|
217
|
+
const origin = resolveOrigin(config);
|
|
218
|
+
const version = resolveVersion(config);
|
|
219
|
+
const pkgName = PACKAGE_BY_KEY[key];
|
|
220
|
+
if (!pkgName) return null;
|
|
221
|
+
return makeEsmImportPath(origin, pkgName, version);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// src/runtime/runtime.ts
|
|
225
|
+
var DEFAULT_REGISTRY = "https://cdn.jsdelivr.net/npm";
|
|
226
|
+
function stateOf(modules, key) {
|
|
227
|
+
return modules[key] ?? (modules[key] = { key, status: "idle" });
|
|
228
|
+
}
|
|
229
|
+
function isReadyOrError(s) {
|
|
230
|
+
return s.status === "ready" || s.status === "error";
|
|
231
|
+
}
|
|
232
|
+
function toError(err) {
|
|
233
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
234
|
+
}
|
|
235
|
+
function normalizeUrlBase(value) {
|
|
236
|
+
const v = (value ?? "").trim();
|
|
237
|
+
if (!v) return void 0;
|
|
238
|
+
return v.replace(/\/+$/, "");
|
|
239
|
+
}
|
|
240
|
+
function resolveConfig(options) {
|
|
241
|
+
const registry = normalizeUrlBase(options.config?.registry) ?? DEFAULT_REGISTRY;
|
|
242
|
+
const version = (options.config?.version ?? options.version).trim() || options.version;
|
|
243
|
+
const out = { registry, version };
|
|
244
|
+
const base = normalizeUrlBase(options.config?.base);
|
|
245
|
+
if (base) out.base = base;
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
function toModuleDefinition(mod, expectedKey) {
|
|
249
|
+
const candidate = (() => {
|
|
250
|
+
if (mod && typeof mod === "object") {
|
|
251
|
+
const record = mod;
|
|
252
|
+
return record.default ?? mod;
|
|
253
|
+
}
|
|
254
|
+
return mod;
|
|
255
|
+
})();
|
|
256
|
+
if (!candidate || typeof candidate !== "object") {
|
|
257
|
+
throw new Error(`Invalid module definition for ${expectedKey}`);
|
|
258
|
+
}
|
|
259
|
+
const def = candidate;
|
|
260
|
+
if (typeof def.key !== "string" || typeof def.init !== "function") {
|
|
261
|
+
throw new Error(`Invalid module definition for ${expectedKey}`);
|
|
262
|
+
}
|
|
263
|
+
if (def.key !== expectedKey) {
|
|
264
|
+
throw new Error(`Module key mismatch: expected "${expectedKey}", got "${def.key}"`);
|
|
265
|
+
}
|
|
266
|
+
return def;
|
|
267
|
+
}
|
|
268
|
+
function createRuntime(options) {
|
|
269
|
+
const debug = options.debug ?? false;
|
|
270
|
+
const auto = options.auto ?? false;
|
|
271
|
+
const ownsCore = options.core == null;
|
|
272
|
+
const core = options.core ?? createCore({
|
|
273
|
+
debug});
|
|
274
|
+
const logger = core.getLogger();
|
|
275
|
+
const config = resolveConfig(options);
|
|
276
|
+
const modules = {};
|
|
277
|
+
const queue = [];
|
|
278
|
+
let observer = null;
|
|
279
|
+
function log(...args) {
|
|
280
|
+
if (!debug) return;
|
|
281
|
+
logger.debug("[AdLib Runtime]", ...args);
|
|
282
|
+
}
|
|
283
|
+
function logError(...args) {
|
|
284
|
+
logger.error("[AdLib Runtime]", ...args);
|
|
285
|
+
}
|
|
286
|
+
function flush(key, st) {
|
|
287
|
+
for (let i = queue.length - 1; i >= 0; i--) {
|
|
288
|
+
const entry = queue[i];
|
|
289
|
+
if (!entry) continue;
|
|
290
|
+
if (entry.key === key) {
|
|
291
|
+
queue.splice(i, 1);
|
|
292
|
+
try {
|
|
293
|
+
entry.cb(st);
|
|
294
|
+
} catch (e) {
|
|
295
|
+
logError("push callback failed", key, e);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
function destroyModule(key) {
|
|
301
|
+
const st = modules[key];
|
|
302
|
+
if (!st) return;
|
|
303
|
+
try {
|
|
304
|
+
st.instance?.destroy?.();
|
|
305
|
+
} catch (e) {
|
|
306
|
+
logError("destroyModule failed", key, e);
|
|
307
|
+
}
|
|
308
|
+
delete st.instance;
|
|
309
|
+
delete st.def;
|
|
310
|
+
delete st.error;
|
|
311
|
+
delete st.promise;
|
|
312
|
+
st.status = "idle";
|
|
313
|
+
}
|
|
314
|
+
async function load(key) {
|
|
315
|
+
const st = stateOf(modules, key);
|
|
316
|
+
if (st.status === "ready") return st;
|
|
317
|
+
if (st.status === "error") return st;
|
|
318
|
+
if (st.status === "loading" && st.promise) return st.promise;
|
|
319
|
+
const importPath = getImportPathForModule(key, config);
|
|
320
|
+
if (!importPath) {
|
|
321
|
+
st.status = "error";
|
|
322
|
+
st.error = new Error(`Unknown module key: ${key}`);
|
|
323
|
+
flush(key, st);
|
|
324
|
+
return st;
|
|
325
|
+
}
|
|
326
|
+
st.status = "loading";
|
|
327
|
+
log("load()", key, "->", importPath);
|
|
328
|
+
const promise = (async () => {
|
|
329
|
+
try {
|
|
330
|
+
const mod = await import(
|
|
331
|
+
/* @vite-ignore */
|
|
332
|
+
importPath
|
|
333
|
+
);
|
|
334
|
+
const def = toModuleDefinition(mod, key);
|
|
335
|
+
st.def = def;
|
|
336
|
+
if (!st.instance) {
|
|
337
|
+
st.instance = def.init(core);
|
|
338
|
+
}
|
|
339
|
+
st.status = "ready";
|
|
340
|
+
delete st.error;
|
|
341
|
+
delete st.promise;
|
|
342
|
+
flush(key, st);
|
|
343
|
+
return st;
|
|
344
|
+
} catch (err) {
|
|
345
|
+
st.status = "error";
|
|
346
|
+
st.error = toError(err);
|
|
347
|
+
delete st.promise;
|
|
348
|
+
flush(key, st);
|
|
349
|
+
return st;
|
|
350
|
+
}
|
|
351
|
+
})();
|
|
352
|
+
st.promise = promise;
|
|
353
|
+
return promise;
|
|
354
|
+
}
|
|
355
|
+
async function reload(key) {
|
|
356
|
+
log("reload()", key);
|
|
357
|
+
destroyModule(key);
|
|
358
|
+
return load(key);
|
|
359
|
+
}
|
|
360
|
+
function push(key, cb) {
|
|
361
|
+
const st = modules[key];
|
|
362
|
+
if (st && isReadyOrError(st)) {
|
|
363
|
+
try {
|
|
364
|
+
cb(st);
|
|
365
|
+
} catch (e) {
|
|
366
|
+
logError("push callback failed", key, e);
|
|
367
|
+
}
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
queue.push({ key, cb });
|
|
371
|
+
}
|
|
372
|
+
function autoLoadFromDOM(root = document) {
|
|
373
|
+
const keys = adlibUtils.collectModuleKeysFromDOM(root);
|
|
374
|
+
for (const key of keys) void load(key);
|
|
375
|
+
}
|
|
376
|
+
function startObserver() {
|
|
377
|
+
if (!adlibUtils.isBrowser()) return;
|
|
378
|
+
if (observer) return;
|
|
379
|
+
observer = new MutationObserver((mutations) => {
|
|
380
|
+
for (const m of mutations) {
|
|
381
|
+
for (const node of Array.from(m.addedNodes)) {
|
|
382
|
+
if (!(node instanceof HTMLElement)) continue;
|
|
383
|
+
autoLoadFromDOM(node);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
observer.observe(document.documentElement, { childList: true, subtree: true });
|
|
388
|
+
}
|
|
389
|
+
function stopObserver() {
|
|
390
|
+
observer?.disconnect();
|
|
391
|
+
observer = null;
|
|
392
|
+
}
|
|
393
|
+
function destroy(opts) {
|
|
394
|
+
log("destroy()");
|
|
395
|
+
stopObserver();
|
|
396
|
+
for (const st of Object.values(modules)) {
|
|
397
|
+
try {
|
|
398
|
+
st.instance?.destroy?.();
|
|
399
|
+
} catch (e) {
|
|
400
|
+
logError("destroy module failed", st.key, e);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (ownsCore) {
|
|
404
|
+
try {
|
|
405
|
+
core.destroy();
|
|
406
|
+
} catch (e) {
|
|
407
|
+
logError("core.destroy failed", e);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
for (const k of Object.keys(modules)) delete modules[k];
|
|
411
|
+
queue.length = 0;
|
|
412
|
+
if (!opts?.keepGlobal && typeof window !== "undefined") {
|
|
413
|
+
delete window.AdLibAttributes;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
const runtime = {
|
|
417
|
+
version: options.version,
|
|
418
|
+
config,
|
|
419
|
+
core,
|
|
420
|
+
debug,
|
|
421
|
+
modules,
|
|
422
|
+
load,
|
|
423
|
+
push,
|
|
424
|
+
reload,
|
|
425
|
+
destroy
|
|
426
|
+
};
|
|
427
|
+
if (typeof window !== "undefined") {
|
|
428
|
+
const globalQ = window.AdLibAttributesQueue;
|
|
429
|
+
if (Array.isArray(globalQ) && globalQ.length > 0) {
|
|
430
|
+
const items = globalQ.splice(0, globalQ.length);
|
|
431
|
+
for (const [key, cb] of items) runtime.push(key, cb);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
if (auto && adlibUtils.isBrowser()) {
|
|
435
|
+
autoLoadFromDOM(document.body ?? document);
|
|
436
|
+
startObserver();
|
|
437
|
+
}
|
|
438
|
+
return runtime;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
exports.createCore = createCore;
|
|
442
|
+
exports.createRuntime = createRuntime;
|
|
443
|
+
exports.default = core_default;
|
|
444
|
+
exports.getCoreSingleton = getCoreSingleton;
|
|
445
|
+
//# sourceMappingURL=index.cjs.map
|
|
446
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/index.ts","../src/runtime/module-map.ts","../src/runtime/runtime.ts"],"names":["collectModuleKeysFromDOM","isBrowser"],"mappings":";;;;;;;AAqHA,SAAS,YAAA,CAAa,QAAQ,KAAA,EAAmB;AAC/C,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,IAAI,IAAA,KAAoB;AAC7B,MAAA,IAAI,CAAC,KAAA,EAAO;AACZ,MAAA,OAAA,CAAQ,IAAA,CAAK,SAAA,EAAW,GAAG,IAAI,CAAA;AAAA,IACjC,CAAA;AAAA,IACA,IAAA,EAAM,IAAI,IAAA,KAAoB;AAC5B,MAAA,OAAA,CAAQ,IAAA,CAAK,QAAA,EAAU,GAAG,IAAI,CAAA;AAAA,IAChC,CAAA;AAAA,IACA,KAAA,EAAO,IAAI,IAAA,KAAoB;AAC7B,MAAA,OAAA,CAAQ,KAAA,CAAM,SAAA,EAAW,GAAG,IAAI,CAAA;AAAA,IAClC;AAAA,GACF;AACF;AAEA,SAAS,UAAU,KAAA,EAAkC;AAEnD,EAAA,OAAO,OAAO,OAAA,KAAY,WAAA,IAAe,KAAA,YAAiB,OAAA;AAC5D;AAEA,SAAS,WAAA,CAAY,IAAa,QAAA,EAA2B;AAC3D,EAAA,IAAI;AACF,IAAA,OAAO,EAAA,CAAG,QAAQ,QAAQ,CAAA;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAEA,SAAS,mBAAA,CAAoB,QAA4B,QAAA,EAAkC;AACzF,EAAA,IAAI,GAAA,GAA0B,MAAA;AAE9B,EAAA,OAAO,GAAA,EAAK;AACV,IAAA,IAAI,UAAU,GAAG,CAAA,IAAK,YAAY,GAAA,EAAK,QAAQ,GAAG,OAAO,GAAA;AACz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;AAAA,MACf,SAAS,CAAA,EAAG;AACV,QAAA,QAAA,CAAS,uBAAuB,CAAC,CAAA;AAAA,MACnC;AAAA,IACF;AAEA,IAAA,KAAA,MAAW,KAAK,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,EAAG,OAAO,QAAQ,CAAC,CAAA;AACtD,IAAA,KAAA,CAAM,MAAA,GAAS,CAAA;AAEf,IAAA,IAAI,CAAC,IAAA,EAAM,UAAA,IAAc,OAAO,WAAW,WAAA,EAAa;AACtD,MAAA,OAAO,MAAA,CAAO,eAAA;AAAA,IAChB;AAAA,EACF;AAEA,EAAA,MAAM,OAAA,GAAwB;AAAA,IAC5B,SAAS,OAAA,CAAQ,OAAA;AAAA,IACjB,MAAA;AAAA,IACA,IAAA;AAAA,IACA,KAAA;AAAA,IACA,OAAA;AAAA,IACA,IAAA;AAAA,IACA,IAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,IAAA,MAAM,UAAU,MAAA,CAAO,oBAAA;AACvB,IAAA,IAAI,MAAM,OAAA,CAAQ,OAAO,CAAA,IAAK,OAAA,CAAQ,SAAS,CAAA,EAAG;AAChD,MAAA,MAAM,KAAA,GAA2B,OAAA,CAAQ,MAAA,CAAO,CAAA,EAAG,QAAQ,MAAM,CAAA;AACjE,MAAA,KAAA,MAAW,CAAC,KAAK,EAAE,CAAA,IAAK,OAAO,OAAA,CAAQ,IAAA,CAAK,KAAK,EAAE,CAAA;AAAA,IACrD;AAAA,EACF;AAEA,EAAA,IAAI,IAAA,IAAQA,sBAAU,EAAG;AACvB,IAAA,eAAA,CAAgB,QAAA,CAAS,QAAQ,QAAQ,CAAA;AACzC,IAAA,aAAA,EAAc;AAAA,EAChB;AAEA,EAAA,OAAO,OAAA;AACT","file":"index.cjs","sourcesContent":["/* --------------------------------------------------------------------------\n * AdLib Attributes · Core\n *\n * Primitives partagées utilisées par le runtime et les modules d’attributs :\n * - délégation d’événements (listeners uniques sur une racine)\n * - registre de modules (définitions + instances)\n * - cycle de vie (mount/unmount/destroy)\n * - observation DOM (signal de changements, orchestration pilotée par le runtime)\n * -------------------------------------------------------------------------- */\n\nexport type Disposer = () => void;\nexport type Cleanup = void | Disposer;\n\nexport type CoreLogger = {\n debug: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n};\n\nexport type CoreOptions = {\n /** Root document/shadow root to bind listeners & observer (defaults to document). */\n root?: Document | ShadowRoot;\n /** Enable debug logs (printed as console.warn with \"[debug]\"). */\n debug?: boolean;\n /** Auto-mount modules on DOMContentLoaded when using singleton. Default: true. */\n autoMount?: boolean;\n};\n\nexport type DelegatedHandler = (e: Event, matched: Element) => void;\n\nexport type OnOptions = {\n /** If true, this delegated handler will run once then auto-unsubscribe. */\n once?: boolean;\n /** Capture phase for the underlying listener (per event type, first call wins). */\n capture?: boolean;\n /** Passive flag for the underlying listener (per event type, first call wins). */\n passive?: boolean;\n};\n\nexport interface Core {\n /**\n * Event delegation: listen on root and invoke handler when an ancestor matches selector.\n * Returns a disposer to remove this specific handler.\n */\n on: (type: string, selector: string, handler: DelegatedHandler, options?: OnOptions) => Disposer;\n\n /** Emit a CustomEvent from a given element. */\n emit: (el: Element, name: string, detail?: unknown) => void;\n\n /** Register a module definition. */\n register: (def: AdLibModuleDefinition) => void;\n\n /** Unregister a module definition by key. */\n unregister: (key: ModuleKey) => void;\n\n /** Mount a module by key, optionally on a given root. */\n mount: (key: ModuleKey, root?: ParentNode) => void;\n\n /** Unmount a module instance by key. */\n unmount: (key: ModuleKey) => void;\n\n /** Mount all registered modules. */\n mountAll: (root?: ParentNode) => void;\n\n /** Unmount all mounted modules. */\n unmountAll: () => void;\n\n /**\n * Observe dynamic DOM changes on a given root.\n *\n * Rôle :\n * - fournir un signal de changement DOM (ajouts/retraits de nœuds)\n * - permettre au runtime d’orchestrer un rescan/remount si nécessaire\n *\n * Retourne un disposer pour arrêter l’observation.\n */\n observe: (root?: ParentNode) => Disposer;\n\n /** Stop observing dynamic DOM changes. */\n stopObserving: () => void;\n\n /** Destroy core: unmount all, remove listeners, disconnect observer. */\n destroy: () => void;\n\n /** Core logger (debug/warn/error). */\n getLogger: () => CoreLogger;\n}\n\n/** Module key type (ex: 'ad-click'). */\nexport type ModuleKey = `ad-${string}`;\n\nexport interface AdLibModuleInstance {\n key: ModuleKey;\n destroy(): void;\n restart?(options?: { rescan?: boolean }): void;\n}\n\nexport interface AdLibModuleDefinition {\n key: ModuleKey;\n init(core: Core): AdLibModuleInstance;\n}\n\n/* --------------------------------- Internals -------------------------------- */\n\ntype DelegatedEntry = {\n selector: string;\n handler: DelegatedHandler;\n once: boolean;\n};\n\ntype EventListenerInfo = {\n capture: boolean;\n passive: boolean;\n listener: (e: Event) => void;\n entries: DelegatedEntry[];\n};\n\nfunction createLogger(debug = false): CoreLogger {\n return {\n debug: (...args: unknown[]) => {\n if (!debug) return;\n console.warn('[debug]', ...args);\n },\n warn: (...args: unknown[]) => {\n console.warn('[warn]', ...args);\n },\n error: (...args: unknown[]) => {\n console.error('[error]', ...args);\n },\n };\n}\n\nfunction isElement(value: unknown): value is Element {\n // Garde-fou typé : vérifie l’existence de Element (tests / environnements non DOM).\n return typeof Element !== 'undefined' && value instanceof Element;\n}\n\nfunction safeMatches(el: Element, selector: string): boolean {\n try {\n return el.matches(selector);\n } catch {\n return false;\n }\n}\n\nfunction findClosestMatching(target: EventTarget | null, selector: string): Element | null {\n let cur: EventTarget | null = target;\n\n while (cur) {\n if (isElement(cur) && safeMatches(cur, selector)) return cur;\n cur = isElement(cur) ? cur.parentElement : null;\n }\n\n return null;\n}\n\nfunction createDelegatedListener(info: EventListenerInfo) {\n return (e: Event) => {\n // Copie défensive : la liste peut être modifiée par un handler \"once\".\n const entries = info.entries.slice();\n\n for (const entry of entries) {\n const matched = findClosestMatching(e.target, entry.selector);\n if (!matched) continue;\n\n entry.handler(e, matched);\n\n if (entry.once) {\n const idx = info.entries.indexOf(entry);\n if (idx >= 0) info.entries.splice(idx, 1);\n }\n }\n };\n}\n\nfunction resolveObserverTarget(root: ParentNode): Node {\n // MutationObserver attend un Node.\n // - Document => document.documentElement si disponible, sinon le document lui-même\n // - ShadowRoot / Element => observe directement\n if (root instanceof Document) return root.documentElement ?? root;\n return root as unknown as Node;\n}\n\n/* ---------------------------------- Core ---------------------------------- */\n\nexport function createCore(options: CoreOptions = {}): Core {\n const root: Document | ShadowRoot = options.root ?? document;\n const logger = createLogger(!!options.debug);\n\n const defs = new Map<ModuleKey, AdLibModuleDefinition>();\n const instances = new Map<ModuleKey, AdLibModuleInstance>();\n\n const listenersByType = new Map<string, EventListenerInfo>();\n\n function on(type: string, selector: string, handler: DelegatedHandler, opts: OnOptions = {}): Disposer {\n const capture = !!opts.capture;\n const passive = !!opts.passive;\n\n const existing = listenersByType.get(type);\n if (existing) {\n existing.entries.push({ selector, handler, once: !!opts.once });\n\n return () => {\n const idx = existing.entries.findIndex((e) => e.selector === selector && e.handler === handler);\n if (idx >= 0) existing.entries.splice(idx, 1);\n\n // ✅ Si c'était le dernier handler, on retire le listener racine et on nettoie la map\n if (existing.entries.length === 0) {\n root.removeEventListener(type, existing.listener, { capture: existing.capture });\n listenersByType.delete(type);\n }\n };\n }\n\n const info: EventListenerInfo = {\n capture,\n passive,\n entries: [{ selector, handler, once: !!opts.once }],\n listener: () => {},\n };\n\n const listener = createDelegatedListener(info);\n info.listener = listener;\n\n listenersByType.set(type, info);\n\n root.addEventListener(type, listener, { capture, passive });\n\n // ✅ Disposer “handler-level” (pas “type-level”)\n return () => {\n const cur = listenersByType.get(type);\n if (!cur) return;\n\n const idx = cur.entries.findIndex((e) => e.selector === selector && e.handler === handler);\n if (idx >= 0) cur.entries.splice(idx, 1);\n\n if (cur.entries.length === 0) {\n root.removeEventListener(type, cur.listener, { capture: cur.capture });\n listenersByType.delete(type);\n }\n };\n }\n\n function emit(el: Element, name: string, detail?: unknown) {\n const ev = new CustomEvent(name, { detail, bubbles: true });\n el.dispatchEvent(ev);\n }\n\n function register(def: AdLibModuleDefinition) {\n defs.set(def.key, def);\n }\n\n function unregister(key: ModuleKey) {\n defs.delete(key);\n }\n\n function mount(key: ModuleKey, _root?: ParentNode) {\n const def = defs.get(key);\n if (!def) return;\n if (instances.has(key)) return;\n\n const inst = def.init(api);\n instances.set(key, inst);\n }\n\n function unmount(key: ModuleKey) {\n const inst = instances.get(key);\n if (!inst) return;\n inst.destroy();\n instances.delete(key);\n }\n\n function mountAll(_root?: ParentNode) {\n for (const key of defs.keys()) mount(key);\n }\n\n function unmountAll() {\n for (const key of instances.keys()) unmount(key);\n }\n\n let observer: MutationObserver | null = null;\n\n function observe(observedRoot: ParentNode = root): Disposer {\n if (observer) return () => {};\n\n observer = new MutationObserver((_mutations) => {\n // Signal DOM : le runtime est responsable de décider quoi charger / recharger.\n // Le core garantit uniquement une observation stable et désinscriptible.\n });\n\n observer.observe(resolveObserverTarget(observedRoot), {\n subtree: true,\n childList: true,\n attributes: false,\n });\n\n return () => stopObserving();\n }\n\n function stopObserving() {\n if (!observer) return;\n observer.disconnect();\n observer = null;\n }\n\n function destroy() {\n stopObserving();\n unmountAll();\n\n for (const [type, info] of listenersByType.entries()) {\n root.removeEventListener(type, info.listener, { capture: info.capture });\n }\n\n listenersByType.clear();\n defs.clear();\n instances.clear();\n }\n\n function getLogger() {\n return logger;\n }\n\n const api: Core = {\n on,\n emit,\n register,\n unregister,\n mount,\n unmount,\n mountAll,\n unmountAll,\n observe,\n stopObserving,\n destroy,\n getLogger,\n };\n\n return api;\n}\n\n/* ----------------------------- Singleton helpers ---------------------------- */\n\nlet singleton: Core | null = null;\n\nexport function getCoreSingleton(options: CoreOptions = {}): Core {\n if (singleton) return singleton;\n singleton = createCore({ autoMount: true, ...options });\n\n const shouldAutoMount = options.autoMount ?? true;\n if (shouldAutoMount && typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener(\n 'DOMContentLoaded',\n () => {\n singleton?.mountAll();\n },\n { once: true }\n );\n } else {\n singleton.mountAll();\n }\n }\n\n return singleton;\n}\n\nexport default createCore;","import type { ModuleKey, RuntimeConfig } from './types';\n\nfunction normalizeOrigin(origin: string): string {\n return origin.trim().replace(/\\/+$/, '');\n}\n\nfunction resolveOrigin(config: RuntimeConfig): string {\n // `base` permet de forcer une origine de chargement (ex: CDN custom).\n // Sinon, on utilise `registry` (ex: jsDelivr / unpkg / registry interne).\n return normalizeOrigin(config.base ?? config.registry);\n}\n\nfunction resolveVersion(config: RuntimeConfig): string {\n const v = (config.version ?? '').trim();\n return v || 'latest';\n}\n\n/**\n * Construit le chemin d'import ESM d'un module à partir de la configuration runtime.\n * Format :\n * {origin}/@adartem/{package}@{version}/dist/index.js\n */\nfunction makeEsmImportPath(origin: string, pkgName: string, version: string): string {\n return `${origin}/@adartem/${pkgName}@${version}/dist/index.js`;\n}\n\nconst PACKAGE_BY_KEY: Record<ModuleKey, string> = {\n 'ad-click': 'ad-click',\n};\n\nexport function getImportPathForModule(key: ModuleKey, config: RuntimeConfig): string | null {\n const origin = resolveOrigin(config);\n const version = resolveVersion(config);\n\n const pkgName = PACKAGE_BY_KEY[key];\n if (!pkgName) return null;\n\n return makeEsmImportPath(origin, pkgName, version);\n}","import { collectModuleKeysFromDOM, isBrowser } from '@adartem/adlib-utils';\n\nimport type { Core } from '../core';\nimport { createCore } from '../core';\nimport { getImportPathForModule } from './module-map';\nimport type {\n AdLibModuleDefinition,\n AdLibRuntime,\n GlobalQueueItem,\n ModuleKey,\n RuntimeConfig,\n RuntimeModuleState,\n RuntimeOptions,\n} from './types';\n\n/**\n * Runtime robuste:\n * - load() : import + init(core) + état\n * - push() : callbacks avant/après load\n * - queue globale window.AdLibAttributesQueue\n * - reload() : destroy module + re-init\n * - auto (optionnel) : scan DOM minimal + MutationObserver\n */\n\ntype QueueEntry = {\n key: ModuleKey;\n cb: (state: RuntimeModuleState) => void;\n};\n\nconst DEFAULT_REGISTRY = 'https://cdn.jsdelivr.net/npm';\n\nfunction stateOf(modules: Record<string, RuntimeModuleState>, key: ModuleKey): RuntimeModuleState {\n return (modules[key] ??= { key, status: 'idle' });\n}\n\nfunction isReadyOrError(s: RuntimeModuleState) {\n return s.status === 'ready' || s.status === 'error';\n}\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction normalizeUrlBase(value?: string): string | undefined {\n const v = (value ?? '').trim();\n if (!v) return undefined;\n return v.replace(/\\/+$/, '');\n}\n\nfunction resolveConfig(options: RuntimeOptions): RuntimeConfig {\n const registry = normalizeUrlBase(options.config?.registry) ?? DEFAULT_REGISTRY;\n const version = (options.config?.version ?? options.version).trim() || options.version;\n\n const out: RuntimeConfig = { registry, version };\n\n const base = normalizeUrlBase(options.config?.base);\n if (base) out.base = base; // ✅ n’ajoute pas la clé si undefined\n\n return out;\n}\n\n/**\n * Valide/normalise le résultat d'un import dynamique vers une AdLibModuleDefinition.\n * Permet d'éviter les `any` et les accès unsafe.\n */\nfunction toModuleDefinition(mod: unknown, expectedKey: ModuleKey): AdLibModuleDefinition {\n const candidate = (() => {\n if (mod && typeof mod === 'object') {\n const record = mod as Record<string, unknown>;\n return record.default ?? mod;\n }\n return mod;\n })();\n\n if (!candidate || typeof candidate !== 'object') {\n throw new Error(`Invalid module definition for ${expectedKey}`);\n }\n\n const def = candidate as Partial<AdLibModuleDefinition>;\n\n if (typeof def.key !== 'string' || typeof def.init !== 'function') {\n throw new Error(`Invalid module definition for ${expectedKey}`);\n }\n\n // Sécurité: clé cohérente\n if (def.key !== expectedKey) {\n throw new Error(`Module key mismatch: expected \"${expectedKey}\", got \"${def.key}\"`);\n }\n\n return def as AdLibModuleDefinition;\n}\n\nexport function createRuntime(options: RuntimeOptions): AdLibRuntime {\n const debug = options.debug ?? false;\n const auto = options.auto ?? false;\n\n // ✅ Ownership: runtime propriétaire uniquement si options.core est absent (null/undefined)\n const ownsCore = options.core == null;\n\n // ✅ Runtime ne récupère jamais le singleton tout seul.\n // - si core injecté => utilisé tel quel, et NON détruit par runtime.destroy()\n // - sinon => core dédié, détruit par runtime.destroy()\n const core: Core =\n options.core ??\n createCore({\n debug,\n autoMount: false,\n });\n\n const logger = core.getLogger();\n const config = resolveConfig(options);\n\n const modules: Record<string, RuntimeModuleState> = {};\n const queue: QueueEntry[] = [];\n\n let observer: MutationObserver | null = null;\n\n function log(...args: unknown[]) {\n if (!debug) return;\n logger.debug('[AdLib Runtime]', ...args);\n }\n\n function logError(...args: unknown[]) {\n logger.error('[AdLib Runtime]', ...args);\n }\n\n function flush(key: ModuleKey, st: RuntimeModuleState) {\n for (let i = queue.length - 1; i >= 0; i--) {\n const entry = queue[i];\n if (!entry) continue;\n if (entry.key === key) {\n queue.splice(i, 1);\n try {\n entry.cb(st);\n } catch (e) {\n logError('push callback failed', key, e);\n }\n }\n }\n }\n\n function destroyModule(key: ModuleKey) {\n const st = modules[key];\n if (!st) return;\n\n try {\n st.instance?.destroy?.();\n } catch (e) {\n logError('destroyModule failed', key, e);\n }\n\n delete st.instance;\n delete st.def;\n delete st.error;\n delete st.promise;\n\n st.status = 'idle';\n }\n\n async function load(key: ModuleKey): Promise<RuntimeModuleState> {\n const st = stateOf(modules, key);\n\n if (st.status === 'ready') return st;\n if (st.status === 'error') return st;\n\n if (st.status === 'loading' && st.promise) return st.promise;\n\n const importPath = getImportPathForModule(key, config);\n if (!importPath) {\n st.status = 'error';\n st.error = new Error(`Unknown module key: ${key}`);\n flush(key, st);\n return st;\n }\n\n st.status = 'loading';\n log('load()', key, '->', importPath);\n\n const promise: Promise<RuntimeModuleState> = (async () => {\n try {\n const mod: unknown = await import(/* @vite-ignore */ importPath);\n const def = toModuleDefinition(mod, key);\n\n st.def = def;\n\n if (!st.instance) {\n st.instance = def.init(core);\n }\n\n st.status = 'ready';\n delete st.error;\n delete st.promise;\n\n flush(key, st);\n return st;\n } catch (err) {\n st.status = 'error';\n st.error = toError(err);\n delete st.promise;\n\n flush(key, st);\n return st;\n }\n })();\n\n st.promise = promise;\n return promise;\n }\n\n async function reload(key: ModuleKey): Promise<RuntimeModuleState> {\n log('reload()', key);\n destroyModule(key);\n return load(key);\n }\n\n function push(key: ModuleKey, cb: (state: RuntimeModuleState) => void) {\n const st = modules[key];\n if (st && isReadyOrError(st)) {\n try {\n cb(st);\n } catch (e) {\n logError('push callback failed', key, e);\n }\n return;\n }\n queue.push({ key, cb });\n }\n\n function autoLoadFromDOM(root: ParentNode = document) {\n const keys = collectModuleKeysFromDOM(root);\n for (const key of keys) void load(key);\n }\n\n function startObserver() {\n if (!isBrowser()) return;\n if (observer) return;\n\n observer = new MutationObserver((mutations) => {\n for (const m of mutations) {\n for (const node of Array.from(m.addedNodes)) {\n if (!(node instanceof HTMLElement)) continue;\n autoLoadFromDOM(node);\n }\n }\n });\n\n observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n\n function stopObserver() {\n observer?.disconnect();\n observer = null;\n }\n\n function destroy(opts?: { keepGlobal?: boolean }) {\n log('destroy()');\n\n stopObserver();\n\n for (const st of Object.values(modules)) {\n try {\n st.instance?.destroy?.();\n } catch (e) {\n logError('destroy module failed', st.key, e);\n }\n }\n\n // ✅ Ownership rule: ne détruit le core QUE si le runtime l'a créé\n if (ownsCore) {\n try {\n core.destroy();\n } catch (e) {\n logError('core.destroy failed', e);\n }\n }\n\n for (const k of Object.keys(modules)) delete modules[k];\n queue.length = 0;\n\n if (!opts?.keepGlobal && typeof window !== 'undefined') {\n delete window.AdLibAttributes;\n }\n }\n\n const runtime: AdLibRuntime = {\n version: options.version,\n config,\n core,\n debug,\n modules,\n load,\n push,\n reload,\n destroy,\n };\n\n if (typeof window !== 'undefined') {\n const globalQ = window.AdLibAttributesQueue;\n if (Array.isArray(globalQ) && globalQ.length > 0) {\n const items: GlobalQueueItem[] = globalQ.splice(0, globalQ.length);\n for (const [key, cb] of items) runtime.push(key, cb);\n }\n }\n\n if (auto && isBrowser()) {\n autoLoadFromDOM(document.body ?? document);\n startObserver();\n }\n\n return runtime;\n}"]}
|