# التثبيت بالذكاء الاصطناعي

الصق أمر واحد في وكيل البرمجة. يقرأ مشروعك، ويركّب datacub، ويتتبّع الإجراءات القليلة اللي تهم، ويتأكد إن الأحداث توصل.

## 1. انسخ الأمر

اختر منصتك وانسخ. نفس الأمر، ومعه معرّف مشروعك جاهز، موجود ورا زر **انسخ الأمر** في [الإعدادات، الربط والذكاء الاصطناعي](https://datacub.to/ar/settings?tab=integrations).

```text none
You are connecting datacub to this website or web app. datacub is product analytics: once it is set up, the team sees where people come from, how many sign up, what they do, who pays and who comes back. For that, datacub needs three things from you, and all three matter equally: its script on every page, the signed-in user's id, and named events for the moments that matter to this business. The install alone only counts page views; identify and the events are what turn them into sign ups, payments and returning customers, so an install without them is not done. Do all three yourself, from the code, in this one task. Do not stop after the install to ask whether to add the rest, do not ask me to describe the business or to pick event names, and do not wait for my yes: decide. Touch nothing unrelated.

Talk to me in Arabic. Keep code, event names and property names in English.

Project ID: not filled in yet: ask me for it (8 letters and digits; datacub shows it under Settings, Integrations)
Never put any other datacub credential (read keys rk_, MCP tokens datacub_mcp_) in code, and never print secrets from .env files.
Reference, if a step is unclear: the datacub agent skill https://docs.datacub.to/skill/datacub/SKILL.md and the docs https://docs.datacub.to/llms.txt. This prompt wins where they differ.

Done means all of these are true:
[ ] The datacub script tag is in the <head> of every page, with exactly this project ID and address.
[ ] window.datacub?.identify(user.id) runs after login and after signup succeed; window.datacub?.reset() runs on logout.
[ ] At least 3 business events fire, and usually 5 to 10: sign up, payment and this product's key actions (step 4), each in the code path where the action succeeded.
[ ] No personal data in events, no packages beyond the ones named here, the app still builds, and your report claims nothing you did not see.

1. Read the code first
README, package manifests, the pages or screens, and the login, signup and payment code. Note which files run in the browser or app and which on the server. Say in one or two sentences what the product does and for whom.

2. Install datacub
Web (any site or framework): one script tag that datacub serves.

    <script src="https://in.datacub.to/v1/sdk.js" data-id="YOUR_PROJECT_ID" defer></script>

Where it goes:
- Plain HTML site: the <head> of EVERY .html page, not only index.html.
- Vite or Create React App: index.html.
- Next.js App Router: app/layout.tsx. Put <head> with this same tag inside <html>, before <body>.
- Next.js Pages Router: pages/_document.tsx, inside <Head>.
- TanStack Start: the root route's head scripts. Anything else: the root HTML template.
The tag defines window.datacub and captures page views, route changes in single page apps, and clicks by itself: add no page view or click tracking. To give an important button a readable name in reports, add data-datacub-name="upgrade_plan" to it.
With the tag, always call window.datacub?.track(...), window.datacub?.identify(...) and window.datacub?.reset(), in browser code only (event handlers, effects), never on the server. The ?. keeps the app working when an ad blocker stops the script. The tag is deferred, so a call in a plain script that runs while the page is still loading (not in an event handler or effect), such as identify for a saved session, goes inside document.addEventListener('DOMContentLoaded', () => { ... }) or it is lost.
In TypeScript, add datacub.d.ts (in src/ for Vite, the project root for Next.js) so window.datacub is typed:

    declare global {
      interface Window {
        datacub?: {
          track(event: string, props?: Record<string, string | number | boolean>): void
          identify(id: string, traits?: { email?: string; name?: string; phone?: string }): void
          reset(): void
        }
      }
    }
    export {}

Use the tag. Only an app without an HTML template of its own may use npm instead, never both: run npm install @datacub/web, start it once in client code (the client entry, never server code), and call datacub.track(...) after import datacub from '@datacub/web'. Install only the exact package names given here (@datacub/web, @datacub/react-native). Never install any other package under @datacub, or one whose name looks like datacub.

    import datacub from '@datacub/web'

    datacub.init('YOUR_PROJECT_ID')

Do not copy the SDK file into the repository.
Add no consent banner or datacub.consent calls: datacub tracks from the first page view or screen.

3. Identify the user
Where login and signup succeed (after the response, where the app stores the user): window.datacub?.identify(user.id, { email: user.email, name: user.name }), leaving out traits the user object does not have. The first argument is the app's own stable user id, never an email, phone, national ID or name. Pass traits at login or when they change, not on every page load. Also call window.datacub?.identify(user.id), without traits, where the app restores an already signed-in user at start (a saved session), so people who signed in before datacub was added are counted too. On logout, after it succeeds: window.datacub?.reset(), or the next person on the device inherits the last user's activity.

4. Add the business events
These are what datacub's funnels, retention and revenue reports are built from. Add at least 3; most products need 5 to 10; stop around 12. Choose each event because the team would act on its number (how many sign up, start using the product, pay, come back, leave), never to log every button.
Walk the customer's life in this app and add an event wherever the app has the action:
- Sign up: signup_completed when an account is created. Props: { method: 'email' } (or 'google', 'phone').
- First value: the moment a new user first gets what they came for, e.g. onboarding_completed, project_created, first booking.
- Core use: the action people come back to repeat, e.g. order_placed, booking_created, task_completed, lesson_completed.
- Money: checkout_completed when a payment, order or subscription succeeds, with the plan or product and the amount as a number, e.g. { plan: 'pro', amount: 399, currency: 'SAR' }. Also subscription_started, payment_failed.
- Growth: teammate_invited, referral_sent, review_submitted, item_shared.
- Leaving or stuck: subscription_cancelled ({ reason } when the app has one), booking_cancelled, account_deleted, search_completed with { has_results: false }.
Ideas by kind of product. Name events after this app's real actions; do not copy a list:
- SaaS: signup_completed, onboarding_completed, project_created, teammate_invited, integration_connected, report_exported, subscription_started, subscription_cancelled.
- Store: signup_completed, search_completed, cart_item_added, coupon_applied, checkout_started, checkout_completed, review_submitted.
- Bookings and services: signup_completed, booking_created, deposit_paid, booking_rescheduled, booking_cancelled.
- Delivery or marketplace app: signup_completed, cart_item_added, order_placed, checkout_completed, order_rated, subscription_started.
- Learning or content: course_enrolled, lesson_completed, quiz_passed, certificate_earned.
Not business events: page_viewed, screen_viewed, button_clicked, modal_opened, tab_switched, form_started. datacub captures views and clicks by itself.
One event per outcome: a purchase is one checkout_completed, never also order_placed for the same order. With phone OTP or Google sign-in, send signup_completed only when the app knows the account is new (an isNew flag, a separate register call); a returning user is a login.
A page that confirms a payment after a redirect (the Stripe, Moyasar, Tap or HyperPay return page) fires checkout_completed once per order: only when it shows the payment succeeded, and remember the order or session id in sessionStorage so a reload or a revisit does not count it again. That guard skips only the track call, never the page's own code.
Names are snake_case, object then past-tense action. Use one event with a property for variants (booking_created { service: 'dental' }), not one event per variant. If the app truly has fewer than 3 such actions (a one-page site), add what exists and say why in the report.
Check for existing analytics calls first. Put each call in the success branch, right after the awaited API call returns and before any redirect (the SDK delivers events sent just before a page change). If the app's request helper does not throw on an error status, check the response where you track; never change the helper itself or how existing code behaves: window.datacub?.track('signup_completed', { method: 'email' }). Never on the button click, never in render or code that re-runs, never on the server; one call per outcome. Properties are flat and low-cardinality (plan, method, step, count, amount, true or false).
Never send passwords, OTPs, tokens, card data, IBANs, national or Iqama IDs, emails, phone numbers, names, addresses or text a person typed in event names or properties (identify traits are the only place for email, name and phone).

5. Check your work
- grep that the tag is on every page and the ID is YOUR_PROJECT_ID.
- Build or type-check the project if its dependencies are there (node_modules exists). Do not install them only to check (that leaves a new lockfile): read your edits back instead.
- curl -sI https://in.datacub.to/v1/sdk.js should answer 200.
- If you can run the app (start any dev server in the background and stop it when you are done, so you never hang waiting on it) in a normal browser, open a page and do one business action: the POST to https://in.datacub.to/v1/batch answers 200 with "accepted" of 1 or more, and datacub's setup page turns green. A 403 names the reason: name it in your report. Headless browsers (Playwright, Puppeteer) count as bots, so their events stay out of reports: check the POST answer. If you cannot run it, say so; never claim you saw events arrive.

6. Report in a few lines
Where the tag went; a table of every event with its properties and the file it fires in; where identify and reset are, what you checked and what you could not, and what I must do, if anything.

Feature flags and A/B tests: skip this unless I ask for one. Then add <script src="https://in.datacub.to/v1/flags.js"></script> right after the datacub tag, and use await window.datacub?.flag('key') (true or false) or await window.datacub?.experiment('key') ('A' the original, 'B' the new version) where that version is actually shown. Use the key of a flag or experiment created in datacub; never invent one. A flag is never a permission check: keep those on the server.

```

لتطبيق React Native أو Expo:

```text none
You are connecting datacub to this mobile app. datacub is product analytics: once it is set up, the team sees where people come from, how many sign up, what they do, who pays and who comes back. For that, datacub needs three things from you, and all three matter equally: its SDK started once, the signed-in user's id, and named events for the moments that matter to this business. The install alone only counts page views; identify and the events are what turn them into sign ups, payments and returning customers, so an install without them is not done. Do all three yourself, from the code, in this one task. Do not stop after the install to ask whether to add the rest, do not ask me to describe the business or to pick event names, and do not wait for my yes: decide. Touch nothing unrelated.

Talk to me in Arabic. Keep code, event names and property names in English.

Project ID: not filled in yet: ask me for it (8 letters and digits; datacub shows it under Settings, Integrations)
Never put any other datacub credential (read keys rk_, MCP tokens datacub_mcp_) in code, and never print secrets from .env files.
Reference, if a step is unclear: the datacub agent skill https://docs.datacub.to/skill/datacub/SKILL.md and the docs https://docs.datacub.to/llms.txt. This prompt wins where they differ.

Done means all of these are true:
[ ] The datacub SDK starts once, at the top of the app entry, with exactly this project ID.
[ ] datacub.identify(user.id) runs after login and after signup succeed; datacub.reset() runs on logout.
[ ] At least 3 business events fire, and usually 5 to 10: sign up, payment and this product's key actions (step 4), each in the code path where the action succeeded.
[ ] No personal data in events, no packages beyond the ones named here, the app still builds, and your report claims nothing you did not see.

1. Read the code first
README, package manifests, the pages or screens, and the login, signup and payment code. Note which files run in the browser or app and which on the server. Say in one or two sentences what the product does and for whom.

2. Install datacub
React Native or Expo (beta). datacub's React Native SDK is in beta: tell me so in your report. Install only the exact package names given here (@datacub/web, @datacub/react-native). Never install any other package under @datacub, or one whose name looks like datacub.

Install it with its two companions, using exactly this command (it picks versions that match the app's Expo SDK). Never write versions into package.json by hand. Run it with a time limit (about 5 minutes) or in the background; if it fails or hangs, stop it, tell me to run it myself, and still do every other step (init, identify, events) so the code is ready:

    npx expo install @datacub/react-native@next @react-native-async-storage/async-storage expo-application

Start it once, at the top of the app's entry (App.tsx, or app/_layout.tsx with Expo Router), then import datacub from '@datacub/react-native' wherever you call datacub.track(...):

    import AsyncStorage from '@react-native-async-storage/async-storage'
    import * as Application from 'expo-application'
    import datacub from '@datacub/react-native'

    datacub.init('YOUR_PROJECT_ID', {
      storage: AsyncStorage,
      app: Application,
    })

Screen views: with React Navigation, import { trackNavigation } from '@datacub/react-native/navigation' and call trackNavigation(ref) in the NavigationContainer's onReady, with ref from useNavigationContainerRef(). With Expo Router, call datacub.screen(segments.join('/') || 'index') in an effect on useSegments() in the root layout. Send route names or templates, never values. Add no other screen tracking.
In a bare React Native app without expo-application, pass app: { applicationId, nativeApplicationVersion, nativeBuildVersion } instead. A new project accepts any app, so no bundle ID needs adding.
Swift, Kotlin, Flutter and other native stacks are not supported yet: say so plainly.
Add no consent banner or datacub.consent calls: datacub tracks from the first page view or screen.

3. Identify the user
Where login and signup succeed (after the response, where the app stores the user): datacub.identify(user.id). The first argument is the app's own stable user id, never an email, phone, national ID or name. Also call datacub.identify(user.id), without traits, where the app restores an already signed-in user at start (a saved session), so people who signed in before datacub was added are counted too. On logout, after it succeeds: datacub.reset(), or the next person on the device inherits the last user's activity.

4. Add the business events
These are what datacub's funnels, retention and revenue reports are built from. Add at least 3; most products need 5 to 10; stop around 12. Choose each event because the team would act on its number (how many sign up, start using the product, pay, come back, leave), never to log every button.
Walk the customer's life in this app and add an event wherever the app has the action:
- Sign up: signup_completed when an account is created. Props: { method: 'email' } (or 'google', 'phone').
- First value: the moment a new user first gets what they came for, e.g. onboarding_completed, project_created, first booking.
- Core use: the action people come back to repeat, e.g. order_placed, booking_created, task_completed, lesson_completed.
- Money: checkout_completed when a payment, order or subscription succeeds, with the plan or product and the amount as a number, e.g. { plan: 'pro', amount: 399, currency: 'SAR' }. Also subscription_started, payment_failed.
- Growth: teammate_invited, referral_sent, review_submitted, item_shared.
- Leaving or stuck: subscription_cancelled ({ reason } when the app has one), booking_cancelled, account_deleted, search_completed with { has_results: false }.
Ideas by kind of product. Name events after this app's real actions; do not copy a list:
- SaaS: signup_completed, onboarding_completed, project_created, teammate_invited, integration_connected, report_exported, subscription_started, subscription_cancelled.
- Store: signup_completed, search_completed, cart_item_added, coupon_applied, checkout_started, checkout_completed, review_submitted.
- Bookings and services: signup_completed, booking_created, deposit_paid, booking_rescheduled, booking_cancelled.
- Delivery or marketplace app: signup_completed, cart_item_added, order_placed, checkout_completed, order_rated, subscription_started.
- Learning or content: course_enrolled, lesson_completed, quiz_passed, certificate_earned.
Not business events: page_viewed, screen_viewed, button_clicked, modal_opened, tab_switched, form_started. datacub captures views and clicks by itself.
One event per outcome: a purchase is one checkout_completed, never also order_placed for the same order. With phone OTP or Google sign-in, send signup_completed only when the app knows the account is new (an isNew flag, a separate register call); a returning user is a login.
A page that confirms a payment after a redirect (the Stripe, Moyasar, Tap or HyperPay return page) fires checkout_completed once per order: only when it shows the payment succeeded, and remember the order or session id in sessionStorage so a reload or a revisit does not count it again. That guard skips only the track call, never the page's own code.
Names are snake_case, object then past-tense action. Use one event with a property for variants (booking_created { service: 'dental' }), not one event per variant. If the app truly has fewer than 3 such actions (a one-page site), add what exists and say why in the report.
Check for existing analytics calls first. Put each call in the success branch, right after the awaited API call returns and before any redirect (the SDK delivers events sent just before a page change). If the app's request helper does not throw on an error status, check the response where you track; never change the helper itself or how existing code behaves: datacub.track('signup_completed', { method: 'email' }). Never on the button click, never in render or code that re-runs, never on the server; one call per outcome. Properties are flat and low-cardinality (plan, method, step, count, amount, true or false).
Never send passwords, OTPs, tokens, card data, IBANs, national or Iqama IDs, emails, phone numbers, names, addresses or text a person typed in event names or properties.

5. Check your work
- Read your edits back: the SDK starts once, before the first screen.
- Build or type-check the project if its dependencies are there (node_modules exists). Do not install them only to check (that leaves a new lockfile): read your edits back instead.
- If you can run the app (start any dev server in the background and stop it when you are done, so you never hang waiting on it) in a normal simulator or device, open a screen and do one business action: the POST to https://in.datacub.to/v1/batch answers 200 with "accepted" of 1 or more, and datacub's setup page turns green. A 403 names the reason: name it in your report. Headless browsers (Playwright, Puppeteer) count as bots, so their events stay out of reports: check the POST answer. If you cannot run it, say so; never claim you saw events arrive.

6. Report in a few lines
Where datacub.init went; a table of every event with its properties and the file it fires in; where identify and reset are, what you checked and what you could not, and what I must do, if anything.

```

## 2. الصقه في وكيلك

Claude Code أو Cursor أو Codex أو Windsurf أو أي وكيل يقدر يعدّل كودك ويشغّله. في Cursor، [افتح في Cursor](https://cursor.com/link/prompt?text=Integrate%20datacub%20product%20analytics%20into%20this%20project.%20Read%20the%20datacub%20skill%20at%20https%3A%2F%2Fdocs.datacub.to%2Fskill%2Fdatacub%2FSKILL.md%20and%20follow%20it%20step%20by%20step.%20Ask%20me%20for%20my%20datacub%20project%20ID%20(8%20letters%20and%20digits)%20when%20you%20need%20it.) يفتح المحادثة ومعها نسخة قصيرة من الأمر؛ وأنت تضغط إدخال بنفسك.

## 3. وش يسوي الوكيل

1. يقرأ كودك ويفهم وش يسوي منتجك وأي إطار تستخدم.
2. يضيف الـ SDK في المكان الصحيح، بمعرّف المشروع اللي تعطيه إياه.
3. يخلي مشاهدات الصفحات والنقرات على datacub، لأنه يجمعها بنفسه.
4. يعرّف المستخدمين المسجّلين بمعرّفك الداخلي، عند تسجيل الدخول والتسجيل الجديد ولما تنرجّع جلسة محفوظة، ويسوي reset عند تسجيل الخروج.
5. يتتبّع نتائج العمل المهمة، 3 على الأقل وغالبًا من 5 إلى 10 (التسجيل، الدفع، أهم أفعال المنتج)، بعد ما تنجح.
6. يضيف استدعاءات الموافقة بس إذا مشروعك يطلب الموافقة أولًا.
7. يشغّل التطبيق ويتأكد إن حدث تلقائي وحدث مخصص يوصلون datacub.
8. يقول لك باختصار وش غيّر وأي شيء باقي عليك، مثل السماح لنطاقك.

وما يحط مفاتيح سرية في كود الواجهة أبد، ولا يتتبّع كل زر، ولا يرسل إيميلات أو أرقام جوال أو اللي يكتبه الناس في خصائص الأحداث.

## مهارة datacub

[Agent Skill](https://agentskills.io) تعلّم أي وكيل متوافق كيف يركّب datacub، بدون ما تلصق أمر. أضفها مرة وحدة لكل مشروع، مثلًا في Claude Code:

```sh none
mkdir -p .claude/skills/datacub && curl -fsSL -o .claude/skills/datacub/SKILL.md https://docs.datacub.to/skill/datacub/SKILL.md
```

الوكلاء الثانيين يقرؤون المهارات من مجلدهم؛ والملف نفسه. بعدها قل له: "Integrate datacub into this project."

## اللي ما يسويه إلا أنت

- سجّل وسوّ المشروع في [datacub](https://datacub.to/ar/signup).
- انسخ معرّف مشروعك من [الإعدادات، عام](https://datacub.to/ar/settings?tab=general)، أو الصق الأمر من الإعدادات اللي فيه المعرّف جاهز.

وعشان وكيلك يقرأ تحليلاتك بعدها، اربطه عن طريق [MCP](https://docs.datacub.to/ar/mcp.md).
