@arc-js/id-generator 0.0.1

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/README.md ADDED
@@ -0,0 +1,547 @@
1
+ # @arc-js/id-generator
2
+
3
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
4
+ ![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-007ACC)
5
+ ![Browser](https://img.shields.io/badge/browser-compatible-green)
6
+ ![Node.js](https://img.shields.io/badge/Node.js-18+-339933)
7
+
8
+ **@arc-js/id-generator** est une bibliothèque TypeScript robuste pour générer des identifiants uniques avec des formats personnalisables. Elle offre une syntaxe expressive pour créer des identifiants complexes combinant texte, chaînes aléatoires, UUID et fonctions personnalisées.
9
+
10
+ ## ✨ Fonctionnalités Principales
11
+
12
+ ### 🔤 Formats de Génération Flexibles
13
+ - **Syntaxe intuitive** : Utilisez des templates avec tokens spéciaux
14
+ - **Combinaisons multiples** : Mélangez texte, random, UUID et handlers personnalisés
15
+ - **Cache intelligent** : Génération optimisée avec cache pour les patterns non-variants
16
+
17
+ ### 🎲 Types de Génération Supportés
18
+ - **Chaînes aléatoires** : Numeric, alphabetic, alphanumeric (avec/sans casse)
19
+ - **UUID** : Versions v1 à v5 avec implémentations standards
20
+ - **Handlers personnalisés** : Intégrez vos propres fonctions de génération
21
+ - **Handlers intégrés** : Timestamp, date, time, compteur, variables d'environnement
22
+
23
+ ### ⚡ Performance & Sécurité
24
+ - **Générateur cryptographique** : Utilise `crypto.getRandomValues` pour la sécurité
25
+ - **Singleton pattern** : Instance unique optimisée
26
+ - **Gestion de cache** : Réduction des calculs redondants
27
+ - **Validation stricte** : Erreurs détaillées pour formats invalides
28
+
29
+ ## 📦 Installation
30
+
31
+ ### Via npm/yarn/pnpm
32
+
33
+ ```bash
34
+ npm install @arc-js/id-generator
35
+ # ou
36
+ yarn add @arc-js/id-generator
37
+ # ou
38
+ pnpm add @arc-js/id-generator
39
+ ```
40
+
41
+ ### Importation directe (CDN)
42
+
43
+ ```html
44
+ <script src="@arc-js/id-generator/id-generator.all.js"></script>
45
+ ```
46
+
47
+ ## 🚀 Démarrage Rapide
48
+
49
+ ### TypeScript/ES Modules
50
+
51
+ ```typescript
52
+ import { IdentifierGenerator, IdentifierGeneratorHandlers } from '@arc-js/id-generator';
53
+ // ou
54
+ import IdGenerator from '@arc-js/id-generator';
55
+ ```
56
+
57
+ ### CommonJS
58
+
59
+ ```javascript
60
+ const { IdentifierGenerator, IdentifierGeneratorHandlers } = require('@arc-js/id-generator');
61
+ ```
62
+
63
+ ### Navigateur (global)
64
+
65
+ ```html
66
+ <script src="@arc-js/id-generator/id-generator.all.js"></script>
67
+ <script>
68
+ // Disponible globalement
69
+ const generator = IdentifierGenerator.getInstance();
70
+ const id = generator.generate('prefix-#rand{size:8,type:alphanumeric}');
71
+ </script>
72
+ ```
73
+
74
+ ## 📚 Syntaxe des Formats
75
+
76
+ ### Structure de Base
77
+
78
+ ```
79
+ texte_littéral#token{options}texte_suivant
80
+ ```
81
+
82
+ - **texte_littéral** : Texte statique inclus tel quel
83
+ - **#** : Délimiteur de token spécial
84
+ - **token** : Type de token (`rand`, `uuid`, `custom`)
85
+ - **{options}** : Options spécifiques au token (optionnel)
86
+
87
+ ### Tokens Disponibles
88
+
89
+ | Token | Description | Options |
90
+ |-------|-------------|---------|
91
+ | `#rand{...}` | Chaîne aléatoire | `size`, `type`, `variant` |
92
+ | `#uuid{...}` | UUID | `version` |
93
+ | `#custom{...}` | Handler personnalisé | Nom du handler |
94
+ | Texte seul | Texte statique | Aucune |
95
+
96
+ ### Options des Tokens
97
+
98
+ #### Options pour `#rand`
99
+ ```typescript
100
+ {
101
+ size: number, // Longueur de la chaîne (défaut: 8)
102
+ type: RandomType, // 'numeric' | 'alphabetic' | 'alphabetic-case' | 'alphanumeric' | 'alphanumeric-case'
103
+ variant: boolean // Si true, génère à chaque fois (défaut: false)
104
+ }
105
+ ```
106
+
107
+ #### Options pour `#uuid`
108
+ ```typescript
109
+ {
110
+ version: UUIDVersion // 'v1' | 'v2' | 'v3' | 'v4' | 'v5' (défaut: 'v4')
111
+ }
112
+ ```
113
+
114
+ #### Options pour `#custom`
115
+ ```typescript
116
+ {
117
+ handlerName: string // Nom du handler personnalisé
118
+ }
119
+ ```
120
+
121
+ ## 🔧 Utilisation Détaillée
122
+
123
+ ### Instance Singleton
124
+
125
+ ```typescript
126
+ // Méthode recommandée : singleton
127
+ const generator = IdentifierGenerator.getInstance();
128
+
129
+ // Méthode statique (plus concise)
130
+ const id = IdentifierGenerator.generateId('format');
131
+ ```
132
+
133
+ ### Exemples Complets
134
+
135
+ #### Exemple 1 : ID avec Random et UUID
136
+
137
+ ```typescript
138
+ const generator = IdentifierGenerator.getInstance();
139
+
140
+ const id1 = generator.generate(
141
+ 'mda-#rand{size:10,type:alphanumeric}-#uuid{version:v1}',
142
+ {
143
+ customTimestamp: () => Date.now().toString()
144
+ }
145
+ );
146
+ // Résultat: "mda-a3b8c9d2e1-6ba7b810-9dad-11d1-80b4-00c04fd430c8"
147
+ ```
148
+
149
+ #### Exemple 2 : Random avec variant
150
+
151
+ ```typescript
152
+ const id2 = generator.generate(
153
+ 'lorem-#rand{type:alphanumeric,variant:true}-ipsum',
154
+ {
155
+ user: () => 'john_doe'
156
+ }
157
+ );
158
+ // Résultat: "lorem-a1b2c3d4-ipsum" (change à chaque appel)
159
+ ```
160
+
161
+ #### Exemple 3 : Handler personnalisé
162
+
163
+ ```typescript
164
+ const id3 = generator.generate(
165
+ 'user-#custom{userId}-#rand{size:6,type:numeric}',
166
+ {
167
+ userId: () => 'USR_' + Math.random().toString(36).substr(2, 9)
168
+ }
169
+ );
170
+ // Résultat: "user-USR_abc123def-123456"
171
+ ```
172
+
173
+ #### Exemple 4 : Utilisation des handlers intégrés
174
+
175
+ ```typescript
176
+ const id4 = IdentifierGenerator.generateId(
177
+ 'order-#custom{timestamp}-#rand{size:8,type:alphanumeric-case}',
178
+ {
179
+ timestamp: IdentifierGeneratorHandlers.timestamp
180
+ }
181
+ );
182
+ // Résultat: "order-1641234567890-A1b2C3d4"
183
+ ```
184
+
185
+ ### Handlers Intégrés
186
+
187
+ ```typescript
188
+ // Disponibles dans IdentifierGeneratorHandlers
189
+ {
190
+ timestamp: () => Date.now().toString(),
191
+ date: () => new Date().toISOString().slice(0, 10).replace(/-/g, ''),
192
+ time: () => new Date().toISOString().slice(11, 19).replace(/:/g, ''),
193
+ counter: () => { /* compteur auto-incrémenté */ },
194
+ env: (envVar: string) => process.env[envVar] || ''
195
+ }
196
+ ```
197
+
198
+ ## 🎯 Cas d'Utilisation Avancés
199
+
200
+ ### Génération d'ID Transactionnels
201
+
202
+ ```typescript
203
+ function generateTransactionId(prefix: string): string {
204
+ return IdentifierGenerator.generateId(
205
+ `\${prefix}-#custom{date}-#custom{time}-#rand{size:12,type:numeric}`,
206
+ {
207
+ date: IdentifierGeneratorHandlers.date,
208
+ time: IdentifierGeneratorHandlers.time
209
+ }
210
+ );
211
+ }
212
+ // Résultat: "TXN-20231225-143025-123456789012"
213
+ ```
214
+
215
+ ### Génération d'ID Utilisateur
216
+
217
+ ```typescript
218
+ class UserService {
219
+ private counter = 0;
220
+
221
+ generateUserId(username: string): string {
222
+ return IdentifierGenerator.getInstance().generate(
223
+ 'USR-#custom{prefix}-#custom{seq}-#rand{size:4,type:alphanumeric}',
224
+ {
225
+ prefix: () => username.substring(0, 3).toUpperCase(),
226
+ seq: () => (++this.counter).toString().padStart(6, '0')
227
+ }
228
+ );
229
+ }
230
+ }
231
+ // Résultat: "USR-JOH-000001-A1B2"
232
+ ```
233
+
234
+ ### Génération d'ID de Session
235
+
236
+ ```typescript
237
+ function generateSessionId(): string {
238
+ return IdentifierGenerator.generateId(
239
+ 'SESS-#uuid{version:v4}-#custom{timestamp}',
240
+ {
241
+ timestamp: () => Date.now().toString(36)
242
+ }
243
+ );
244
+ }
245
+ // Résultat: "SESS-550e8400-e29b-41d4-a716-446655440000-kyz9w8"
246
+ ```
247
+
248
+ ## ⚙️ Configuration Avancée
249
+
250
+ ### Gestion du Cache
251
+
252
+ ```typescript
253
+ const generator = IdentifierGenerator.getInstance();
254
+
255
+ // Générer avec cache (par défaut pour les non-variants)
256
+ const cachedId = generator.generate('id-#rand{size:8,type:alphanumeric,variant:false}');
257
+ // Même valeur à chaque appel pour la même session
258
+
259
+ // Vider le cache
260
+ generator.clearCache();
261
+
262
+ // Forcer une nouvelle génération
263
+ const freshId = generator.generate('id-#rand{size:8,type:alphanumeric,variant:true}');
264
+ ```
265
+
266
+ ### Handlers Personnalisés Complexes
267
+
268
+ ```typescript
269
+ // Handler avec paramètres
270
+ const configurableHandler = (prefix: string, length: number) =>
271
+ () => prefix + Math.random().toString(36).substr(2, length);
272
+
273
+ // Handler asynchrone (à wrapper)
274
+ const asyncHandler = async () => {
275
+ const response = await fetch('/api/id-source');
276
+ return response.text();
277
+ };
278
+
279
+ const generator = IdentifierGenerator.getInstance();
280
+ const id = generator.generate(
281
+ 'item-#custom{dynamicId}',
282
+ {
283
+ dynamicId: () => configurableHandler('ITM_', 8)()
284
+ }
285
+ );
286
+ ```
287
+
288
+ ### Extension des Types
289
+
290
+ ```typescript
291
+ // Ajouter de nouveaux types de random
292
+ interface ExtendedRandomOptions extends RandomOptions {
293
+ exclude?: string; // Caractères à exclure
294
+ }
295
+
296
+ // Créer un générateur étendu
297
+ class ExtendedIdentifierGenerator extends IdentifierGenerator {
298
+ protected generateRandomString(options: ExtendedRandomOptions): string {
299
+ if (options.exclude) {
300
+ // Implémentation personnalisée
301
+ }
302
+ return super.generateRandomString(options);
303
+ }
304
+ }
305
+ ```
306
+
307
+ ## 📊 Table des Types de Random
308
+
309
+ | Type | Caractères Inclus | Exemple |
310
+ |------|------------------|---------|
311
+ | `numeric` | 0-9 | "12345678" |
312
+ | `alphabetic` | a-z (minuscules) | "abcdefgh" |
313
+ | `alphabetic-case` | a-z, A-Z | "AbCdEfGh" |
314
+ | `alphanumeric` | a-z, 0-9 | "a1b2c3d4" |
315
+ | `alphanumeric-case` | a-z, A-Z, 0-9 | "A1b2C3d4" |
316
+
317
+ ## 🛡️ Gestion des Erreurs
318
+
319
+ ### Erreurs de Format
320
+
321
+ ```typescript
322
+ try {
323
+ generator.generate('invalid-#unknown{type:invalid}');
324
+ } catch (error) {
325
+ console.error('Erreur de format:', error.message);
326
+ // "Type de token non supporté: unknown"
327
+ }
328
+ ```
329
+
330
+ ### Erreurs de Handler
331
+
332
+ ```typescript
333
+ try {
334
+ generator.generate('#custom{missingHandler}', {});
335
+ } catch (error) {
336
+ console.error('Handler manquant:', error.message);
337
+ // "Handler personnalisé non trouvé: missingHandler"
338
+ }
339
+ ```
340
+
341
+ ### Validation des Options
342
+
343
+ ```typescript
344
+ // Taille négative
345
+ generator.generate('#rand{size:-5}'); // Lance une erreur
346
+
347
+ // Type invalide
348
+ generator.generate('#rand{type:invalid}'); // Utilise la valeur par défaut
349
+ ```
350
+
351
+ ## 🔧 Intégration
352
+
353
+ ### Avec React
354
+
355
+ ```tsx
356
+ import React, { useMemo } from 'react';
357
+ import { IdentifierGenerator } from '@arc-js/id-generator';
358
+
359
+ const ProductCard: React.FC<{ product: Product }> = ({ product }) => {
360
+ const uniqueId = useMemo(() =>
361
+ IdentifierGenerator.generateId(
362
+ 'product-#custom{id}-#rand{size:4,type:alphanumeric}',
363
+ { id: () => product.id }
364
+ ), [product.id]);
365
+
366
+ return (
367
+ <div id={uniqueId}>
368
+ {/* Contenu */}
369
+ </div>
370
+ );
371
+ };
372
+ ```
373
+
374
+ ### Avec Node.js
375
+
376
+ ```typescript
377
+ import { IdentifierGenerator, IdentifierGeneratorHandlers } from '@arc-js/id-generator';
378
+
379
+ // Configuration pour Node.js
380
+ if (typeof window === 'undefined') {
381
+ // Polyfill pour crypto si nécessaire
382
+ global.crypto = require('crypto');
383
+ }
384
+
385
+ export function generateRequestId(): string {
386
+ return IdentifierGenerator.generateId(
387
+ 'req-#custom{timestamp}-#rand{size:16,type:alphanumeric-case}',
388
+ {
389
+ timestamp: IdentifierGeneratorHandlers.timestamp
390
+ }
391
+ );
392
+ }
393
+ ```
394
+
395
+ ### Avec Vue.js
396
+
397
+ ```vue
398
+ <template>
399
+ <div :id="uniqueId">
400
+ <!-- Contenu -->
401
+ </div>
402
+ </template>
403
+
404
+ <script setup>
405
+ import { computed } from 'vue';
406
+ import { IdentifierGenerator } from '@arc-js/id-generator';
407
+
408
+ const props = defineProps(['item']);
409
+
410
+ const uniqueId = computed(() =>
411
+ IdentifierGenerator.generateId(
412
+ 'item-#custom{itemId}',
413
+ { itemId: () => props.item.id }
414
+ )
415
+ );
416
+ </script>
417
+ ```
418
+
419
+ ## 📋 Table des Performances
420
+
421
+ | Opération | Temps moyen | Mémoire |
422
+ |-----------|-------------|---------|
423
+ | Génération simple (#rand) | < 1ms | ~100KB |
424
+ | Génération UUID (#uuid v4) | < 2ms | ~100KB |
425
+ | Format complexe (5 tokens) | < 5ms | ~150KB |
426
+ | Cache hit | < 0.1ms | N/A |
427
+
428
+ ## 🚨 Meilleures Pratiques
429
+
430
+ ### 1. Réutiliser les Instances
431
+ ```typescript
432
+ // MAUVAIS : nouvelle instance à chaque fois
433
+ const id1 = new IdentifierGenerator().generate(...);
434
+
435
+ // BON : singleton
436
+ const generator = IdentifierGenerator.getInstance();
437
+ const id2 = generator.generate(...);
438
+ const id3 = generator.generate(...);
439
+ ```
440
+
441
+ ### 2. Utiliser le Cache Appropriément
442
+ ```typescript
443
+ // Pour les IDs uniques par session
444
+ generator.generate('session-#rand{variant:true}');
445
+
446
+ // Pour les IDs constants
447
+ generator.generate('constant-#rand{variant:false}');
448
+ ```
449
+
450
+ ### 3. Valider les Formats
451
+ ```typescript
452
+ function isValidFormat(format: string): boolean {
453
+ try {
454
+ IdentifierGenerator.generateId(format, {});
455
+ return true;
456
+ } catch {
457
+ return false;
458
+ }
459
+ }
460
+ ```
461
+
462
+ ### 4. Sécuriser la Génération
463
+ ```typescript
464
+ // Utiliser crypto pour les IDs sensibles
465
+ const secureId = generator.generate(
466
+ '#rand{size:32,type:alphanumeric-case,variant:true}'
467
+ );
468
+ ```
469
+
470
+ ## 🔗 API Complète
471
+
472
+ ### Classe `IdentifierGenerator`
473
+
474
+ #### Méthodes Statiques
475
+ - `getInstance(): IdentifierGenerator` - Retourne l'instance singleton
476
+ - `generateId(format: string, customHandlers?: Record<string, CustomHandler>): string` - Génère un ID directement
477
+ - `exposeToGlobal(): void` - Expose à l'objet global (navigateur)
478
+
479
+ #### Méthodes d'Instance
480
+ - `generate(format: string, customHandlers?: Record<string, CustomHandler>): string` - Génère un ID
481
+ - `clearCache(): void` - Vide le cache interne
482
+
483
+ ### Objet `IdentifierGeneratorHandlers`
484
+
485
+ Handlers prédéfinis pour les cas courants :
486
+ - `timestamp(): string`
487
+ - `date(): string`
488
+ - `time(): string`
489
+ - `counter(): string`
490
+ - `env(envVar: string): string`
491
+
492
+ ### Types Exportés
493
+
494
+ ```typescript
495
+ export type RandomType = 'numeric' | 'alphabetic' | 'alphabetic-case' | 'alphanumeric' | 'alphanumeric-case';
496
+ export type UUIDVersion = 'v1' | 'v2' | 'v3' | 'v4' | 'v5';
497
+ export type CustomHandler = () => string;
498
+
499
+ export interface RandomOptions {
500
+ size: number;
501
+ type: RandomType;
502
+ variant: boolean;
503
+ }
504
+
505
+ export interface UUIDOptions {
506
+ version: UUIDVersion;
507
+ }
508
+
509
+ export interface TokenDefinition {
510
+ type: 'string' | 'random' | 'uuid' | 'custom';
511
+ value: string | RandomOptions | UUIDOptions | CustomHandler;
512
+ }
513
+ ```
514
+
515
+ ## 🔧 Build et Développement
516
+
517
+ ### Structure du Projet
518
+
519
+ ```
520
+ @arc-js/id-generator/
521
+ ├── id-generator.all.js
522
+ ├── id-generator.all.min.js
523
+ ├── index.d.ts
524
+ ├── index.js
525
+ ├── index.min.d.ts
526
+ ├── index.min.js
527
+ ├── package.json
528
+ ├── tsconfig.json
529
+ └── README.md
530
+ ```
531
+
532
+ ## 📄 Licence
533
+
534
+ MIT License - Voir le fichier [LICENSE](LICENSE) pour plus de détails.
535
+
536
+ ## 🐛 Signaler un Bug
537
+
538
+ Envoyez nous un mail à l'adresse `contact.inicode@gmail.com` pour :
539
+ - Signaler un bug
540
+ - Proposer une amélioration
541
+ - Poser une question
542
+
543
+ ---
544
+
545
+ **@arc-js/id-generator** - Générez des identifiants uniques avec élégance et puissance.
546
+
547
+ *Développé par l'équipe INICODE*