@walkeros/core 0.0.8 → 0.1.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 CHANGED
@@ -1,108 +1,313 @@
1
1
  <p align="left">
2
2
  <a href="https://elbwalker.com">
3
- <img title="elbwalker" src='https://www.elbwalker.com/img/elbwalker_logo.png' width="256px"/>
3
+ <img title="elbwalker" src="https://www.elbwalker.com/img/elbwalker_logo.png" width="256px"/>
4
4
  </a>
5
5
  </p>
6
6
 
7
7
  # Core Types & Utilities for walkerOS
8
8
 
9
- The walkerOS Core package provides the foundational TypeScript definitions and
10
- platform-agnostic utilities that power the entire walkerOS ecosystem. It serves
11
- as the bedrock for type safety and shared functionality across all sources,
12
- collectors, and destinations.
9
+ [Source Code](https://github.com/elbwalker/walkerOS/tree/main/packages/core)
10
+ &bull; [NPM Package](https://www.npmjs.com/package/@walkeros/core)
13
11
 
14
- ## Role in walkerOS Ecosystem
12
+ Core utilities are a collection of platform-agnostic functions that can be used
13
+ across all walkerOS environments. They provide standardized building blocks for
14
+ data manipulation, validation, mapping, and more.
15
15
 
16
- walkerOS follows a **source → collector → destination** architecture:
16
+ ## Installation
17
17
 
18
- - **Sources**: Capture events from various environments (browser DOM, dataLayer,
19
- server requests)
20
- - **Collector**: Processes, validates, and routes events with consent awareness
21
- - **Destinations**: Send processed events to analytics platforms (GA4, Meta,
22
- custom APIs)
18
+ Import the core utilities directly from the `@walkeros/core` package:
23
19
 
24
- The Core package provides the essential building blocks that all other packages
25
- depend on, ensuring consistent data structures, type definitions, and utility
26
- functions across the entire platform.
20
+ ```ts
21
+ import { assign, anonymizeIP, getMappingValue } from '@walkeros/core';
22
+ ```
27
23
 
28
- ## Installation
24
+ ## Core Utilities
25
+
26
+ ### Data Manipulation
27
+
28
+ #### assign
29
+
30
+ `assign<T, U>(target: T, source: U, options?): T & U` merges two objects with
31
+ advanced merging capabilities. It has special behavior for arrays: when merging,
32
+ it concatenates arrays from both objects, removing duplicates.
33
+
34
+ ```ts
35
+ interface AssignOptions {
36
+ merge?: boolean; // Merge array properties (default: true)
37
+ shallow?: boolean; // Create shallow copy (default: true)
38
+ extend?: boolean; // Extend with new properties (default: true)
39
+ }
40
+
41
+ const obj1 = { a: 1, b: [1, 2] };
42
+ const obj2 = { b: [2, 3], c: 3 };
43
+
44
+ assign(obj1, obj2); // Returns { a: 1, b: [1, 2, 3], c: 3 }
45
+ assign(obj1, obj2, { merge: false }); // Returns { a: 1, b: [2, 3], c: 3 }
46
+ ```
47
+
48
+ #### Path Operations
49
+
50
+ ##### getByPath
51
+
52
+ `getByPath(object: unknown, path: string, defaultValue?: unknown): unknown`
53
+ accesses nested properties using dot notation. Supports wildcard `*` for array
54
+ iteration.
55
+
56
+ ```js
57
+ getByPath({ data: { id: 'wow' } }, 'data.id'); // Returns "wow"
58
+ getByPath({ nested: [1, 2, { id: 'cool' }] }, 'nested.*.id'); // Returns ['', '', 'cool']
59
+ getByPath({ arr: ['foo', 'bar'] }, 'arr.1'); // Returns "bar"
60
+ ```
61
+
62
+ ##### setByPath
63
+
64
+ `setByPath(object: WalkerOS.Event, path: string, value: unknown): WalkerOS.Event`
65
+ sets nested values using dot notation, returning a new object with the updated
66
+ value.
67
+
68
+ ```js
69
+ const updatedEvent = setByPath(event, 'data.id', 'new-value');
70
+ // Returns a new event with data.id set to 'new-value'
71
+ ```
72
+
73
+ #### clone
74
+
75
+ `clone<T>(original: T): T` creates a deep copy of objects/arrays with circular
76
+ reference handling.
29
77
 
30
- ```sh
31
- npm install @walkeros/core
78
+ ```js
79
+ const original = { foo: true, arr: ['a', 'b'] };
80
+ const cloned = clone(original);
81
+ original.foo = false; // cloned.foo remains true
32
82
  ```
33
83
 
34
- ## Usage
84
+ #### castValue
35
85
 
36
- The core package exports essential types and utilities:
86
+ `castValue(value: unknown): WalkerOS.PropertyType` converts string values to
87
+ appropriate types (number, boolean).
37
88
 
38
- ```typescript
39
- import {
40
- // Core event types
41
- WalkerOS,
89
+ ```js
90
+ castValue('123'); // Returns 123 (number)
91
+ castValue('true'); // Returns true (boolean)
92
+ castValue('hello'); // Returns 'hello' (unchanged)
93
+ ```
94
+
95
+ ### Privacy & Security
96
+
97
+ #### anonymizeIP
98
+
99
+ `anonymizeIP(ip: string): string` anonymizes IPv4 addresses by setting the last
100
+ oclet to zero.
101
+
102
+ ```js
103
+ anonymizeIP('192.168.1.100'); // Returns '192.168.1.0'
104
+ ```
105
+
106
+ #### Hashing
107
+
108
+ `getId(length?: number): string` generates random alphanumeric strings for
109
+ unique identifiers.
110
+
111
+ ```js
112
+ getId(); // Returns random 6-char string like 'a1b2c3'
113
+ getId(10); // Returns 10-character string
114
+ ```
115
+
116
+ ### Event Processing
42
117
 
43
- // Utility functions
44
- assign,
45
- clone,
46
- validateEvent,
118
+ #### getMappingValue
47
119
 
48
- // Consent management
49
- Consent,
120
+ `getMappingValue(event: WalkerOS.Event, mapping: Mapping.Data, options?: Mapping.Options): Promise<WalkerOS.Property | undefined>`
121
+ extracts values from events using
122
+ [mapping configurations](https://www.elbwalker.com/docs/destinations/event-mapping).
50
123
 
51
- // Mapping utilities
52
- byPath,
53
- mapping,
54
- } from '@walkeros/core';
124
+ ```ts
125
+ // Simple path mapping
126
+ await getMappingValue(event, 'data.productId');
55
127
 
56
- // Example: Validate an event
57
- const event: WalkerOS.Event = {
58
- event: 'order complete',
59
- data: { value: 9001 },
60
- // ... other properties
128
+ // Complex mapping with conditions and loops
129
+ const mapping = {
130
+ map: {
131
+ orderId: 'data.id',
132
+ products: {
133
+ loop: [
134
+ 'nested',
135
+ {
136
+ condition: (entity) => entity.entity === 'product',
137
+ map: { id: 'data.id', name: 'data.name' },
138
+ },
139
+ ],
140
+ },
141
+ },
61
142
  };
143
+ await getMappingValue(event, mapping);
144
+ ```
62
145
 
63
- if (validateEvent(event)) {
64
- console.log('Event is valid!');
65
- }
146
+ #### getMappingEvent
147
+
148
+ `getMappingEvent(event: WalkerOS.PartialEvent, mapping?: Mapping.Rules): Promise<Mapping.Result>`
149
+ finds the appropriate mapping rule for an event.
150
+
151
+ ### Marketing & Analytics
152
+
153
+ #### getMarketingParameters
154
+
155
+ `getMarketingParameters(url: URL, custom?: MarketingParameters): WalkerOS.Properties`
156
+ extracts UTM and click ID parameters from URLs.
157
+
158
+ ```js
159
+ getMarketingParameters(
160
+ new URL('https://example.com/?utm_source=docs&gclid=123'),
161
+ );
162
+ // Returns { source: "docs", gclid: "123", clickId: "gclid" }
163
+
164
+ // With custom parameters
165
+ getMarketingParameters(url, { utm_custom: 'custom', partner: 'partnerId' });
66
166
  ```
67
167
 
68
- ## Event Naming Convention
168
+ ### Type Validation
169
+
170
+ #### Type Checkers
171
+
172
+ A comprehensive set of type checking functions:
173
+
174
+ - `isString(value)`, `isNumber(value)`, `isBoolean(value)`
175
+ - `isArray(value)`, `isObject(value)`, `isFunction(value)`
176
+ - `isDefined(value)`, `isSameType(a, b)`
177
+ - `isPropertyType(value)` - Checks if value is valid walkerOS property
69
178
 
70
- walkerOS follows a strict **"entity action"** naming convention for events:
179
+ #### Property Utilities
71
180
 
72
- **Correct**: Use spaces to separate entity and action
181
+ - `castToProperty(value)` - Casts to valid property type
182
+ - `filterValues(object)` - Filters object to valid properties only
183
+ - `isPropertyType(value)` - Type guard for property validation
73
184
 
74
- ```typescript
75
- elb('order complete', { value: 99.99 });
76
- elb('product add', { id: 'abc123' });
77
- elb('page view', { path: '/home' });
78
- elb('user register', { email: 'user@example.com' });
185
+ ### Request Handling
186
+
187
+ #### requestToData
188
+
189
+ `requestToData(parameter: unknown): WalkerOS.AnyObject | undefined` converts
190
+ query strings to JavaScript objects with type casting.
191
+
192
+ ```js
193
+ requestToData('a=1&b=true&c=hello&arr[0]=x&arr[1]=y');
194
+ // Returns { a: 1, b: true, c: 'hello', arr: ['x', 'y'] }
195
+ ```
196
+
197
+ #### requestToParameter
198
+
199
+ `requestToParameter(data: WalkerOS.AnyObject): string` converts objects to
200
+ URL-encoded query strings.
201
+
202
+ ```js
203
+ requestToParameter({ a: 1, b: true, arr: ['x', 'y'] });
204
+ // Returns 'a=1&b=true&arr[0]=x&arr[1]=y'
205
+ ```
206
+
207
+ ### User Agent Parsing
208
+
209
+ #### parseUserAgent
210
+
211
+ `parseUserAgent(userAgent?: string): WalkerOS.User` extracts browser, OS, and
212
+ device information.
213
+
214
+ ```js
215
+ parseUserAgent(navigator.userAgent);
216
+ // Returns { browser: 'Chrome', browserVersion: '91.0', os: 'Windows', ... }
79
217
  ```
80
218
 
81
- **Incorrect**: Do not use underscores or other separators
219
+ Individual functions are also available:
220
+
221
+ - `getBrowser(userAgent)` - Returns browser name
222
+ - `getBrowserVersion(userAgent)` - Returns browser version
223
+ - `getOS(userAgent)` - Returns operating system
224
+ - `getOSVersion(userAgent)` - Returns OS version
225
+ - `getDeviceType(userAgent)` - Returns 'Desktop', 'Tablet', or 'Mobile'
226
+
227
+ ### Error Handling
82
228
 
83
- ```typescript
84
- // Don't do this
85
- elb('order_complete', data); // Wrong: underscores
86
- elb('orderComplete', data); // Wrong: camelCase
87
- elb('purchase', data); // Wrong: single word
229
+ #### tryCatch
230
+
231
+ `tryCatch(tryFn: Function, catchFn?: Function, finallyFn?: Function)` wraps
232
+ functions with error handling.
233
+
234
+ ```js
235
+ const safeParse = tryCatch(JSON.parse, () => ({}));
236
+ safeParse('{"valid": "json"}'); // Parses successfully
237
+ safeParse('invalid'); // Returns {} instead of throwing
88
238
  ```
89
239
 
90
- **Why spaces matter**: walkerOS destinations automatically transform your
91
- semantic event names into platform-specific formats. For example,
92
- `'order complete'` becomes `'purchase'` for Google Analytics 4, while preserving
93
- the original meaning in your data model.
240
+ #### tryCatchAsync
241
+
242
+ `tryCatchAsync(tryFn: Function, catchFn?: Function, finallyFn?: Function)` for
243
+ async operations.
244
+
245
+ ```js
246
+ const safeAsyncCall = tryCatchAsync(
247
+ () => fetchUserData(),
248
+ (error) => ({ error: 'Failed to load user' }),
249
+ );
250
+ ```
251
+
252
+ ### Performance Optimization
253
+
254
+ #### debounce
255
+
256
+ `debounce(fn: Function, wait?: number)` delays function execution until after
257
+ the wait time.
258
+
259
+ ```js
260
+ const debouncedSearch = debounce(searchFunction, 300);
261
+ // Only executes after 300ms of inactivity
262
+ ```
263
+
264
+ #### throttle
265
+
266
+ `throttle(fn: Function, wait?: number)` limits function execution frequency.
267
+
268
+ ```js
269
+ const throttledScroll = throttle(scrollHandler, 100);
270
+ // Executes at most every 100ms
271
+ ```
272
+
273
+ ### Utilities
274
+
275
+ #### trim
276
+
277
+ `trim(str: string): string` removes whitespace from string ends.
278
+
279
+ #### throwError
280
+
281
+ `throwError(message: string)` throws descriptive errors.
282
+
283
+ #### onLog
284
+
285
+ `onLog(message: unknown, verbose?: boolean)` provides consistent logging.
286
+
287
+ ```js
288
+ onLog('Debug info', true); // Logs message
289
+ onLog('Silent message'); // No output
290
+ ```
291
+
292
+ ### Validation
293
+
294
+ #### validateEvent
295
+
296
+ `validateEvent(obj: unknown, customContracts?: Schema.Contracts): WalkerOS.Event | never`
297
+ validates event structure and throws on invalid events.
298
+
299
+ #### validateProperty
300
+
301
+ Validates that values conform to walkerOS property types.
302
+
303
+ ---
94
304
 
95
- ## Core Features
305
+ For platform-specific utilities, see:
96
306
 
97
- - **TypeScript Definitions**: Complete type system for walkerOS events and
98
- configurations
99
- - **Platform-Agnostic Utilities**: Shared functions for data manipulation and
100
- validation
101
- - **Consent Types**: Standardized consent management interfaces
102
- - **Event Validation**: Built-in validation for event structure and data
103
- integrity
104
- - **Mapping Utilities**: Tools for transforming data between different formats
105
- - **Privacy Utilities**: Functions for data anonymization and privacy compliance
307
+ - [Web Core](https://www.elbwalker.com/docs/core/web) - Browser-specific
308
+ functions
309
+ - [Server Core](https://www.elbwalker.com/docs/core/server) - Node.js server
310
+ functions
106
311
 
107
312
  ## Contribute
108
313