# Segmentify Integration > Documentation for the Segmentify Integration library. import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components'; ## Core Features Every event, payload, and config option is fully typed. Catch integration errors at build time, not in production. Page views, product views, basket ops, purchases, wishlists, and gamification — all ready to go out of the box. Define URL patterns or use external object matching. The library detects page types and fires events automatically. Built-in History API interception re-detects pages on every route change. Works with React, Vue, Angular, and Next.js. --- ## Explore the Documentation --- # Introduction > This guide will help you set up the Segmentify integration library in your project. ## Prerequisites - Node.js >= 20 - A Segmentify account with an API key ## Quick Start ### 1. Install the package ```bash npm install @segmentify/integration # or pnpm add @segmentify/integration # or yarn add @segmentify/integration ``` ### 2. Initialize the library ```typescript import { Initializer, type SegmentifyConfig } from '@segmentify/integration'; const AppConfig = { domain: 'segmentify.com', apiKey: '', language: '', currency: '', segmentifyApiUrl: '', segmentifyPushUrl: '', doNotPersonalize: { cb: () => false, }, debug: 'DEBUG', spa: false, ga: { enabled: true, ga4: true, }, searchify: true, } as const satisfies SegmentifyConfig; new Initializer({ ...AppConfig, pageMap: { 'Home Page': { type: 'Home Page', category: 'Home Page', pattern: ['/'], }, }, }); ``` ### 3. Start tracking events ```typescript import { SegmentifyEventManager } from '@segmentify/integration'; // Track a page view SegmentifyEventManager().PageView({ name: 'PAGE_VIEW', }); // Track a product view SegmentifyEventManager().ProductView({ productId: 'PROD-123', title: 'Amazing Product', price: 99.99, category: 'electronics', }); ``` ## As a Script Tag For non-bundled environments, include the UMD build directly: ```html ``` ## Build Outputs The package ships with multiple formats: | File | Format | Use Case | | ------------------ | ----------------------- | --------------------------------------- | | `dist/index.es.js` | ES Module | Modern bundlers (Vite, webpack, Rollup) | | `dist/index.js` | CommonJS | Node.js / legacy bundlers | | `dist/index.d.ts` | TypeScript Declarations | Type checking and IDE support | ## What's Next? - [Configuration](/02-configuration) — Full configuration reference - [Events](/05-events) — Complete guide to event tracking --- # Configuration > Simple configuration example. ## Basic Configuration ```typescript import { Initializer } from '@segmentify/integration'; new Initializer({ domain: 'your-domain.com', apiKey: 'your-api-key', language: 'EN', currency: 'USD', spa: false, segmentifyApiUrl: '//your-api.segmentify.com', }); ``` ## Configuration Reference | Property | Type | Required | Description | | ------------------- | --------------------------------------------------- | -------- | ---------------------------------------------------------------------- | | `domain` | `string` | Yes | Your website domain | | `apiKey` | `string` | Yes | Your Segmentify API key | | `language` | `string` | Yes | Language code (e.g., `'EN'`, `'TR'`) | | `currency` | `string` | Yes | Currency code (e.g., `'USD'`, `'EUR'`) | | `spa` | `boolean` | Yes | Enable [SPA mode](/04-spa-mode) for client-side routing | | `segmentifyApiUrl` | `string` | Yes | Segmentify API endpoint URL | | `segmentifyPushUrl` | `string` | No | Custom push endpoint URL | | `debug` | `boolean \| 'DEBUG' \| 'INFO' \| 'WARN' \| 'ERROR'` | No | Enable debug logging — see [Logger](/11-logger) | | `searchify` | `boolean` | No | Enable Searchify integration | | `ga` | `object` | No | Google Analytics config (see below) | | `pageMap` | `PageMap` | No | Page type mapping — see [Page Mapping](/03-page-mapping) | | `doNotPersonalize` | `object` | No | Opt-out callback (see below) | | `allPageLogic` | `object` | No | Global pre/post execute — see [Page Mapping](/03-page-mapping) | | `user` | `User` | No | Pre-set user info — see [User Identification](/06-user-identification) | ## Google Analytics ```typescript new Initializer({ // ...required fields ga: { enabled: true, ga4: true, // true for GA4, false for Universal Analytics }, }); ``` ## Do Not Personalize Provide a callback that returns `true` to opt out of personalization: ```typescript new Initializer({ // ...required fields doNotPersonalize: { cb: () => !hasConsent(), // e.g., check GDPR preferences }, }); ``` ## Initialization Behavior - Calling `new Initializer()` twice logs a warning and skips the second call. - The Segmentify SDK script is loaded asynchronously after DOM ready. - Any events queued from the previous page are drained automatically. ## See Also - [Page Mapping](/03-page-mapping) - [SPA Mode](/04-spa-mode) - [Logger](/11-logger) --- # Page Mapping > Page mapping defines how URLs on your site map to Segmentify page types. When configured, the library automatically detects the current page and sends the appropriate tracking event. ## How It Works When you provide a `pageMap` in your config, the library: 1. Matches the current URL against your configured patterns (or calls `externalObject`) 2. Determines the page type 3. Runs `preExecuteFunction` to gather page-specific data 4. Sends the tracking event 5. Runs `postExecuteFunction` after tracking ## Basic Page Map ```typescript import { Initializer } from '@segmentify/integration'; import type { PageMap } from '@segmentify/integration'; const pageMap: PageMap = { 'Home Page': { type: 'Home Page', pattern: ['/'], }, 'Product Page': { type: 'Product Page', pattern: ['/product/*', '/p/*'], }, 'Category Page': { type: 'Category Page', pattern: ['/category/*'], }, }; new Initializer({ // ...required fields pageMap, }); ``` ## Page Types | Page Key | Constant | Description | | ----------------------- | ---------------------------------- | ---------------------- | | `Home Page` | `PAGE_TYPES.HOME_PAGE` | Site homepage | | `Product Page` | `PAGE_TYPES.PRODUCT_PAGE` | Product detail pages | | `Category Page` | `PAGE_TYPES.CATEGORY_PAGE` | Category listing pages | | `Brand Page` | `PAGE_TYPES.BRAND_PAGE` | Brand-specific pages | | `Search Page` | `PAGE_TYPES.SEARCH_PAGE` | Search results | | `Empty Search Page` | `PAGE_TYPES.EMPTY_SEARCH_PAGE` | No-results search | | `Basket Page` | `PAGE_TYPES.BASKET_PAGE` | Shopping cart | | `Checkout Success Page` | `PAGE_TYPES.CHECKOUT_SUCCESS_PAGE` | Order confirmation | | `Register` | `PAGE_TYPES.REGISTER_PAGE` | User registration | | `Login` | `PAGE_TYPES.LOGIN_PAGE` | User login | | `Logout` | `PAGE_TYPES.LOGOUT_PAGE` | User logout | | `404 Page` | `PAGE_TYPES.FOUR_O_FOUR_PAGE` | Not found | | `Blog Page` | `PAGE_TYPES.BLOG_PAGE` | Blog content | | `Profile Page` | `PAGE_TYPES.PROFILE_PAGE` | User profile | | `Unknown Page` | `PAGE_TYPES.UNKNOWN_PAGE` | Unmatched pages | ## Pattern Matching Match pages using glob-style URL patterns. Multiple patterns per page — matches if **any** pattern hits: ```typescript 'Product Page': { type: 'Product Page', pattern: ['/product/*', '/p/*', '/item/*'], } ``` ## External Object Matching For SPAs where URL patterns aren't enough, determine the page type programmatically: ```typescript 'Product Page': { type: 'Product Page', externalObject: () => { const currentRoute = getAppRoute(); return currentRoute.name === 'product' ? 'Product Page' : null; }, } ``` If `externalObject` returns `null`, the matcher falls through to the next page config. ## Pre/Post Execute Functions `preExecuteFunction` runs **before** the tracking event — returns page-specific data: ```typescript 'Product Page': { type: 'Product Page', pattern: ['/product/*'], preExecuteFunction: async () => { const product = await getProductFromPage(); return { productId: product.id, title: product.name, price: product.price }; }, } ``` The return type is inferred from the page type: | Page Type | Expected Return Type | | ----------------------- | --------------------------------------------- | | `Product Page` | `ProductViewPayload` | | `Checkout Success Page` | `PurchasePayload` | | `Basket Page` | `BasketViewPayload` | | `Register` | `RegisterPayload` | | `Login` | `Omit` | | `Logout` | `Omit` | `postExecuteFunction` runs **after** the event completes: ```typescript 'Product Page': { type: 'Product Page', pattern: ['/product/*'], postExecuteFunction: () => { console.log('Product page tracked'); }, } ``` ## Additional Options | Option | Type | Description | | ----------------- | ------------------------------------------- | ----------------------------- | | `category` | `PageKey` | Page category override | | `brand` | `string \| () => string \| Promise` | Brand name or getter | | `subCategory` | `string \| () => string \| Promise` | Subcategory or getter | | `params` | `object \| () => object \| Promise` | Additional parameters | | `emptySearchPage` | `boolean` | Flag for empty search results | ## Full Example ```typescript const pageMap: PageMap = { 'Home Page': { type: 'Home Page', pattern: ['/'], }, 'Product Page': { type: 'Product Page', pattern: ['/product/*'], preExecuteFunction: () => ({ productId: document .querySelector('[data-product-id]') ?.getAttribute('data-product-id') || '', title: document.querySelector('h1')?.textContent || '', price: parseFloat(document.querySelector('.price')?.textContent || '0'), }), }, 'Basket Page': { type: 'Basket Page', pattern: ['/cart', '/basket'], preExecuteFunction: () => ({ totalPrice: getCartTotal(), productList: getCartItems(), }), }, 'Checkout Success Page': { type: 'Checkout Success Page', pattern: ['/order/success*'], preExecuteFunction: () => ({ totalPrice: getOrderTotal(), orderNo: getOrderNumber(), productList: getOrderItems(), }), }, 'Search Page': { type: 'Search Page', pattern: ['/search*'], }, }; ``` ## See Also - [SPA Mode](/04-spa-mode) — How page detection works with client-side routing --- # SPA Mode > Single Page Applications handle navigation client-side without full page reloads. The library has built-in SPA support to re-detect page types on route changes. ## Enabling SPA Mode Set `spa: true` in your [configuration](/02-configuration): ```typescript new Initializer({ // ...required fields spa: true, pageMap: { /* your page map */ }, }); ``` ## How It Works When enabled, the `Page` class: 1. Listens for URL changes via `popstate` events 2. Intercepts `pushState` and `replaceState` calls 3. Re-runs page detection on every navigation 4. Sends a new tracking event for each detected page You **don't need to manually call** tracking events on route change — the library handles it automatically. ## When to Use | Scenario | Use `spa: true` | | ---------------------------------------------- | --------------- | | React / Vue / Angular with client-side routing | Yes | | Next.js with full page reloads (`` tags) | No | | Next.js App Router with `Link` component | Yes | | Traditional multi-page site | No | | Hybrid (some pages reload, some don't) | Yes | ## Manual Alternative You can skip SPA mode and call events manually in your router: ```typescript router.afterEach(to => { if (to.name === 'product') { events.ProductView({ productId: to.params.id }); } else { events.PageView({ category: to.meta.category }); } }); ``` ## Cleanup When your SPA unmounts (e.g., micro-frontend), call `destroy()` to remove listeners: ```typescript initializer.destroy(); ``` ## See Also - [Configuration](/02-configuration) - [Page Mapping](/03-page-mapping) --- # Events > The `Events` class provides methods for tracking all types of user interactions on your e-commerce site. Every event is enriched with device info, session data, referrer, and user context before being sent to the Segmentify API. ## SegmentifyEventManager Use the `SegmentifyEventManager` singleton to access the shared `Events` instance. This is the recommended approach — it guarantees a single instance across your app: ```typescript import { SegmentifyEventManager } from '@segmentify/integration'; SegmentifyEventManager().PageView({ category: 'home' }); SegmentifyEventManager().ProductView({ productId: 'PROD-123', price: 99.99 }); ``` `SegmentifyEventManager()` creates an `Events` instance on first call and returns the same instance on subsequent calls. ::: tip You can also create an instance directly with `new Events()`, but `SegmentifyEventManager` ensures all parts of your app share the same queue and config. ::: ## Page View Track when a user visits a page: ```typescript await SegmentifyEventManager().PageView({ category: 'home', subCategory: 'main', params: { page: 'homepage' }, }); ``` ## Product View Track when a user views a product. The library automatically detects the traffic source (social, paid, search, etc.): ```typescript await SegmentifyEventManager().ProductView({ productId: 'PROD-123', title: 'Amazing Product', price: 99.99, oldPrice: 129.99, category: 'electronics', brand: 'TechBrand', inStock: true, url: 'https://example.com/product/123', image: 'https://example.com/images/product-123.jpg', colors: ['red', 'blue'], sizes: ['S', 'M', 'L'], }); ``` ## Basket Operations ### Add to Basket ```typescript await SegmentifyEventManager().BasketAdd({ productId: 'PROD-123', price: 99.99, quantity: 1, }); ``` ### Remove from Basket ```typescript await SegmentifyEventManager().BasketRemove({ productId: 'PROD-123', price: 99.99, quantity: 1, }); ``` ### View Basket ```typescript await SegmentifyEventManager().BasketView({ totalPrice: 299.97, productList: [ { productId: 'PROD-123', price: 99.99, quantity: 2 }, { productId: 'PROD-456', price: 99.99, quantity: 1 }, ], }); ``` ### Clear Basket ```typescript await SegmentifyEventManager().BasketClear({}); ``` ::: tip `basketId` is automatically generated from the user ID. You don't need to pass it manually. ::: ## Purchase Track completed purchases: ```typescript await SegmentifyEventManager().Purchase({ totalPrice: 299.97, orderNo: 'ORDER-789', productList: [ { productId: 'PROD-123', price: 99.99, quantity: 2 }, { productId: 'PROD-456', price: 99.99, quantity: 1 }, ], paymentType: 'credit_card', coupon: 'SAVE10', tax: 30.0, shipment: 5.99, }); ``` ## Checkout Steps Track checkout funnel progression for drop-off analysis: ```typescript // Step 1: Customer information await SegmentifyEventManager().CustomerInformation({ totalPrice: 199.99, productList: [{ productId: 'SKU-100', quantity: 1, price: 199.99 }], }); // Step 2: Payment information await SegmentifyEventManager().PaymentInformation({ totalPrice: 199.99, orderNo: 'pending', productList: [{ productId: 'SKU-100', quantity: 1, price: 199.99 }], }); // Step 3: Purchase (see above) ``` ## User Operations ### Register ```typescript await SegmentifyEventManager().Register({ email: 'newuser@example.com', username: 'newuser', }); ``` ### Log In ```typescript await SegmentifyEventManager().LogIn({ email: 'user@example.com', username: 'johndoe', }); ``` ### Log Out ```typescript await SegmentifyEventManager().Logout({}); ``` ### Identify (Update Profile) Update user profile data without triggering a login/register event: ```typescript await SegmentifyEventManager().Identify({ email: 'user@example.com', source: 'email-collection', isRegistered: true, }); ``` The `Identify` method also handles special source types: - `source: 'email-collection'` automatically sets `emailNtf: true` - `source: 'whatsapp-collection'` automatically sets `whatsappNtf: true` ### IYS Permission (Turkey Compliance) Record IYS consent for commercial communications: ```typescript await SegmentifyEventManager().IysPermission({ email: 'user@example.com', phone: '+905551234567', }); ``` ## Favorites / Wishlist ### Add to Favorites ```typescript await SegmentifyEventManager().FavoriteAdd({ productId: 'SKU-999', favoritesList: ['SKU-1', 'SKU-2', 'SKU-999'], }); ``` ### Remove from Favorites ```typescript await SegmentifyEventManager().FavoriteRemove({ productId: 'SKU-999', favoritesList: ['SKU-1', 'SKU-2'], }); ``` ### View Favorites ```typescript await SegmentifyEventManager().FavoriteView({ favoritesList: ['SKU-1', 'SKU-2'], }); ``` ### Favorite Detail ```typescript await SegmentifyEventManager().FavoriteDetail({ favoritesList: ['SKU-1', 'SKU-2', 'SKU-3'], }); ``` ## Form Tracking Track form submissions for lead capture and analytics: ```typescript await SegmentifyEventManager().Form({ formName: 'contact', fields: { name: 'John', message: 'Hello' }, instanceId: 'contact-form-1', }); ``` ## Interaction Tracking Track clicks, scroll events, or custom UI interactions: ```typescript await SegmentifyEventManager().Interaction({ type: 'click', instanceId: 'hero-banner-1', interactionId: 'cta-button', }); ``` ## Gamification ### Wheel of Fortune ```typescript await SegmentifyEventManager().GamificationWof({ type: 'win', win: '10%_discount', instanceId: 'wof-banner-1', }); ``` ### Scratch Card ```typescript await SegmentifyEventManager().GamificationScratch({ type: 'win', win: 'free_shipping', instanceId: 'scratch-card-1', }); ``` ## Advanced: sendEvent All methods above are convenience wrappers around `sendEvent`. You can call it directly for custom events: ```typescript await SegmentifyEventManager().sendEvent({ name: 'CUSTOM_EVENT', type: 'my_custom_type', params: { key: 'value' }, }); ``` ### Delayed Events Send an event after a delay (e.g., engagement tracking): ```typescript await SegmentifyEventManager().sendEvent( { name: 'CUSTOM_EVENT', type: 'scroll-depth', params: { depth: 75 } }, { timeout: 3000 } // 3 second delay ); ``` ### Deferred Events Queue an event for the next page load: ```typescript await SegmentifyEventManager().sendEvent({ name: 'PRODUCT_VIEW', productId: 'SKU-42', nextPage: true, // Saved to localStorage, sent on next page }); ``` ## Event Methods Summary | Method | Internal Event Name | Step | | --------------------- | ------------------- | ---------------- | | `PageView` | `PAGE_VIEW` | — | | `ProductView` | `PRODUCT_VIEW` | — | | `BasketView` | `CHECKOUT` | `view-basket` | | `BasketAdd` | `BASKET_OPERATIONS` | `add` | | `BasketRemove` | `BASKET_OPERATIONS` | `remove` | | `BasketClear` | `BASKET_OPERATIONS` | `clear` | | `Purchase` | `CHECKOUT` | `purchase` | | `CustomerInformation` | `CHECKOUT` | `customer-info` | | `PaymentInformation` | `CHECKOUT` | `payment-info` | | `Register` | `USER_OPERATIONS` | `signup` | | `LogIn` | `USER_OPERATIONS` | `signin` | | `Logout` | `USER_OPERATIONS` | `signout` | | `Identify` | `USER_OPERATIONS` | `update` | | `IysPermission` | `USER_OPERATIONS` | `iyspermissions` | | `FavoriteAdd` | `WISHLIST` | `add` | | `FavoriteRemove` | `WISHLIST` | `remove` | | `FavoriteView` | `WISHLIST` | `view-favorites` | | `FavoriteDetail` | `WISHLIST` | `detail` | | `Form` | `FORM` | — | | `Interaction` | `INTERACTION` | — | | `GamificationWof` | `GAMIFICATION` | `win` | | `GamificationScratch` | `GAMIFICATION` | `win` | | `ErrorHandler` | `CUSTOM_EVENT` | — | ## See Also - [Queue — How Events Are Processed](/10-queue) - [Error Handling](/07-error-handling) --- # User Identification > The library manages user sessions and identity tracking automatically via cookies and the Segmentify API. ## Session & User IDs Every event is enriched with two IDs managed as cookies: | Cookie | Lifetime | Purpose | | ----------------- | -------- | -------------------------------------------- | | `_sgf_session_id` | 24 hours | Identifies a single browsing session | | `_sgf_user_id` | 1 year | Persists across sessions for returning users | These are created automatically on the first event. If either is missing, the library fetches new IDs from the Segmentify API. ## Linking to Known Users You can associate tracked behavior with a known user via: - **`user` in config** — set at initialization (see [Configuration](/02-configuration)) - **`email` / `externalId` in event payloads** — passed on any event call - **`Register`, `LogIn`, `Identify` events** — dedicated user operations (see [Events](/05-events)) ## Platform Detection The library detects the user's device automatically using the Bowser library: | Platform | Value | | -------- | ---------- | | Desktop | `'PC'` | | Mobile | `'mobile'` | | Tablet | `'tablet'` | This is included in every event payload as part of the enriched `ExtendedPayload`, along with OS name, OS version, and browser. ## See Also - [Events — User Operations](/05-events#user-operations) --- # Error Handling > The library provides built-in error tracking at multiple levels, reporting client-side errors back to the Segmentify API. ## The ErrorHandler Event Send error information explicitly via `SegmentifyEventManager().ErrorHandler`: ```typescript try { await SegmentifyEventManager().ProductView(payload); } catch (error) { await SegmentifyEventManager().ErrorHandler(error as Error); } ``` This sends a `CUSTOM_EVENT` with type `error_handler` containing the error message. ## Internal Error Handling The library catches errors internally so a single failure doesn't break the integration: - **Initializer** — wraps setup steps in try-catch. Logs the error, sends an `ErrorHandler` event, and continues for non-critical failures. - **Events** — if a single event fails (network error, bad response), it's skipped and the [queue](/10-queue) continues processing. - **Page Detection** — if `preExecuteFunction` or `postExecuteFunction` throws, the error is caught and logged. ## Best Practices 1. **Wrap custom callbacks in try-catch** — handle errors in your `preExecuteFunction` / `postExecuteFunction` to prevent breaking page detection. 2. **Use debug mode during development** — set `debug: true` to see error traces in the console (see [Logger](/11-logger)). 3. **Monitor ErrorHandler events** — check your Segmentify dashboard for `CUSTOM_EVENT` entries with type `error_handler`. ## See Also - [Events](/05-events) - [Logger](/11-logger) --- # ReactiveStore > ReactiveStore is an in-memory key-value store backed by the window object with Proxy-based validation. The library uses it internally to hold configuration and runtime state. ## Usage All methods are static: ```typescript import { ReactiveStore } from '@segmentify/integration'; ReactiveStore.set('myKey', 'myValue'); const value = ReactiveStore.get('myKey'); // 'myValue' ReactiveStore.has('myKey'); // true ReactiveStore.remove('myKey'); ReactiveStore.getAll(); // { ... } ReactiveStore.clear(); ``` `set`, `remove`, and `clear` return the class for chaining: ```typescript ReactiveStore.set('lang', 'EN').set('currency', 'USD'); ``` ## Validators Attach validation functions to keys. Invalid values throw an error: ```typescript ReactiveStore.addValidator( 'apiKey', v => typeof v === 'string' && v.length > 0 ); ReactiveStore.set('apiKey', 'abc123'); // OK ReactiveStore.set('apiKey', ''); // throws Error ``` ## Internal Keys | Key | Purpose | | ----------------------------- | ------------------------------ | | `__store:SegmentifyConfig` | The `SegmentifyConfig` object | | `__store:SegmentifyPage` | The `pageMap` configuration | | `__store:__segmentifyReady__` | `true` when SDK is loaded | | `__segmentify:initialized__` | Prevents double initialization | ::: warning Avoid overwriting these keys — doing so may break the library. ::: ## ReactiveStore vs PersistedStore | Feature | ReactiveStore | PersistedStore | | -------------------- | ----------------- | --------------------------- | | Storage | `window` (memory) | `localStorage` (persistent) | | Survives page reload | No | Yes | | Validators | Yes | No | | Value type | Any | Strings only | | Use case | Runtime state | User data, event queues | ## See Also - [PersistedStore](/09-persisted-store) --- # PersistedStore > PersistedStore is a thin static wrapper around window.localStorage for persisting data across page reloads. ## Usage ```typescript import { PersistedStore } from '@segmentify/integration'; PersistedStore.setItem('myKey', 'myValue'); const value = PersistedStore.getItem('myKey'); // 'myValue' PersistedStore.removeItem('myKey'); PersistedStore.clear(); ``` ## Storing Objects Since `localStorage` only stores strings, serialize objects: ```typescript PersistedStore.setItem('user', JSON.stringify({ email: 'user@example.com' })); const parsed = JSON.parse(PersistedStore.getItem('user') || 'null'); ``` ## Internal Keys The library uses `PersistedStore` for data that must survive page reloads: | Key | Purpose | | ---------------------------------- | ------------------------------------- | | `__store:__segmentifyEventQueue__` | Events deferred with `nextPage: true` | | `sgfUserUpdateData` | Cached user identification data | ::: warning Avoid overwriting these keys — the library depends on them. ::: For how `ReactiveStore` and `PersistedStore` compare, see the [comparison table in ReactiveStore](/08-reactive-store#reactivestore-vs-persistedstore). ## See Also - [ReactiveStore](/08-reactive-store) --- # Queue > The `Queue` class is a generic FIFO (First-In, First-Out) linked list used internally by the `Events` class to process tracking events in order. ## Usage ```typescript import { Queue } from '@segmentify/integration'; const queue = new Queue(); queue.enqueue('first', 'second', 'third'); queue.getHead(); // 'first' queue.getTail(); // 'third' queue.length; // 3 queue.dequeue(); // removes 'first' queue.dequeueBy(2); // removes next 2 items ``` ## How Events Uses the Queue When you call any event method (`PageView`, `Purchase`, etc.), the enriched payload is enqueued and a drain loop sends them sequentially: - **Order preserved** — events sent in the order triggered - **No duplication** — only one drain loop runs at a time - **Resilient** — a failed event is skipped, the next one processes ## Custom Implementation The `Events` constructor accepts any queue implementing `IQueue`: ```typescript import type { IQueue } from '@segmentify/integration'; class MyQueue implements IQueue { length = 0; enqueue(...args: T[]) { /* ... */ } dequeue() { /* ... */ } dequeueBy(count: number) { /* ... */ } getHead(): T | undefined { /* ... */ } getTail(): T | undefined { /* ... */ } } const events = new Events(new MyQueue()); ``` ## See Also - [Events](/05-events) --- # Logger > The `Logger` class provides structured console logging with prefixes and grouping. All output is gated behind the `debug` config flag — when off, nothing is logged. ## Usage ```typescript import { getLogger } from '@segmentify/integration'; const logger = getLogger(); logger.log('Something happened'); logger.info('Info message'); logger.warn('Warning'); logger.error('Error'); ``` All output is prefixed with `[Segmentify]` by default. ## Component Prefixes Create scoped loggers for different parts of your code: ```typescript const eventsLogger = getLogger().withPrefix('Events'); eventsLogger.log('Event sent'); // Output: [Segmentify] [Events] Event sent ``` Each `withPrefix` call creates a new instance — scoped loggers don't affect each other. ## Console Grouping ```typescript const logger = getLogger(); logger.group('Processing events'); logger.log('Event 1 sent'); logger.log('Event 2 sent'); logger.groupEnd(); ``` ## Runtime Updates Toggle debug mode or change the prefix without re-initializing: ```typescript import { updateLoggerConfig } from '@segmentify/integration'; updateLoggerConfig({ debug: false }); updateLoggerConfig({ debug: true, prefix: '[MyApp]' }); ``` ## Checking Debug State ```typescript if (getLogger().isDebugEnabled()) { getLogger().log('Detailed debug info', expensiveComputation()); } ``` ## See Also - [Configuration - `debug` option](/02-configuration) --- # Copy for LLMs > Give this documentation, or a Google Doc, to an LLM as clean Markdown LLMs such as Claude or ChatGPT read Markdown far better than a copied web page or a Word-style document: headings, lists, tables and code blocks keep their structure, and no navigation, styling or long URLs waste the context window. This site, and the Google Docs we write alongside it, can both be handed to an LLM as Markdown. ## Copy a page of this site - **Copy for LLMs**: the button under the title of every page copies the page as Markdown (title, description and content). Paste it into the LLM. - **View as Markdown**: every page is also served as a Markdown file: replace the trailing slash of the page address with `.md`, so `…/some-page/` becomes `…/some-page.md`. - **llms.txt**: [`llms.txt`](../llms.txt) lists every page of the site with a link to its Markdown file, following the [llms.txt](https://llmstxt.org/) convention. Give its address to an LLM or agent that can browse. - **llms-full.txt**: [`llms-full.txt`](../llms-full.txt) is the whole site in one Markdown file, for a tool that should read all of it at once. ## Export a Google Doc as Markdown (Google Docs Copy for LLMs) Specs, analyses and meeting notes often start in Google Docs. To give one to an LLM, or to move it into this documentation, export it as Markdown with the **Better Google Docs Copy** Chrome extension (its project is called "Google Docs Copy for LLMs"): 1. Install it from the [Chrome Web Store](https://chromewebstore.google.com/detail/better-google-docs-copy/faciokbjemdddkjokcajndenapikgcml). 2. Open the Google Doc and click **Copy for LLM**. 3. The first time, sign in with your Google account and allow access. The extension reads the document through the Google Docs API and its comments through the Google Drive API. 4. Choose whether to copy the selected text or the whole document, then paste the Markdown where you need it. What it adds over a plain copy: - **Comments**: comment threads come along with the passage they were left on, so the LLM sees the review discussion too. - **Images**: Google's very long image URLs are replaced with short references, so they do not fill the context window. - **Options** (right-click the extension icon, then Options): heading style (ATX `# Heading` or Setext), comment format (XML tags, blockquote or quoted context) and whether resolved comments are included. The extension runs in the browser and only talks to Google's APIs. Before pasting a document into an external LLM, check that it holds no customer data, credentials or other information that must not leave the company. ### Without the extension Google Docs can export Markdown itself, without comments: - **Whole document**: File → Download → Markdown (.md). - **A selection**: turn on Tools → Preferences → Enable Markdown, then use Edit → Copy as Markdown. ## Move a Google Doc into this documentation 1. Export the doc as Markdown as described above (leave comments out, or resolve them first). 2. Save it as a new `.md` file under `src/content/docs/`, with `title` and `description` front matter. 3. Add the page to the `sidebar` in `astro.config.mjs`, and open a pull request.