# Omar Albeik — full text
> Software engineer, product designer, and digital transformation advisor in Amsterdam. Writes in Arabic and English about software, AI, and digital transformation.
Omar Albeik (Arabic: عمر البيك) is a software engineer, product
designer, and digital transformation advisor based in Amsterdam, the
Netherlands. He has been building software since 2008, and is currently a
senior software engineer at Booking.com, after Spotify, Backbase, and
Udacity. He runs Harf Labs, where he publishes most of his open source,
and started Unblock Syria, a volunteer-run initiative working to restore
digital access for Syrians.
He was born in Aleppo, Syria, left in 2012 because of the war, and has
lived in Amsterdam since 2019. He speaks Arabic, English, Turkish, and
Dutch. He writes in both Arabic and English about software, AI, digital
transformation, scalability, product engineering, careers, politics, and
Arabic calligraphy, and is a student of the thuluth script. This site,
omaralbeik.com, is his personal website.
Also known as: عمر البيك, Omar Al-Beik, Omar Al Beik, Omar Albayk, Omar Albaik, Omar Albeck, Omar Elbeik, Omar El-Beik, Omer Albeik, Omer Albeek, Umar Albeik, omaralbeik. All refer to the same person.
Every post exists in both English and Arabic; the two are translations
of one another, not separate content. For half the size, one language
at a time: https://omaralbeik.com/en/llms-full.txt and https://omaralbeik.com/ar/llms-full.txt.
NOTE: this file contains the full text of the 20 most
recent of 28 posts, which is as much as fits a 500KB budget.
The contents list below is complete, and every post — included here or
not — is individually available at its own URL with `.md` appended.
## Contents
Posts (English), 14:
- [A website on Cloudflare Workers: from local preview to your own domain](https://omaralbeik.com/en/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers) (tutorial, 6 November 2026) [Markdown](https://omaralbeik.com/en/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers.md)
- [Cloudflare Workers: from a request to a running application](https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-workers) (tutorial, 21 September 2026) [Markdown](https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-workers.md)
- [Cloudflare DNS: from buying a domain to a working website](https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-dns) (tutorial, 17 September 2026) [Markdown](https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-dns.md)
- [An introduction to Cloudflare's ecosystem](https://omaralbeik.com/en/blog/series/cloudflare/introduction-to-cloudflare) (article, 7 September 2026) [Markdown](https://omaralbeik.com/en/blog/series/cloudflare/introduction-to-cloudflare.md)
- [Drawing link previews that work in Arabic](https://omaralbeik.com/en/blog/link-previews-that-work-in-arabic) (tutorial, 31 August 2026) [Markdown](https://omaralbeik.com/en/blog/link-previews-that-work-in-arabic.md)
- [Syria is off the list](https://omaralbeik.com/en/blog/syria-is-off-the-list) (note, 26 August 2026) [Markdown](https://omaralbeik.com/en/blog/syria-is-off-the-list.md)
- [Why AI gets Arabic calligraphy wrong](https://omaralbeik.com/en/blog/why-ai-gets-arabic-calligraphy-wrong) (article, 7 August 2026) [Markdown](https://omaralbeik.com/en/blog/why-ai-gets-arabic-calligraphy-wrong.md)
- [Binding libVLC directly from Swift 6](https://omaralbeik.com/en/blog/binding-libvlc-directly-from-swift-6) (article, 3 August 2026) [Markdown](https://omaralbeik.com/en/blog/binding-libvlc-directly-from-swift-6.md)
- [Namespace your Swift extensions](https://omaralbeik.com/en/blog/namespace-your-swift-extensions) (article, 19 February 2022) [Markdown](https://omaralbeik.com/en/blog/namespace-your-swift-extensions.md)
- [Enforce SSH instead of HTTPS for Git operations](https://omaralbeik.com/en/blog/enforce-ssh-instead-of-https-for-git-operations) (tutorial, 23 August 2021) [Markdown](https://omaralbeik.com/en/blog/enforce-ssh-instead-of-https-for-git-operations.md)
- [Three comparisons the standard library already does](https://omaralbeik.com/en/blog/let-the-standard-library-compare) (note, 16 December 2019) [Markdown](https://omaralbeik.com/en/blog/let-the-standard-library-compare.md)
- [Property observers already give you the old and new value](https://omaralbeik.com/en/blog/property-observers-old-and-new-value) (note, 6 December 2019) [Markdown](https://omaralbeik.com/en/blog/property-observers-old-and-new-value.md)
- [A typealias can take a type parameter](https://omaralbeik.com/en/blog/generics-in-typealias) (note, 5 December 2019) [Markdown](https://omaralbeik.com/en/blog/generics-in-typealias.md)
- [When to use a safe collection subscript](https://omaralbeik.com/en/blog/safe-collection-subscript) (note, 12 July 2019) [Markdown](https://omaralbeik.com/en/blog/safe-collection-subscript.md)
Posts (Arabic), 14:
- [استضافة موقع على Cloudflare Workers: من التجربة المحلية إلى نطاقك الخاص](https://omaralbeik.com/ar/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers) (tutorial, 6 تشرين الثاني 2026) [Markdown](https://omaralbeik.com/ar/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers.md)
- [دليل Cloudflare Workers: من أول طلب إلى تطبيق يعمل](https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-workers) (tutorial, 21 أيلول 2026) [Markdown](https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-workers.md)
- [دليل Cloudflare DNS: من شراء النطاق إلى تشغيل الموقع](https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-dns) (tutorial, 17 أيلول 2026) [Markdown](https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-dns.md)
- [مدخل إلى منظومة Cloudflare](https://omaralbeik.com/ar/blog/series/cloudflare/introduction-to-cloudflare) (article, 7 أيلول 2026) [Markdown](https://omaralbeik.com/ar/blog/series/cloudflare/introduction-to-cloudflare.md)
- [معاينات الروابط بنص عربي سليم](https://omaralbeik.com/ar/blog/link-previews-that-work-in-arabic) (tutorial, 31 آب 2026) [Markdown](https://omaralbeik.com/ar/blog/link-previews-that-work-in-arabic.md)
- [سوريا خارج القائمة](https://omaralbeik.com/ar/blog/syria-is-off-the-list) (note, 26 آب 2026) [Markdown](https://omaralbeik.com/ar/blog/syria-is-off-the-list.md)
- [لماذا يُخطئ الذكاء الاصطناعيّ في الخطّ العربيّ](https://omaralbeik.com/ar/blog/why-ai-gets-arabic-calligraphy-wrong) (article, 7 آب 2026) [Markdown](https://omaralbeik.com/ar/blog/why-ai-gets-arabic-calligraphy-wrong.md)
- [ربط libVLC بـSwift 6 مباشرةً](https://omaralbeik.com/ar/blog/binding-libvlc-directly-from-swift-6) (article, 3 آب 2026) [Markdown](https://omaralbeik.com/ar/blog/binding-libvlc-directly-from-swift-6.md)
- [تنظيم إضافات Swift في فضاء أسماء مستقل](https://omaralbeik.com/ar/blog/namespace-your-swift-extensions) (article, 19 شباط 2022) [Markdown](https://omaralbeik.com/ar/blog/namespace-your-swift-extensions.md)
- [استخدام SSH تلقائيًا بدل HTTPS في Git](https://omaralbeik.com/ar/blog/enforce-ssh-instead-of-https-for-git-operations) (tutorial, 23 آب 2021) [Markdown](https://omaralbeik.com/ar/blog/enforce-ssh-instead-of-https-for-git-operations.md)
- [ثلاث مقارنات تفعلها المكتبة القياسيّة عنك](https://omaralbeik.com/ar/blog/let-the-standard-library-compare) (note, 16 كانون الأول 2019) [Markdown](https://omaralbeik.com/ar/blog/let-the-standard-library-compare.md)
- [القيمتان القديمة والجديدة في willSet وdidSet](https://omaralbeik.com/ar/blog/property-observers-old-and-new-value) (note, 6 كانون الأول 2019) [Markdown](https://omaralbeik.com/ar/blog/property-observers-old-and-new-value.md)
- [استخدام الأنواع العامة مع typealias في Swift](https://omaralbeik.com/ar/blog/generics-in-typealias) (note, 5 كانون الأول 2019) [Markdown](https://omaralbeik.com/ar/blog/generics-in-typealias.md)
- [متى نحتاج إلى subscript آمن في Swift؟](https://omaralbeik.com/ar/blog/safe-collection-subscript) (note, 12 تموز 2019) [Markdown](https://omaralbeik.com/ar/blog/safe-collection-subscript.md)
Pages, as Markdown:
- English: [Home](https://omaralbeik.com/en.md), [Blog](https://omaralbeik.com/en/blog.md), [Work](https://omaralbeik.com/en/work.md), [Calligraphy](https://omaralbeik.com/en/calligraphy.md), [Library](https://omaralbeik.com/en/library.md), [About](https://omaralbeik.com/en/about.md), [Contact](https://omaralbeik.com/en/contact.md)
- Arabic: [Home](https://omaralbeik.com/ar.md), [Blog](https://omaralbeik.com/ar/blog.md), [Work](https://omaralbeik.com/ar/work.md), [Calligraphy](https://omaralbeik.com/ar/calligraphy.md), [Library](https://omaralbeik.com/ar/library.md), [About](https://omaralbeik.com/ar/about.md), [Contact](https://omaralbeik.com/ar/contact.md)
---
# A website on Cloudflare Workers: from local preview to your own domain
- URL: https://omaralbeik.com/en/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers
- Markdown: https://omaralbeik.com/en/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers.md
- Translation: https://omaralbeik.com/ar/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers
- Author: Omar Albeik
- Language: en
- Type: tutorial
- Date: 6 November 2026
- Topics: infrastructure
The reading-time API from part three works from a terminal. Let's give it a page where someone can paste a paragraph, choose a language, and get an estimate.
That page can live alongside the API on Cloudflare Workers. The browser downloads HTML, CSS, and JavaScript as files. When the reader submits the form, our Hono handler does the calculation. Both use the same hostname.
We'll take it through local testing, a branch preview, and a release on your own domain. The useful part is learning to explain each response: which file or handler produced it, which settings it used, and whether the browser is showing the latest version.
Start with the `reading-api` project from [part three](/en/blog/series/cloudflare/understanding-cloudflare-workers). You should already have `src/index.ts`, `src/analyze.ts`, Hono, and Wrangler. We'll keep the analysis and validation code, then add a small frontend using plain HTML and JavaScript. Using plain files makes it easier to follow each request before introducing a framework.
- [Understand what gets served](#a-website-is-more-than-one-request).
- [Add the page and connect the API](#give-the-api-a-front-door).
- [Check routing and missing pages](#make-missing-pages-useful).
- [Deploy from Git and review a preview](#deploy-the-site-then-automate-releases).
- [Connect your domain](#put-it-on-your-own-domain).
- [Handle updates and framework builds](#cache-the-files-with-their-next-update-in-mind).
A reading-time calculator could run entirely in the browser, keeping the text on the reader's device. Here we are deliberately reusing the API to learn how a frontend and a Worker fit together. That setup becomes more useful when we add features such as saving drafts.
## A website is more than one request
Open the finished tool and the browser asks for the page. The HTML points to a stylesheet and a JavaScript file, so the browser requests those too. Submitting the form creates another request, this time to `/api/reading-time`.
The first three responses can be files prepared before the visit. The last depends on the paragraph the reader submitted.
[Workers Static Assets](https://developers.cloudflare.com/workers/static-assets/) lets us deploy those files with the Worker. We don't need a second hosting service or a separate server that reads them from disk. The asset directory contains the public files; the Worker entry point contains the server code.
This is also why “static” doesn't mean “nothing happens when you click.” A static HTML page can load JavaScript, call an API, and update its contents. The word describes how its initial response is produced.
**Three ways to put a page on the screen**
A single website can combine these approaches.
1. **Before the visit — Prerendered HTML**: A blog post is built into an HTML file, ready to serve when someone requests it.
2. **During the request — Server rendering**: The Worker generates HTML for this request, perhaps using the visitor's session or current data.
3. **After the page loads — Browser interaction**: JavaScript updates the page. Our reading tool calls an API and displays its response.
Browser interaction works with either prerendered or server-rendered HTML.
*Choose when to generate a response based on what it needs to know. Interactivity alone does not require server-rendered HTML.*
For our tool, the form is identical for every visitor. Generating that HTML on each request would add work without changing the answer. We'll serve it as a file and reserve the handler for the calculation.
## Where does Pages fit?
Cloudflare now [recommends Workers for new projects](https://developers.cloudflare.com/pages/). Workers supports static files, server code, Git builds, and branch previews. Pages still has its own deployment workflow and Pages Functions, so you will encounter both in existing projects and older tutorials.
For an existing Pages site, the decision deserves more context. Check the framework adapter, Functions routes, redirects, and preview workflow before migrating. Cloudflare's [Pages-to-Workers guide](https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/) covers those differences.
## Give the API a front door
Already have a frontend? Use its files in place of the form below, then follow the routing and deployment steps. If your framework generates a Worker bundle, use its adapter setup as described in the [Astro section](#what-changes-when-you-use-astro).
Inside `reading-api`, create a `public` directory. The project will look like this:
```text
reading-api/
├── public/
│ ├── index.html
│ ├── styles.css
│ ├── app.js
│ ├── 404.html
│ └── _headers
├── src/
│ ├── analyze.ts
│ └── index.ts
├── package.json
├── package-lock.json
└── wrangler.jsonc
```
Everything in `public` should be safe to download. Keep `.dev.vars`, configuration credentials, and server source outside it. Set the asset directory to the folder you intend to publish, never the repository root.
### Tell Wrangler which files to serve
Add this top-level property to the existing `wrangler.jsonc`. Keep its `main`, `vars`, and other settings from part three:
```jsonc title="wrangler.jsonc · add to the existing object"
{
"assets": {
"directory": "./public",
"binding": "ASSETS",
"not_found_handling": "404-page",
"run_worker_first": ["/api", "/api/*", "/health"]
}
}
```
`directory` selects the files to upload. `ASSETS` gives our handler a way to request an asset response. `404-page` selects an HTML error page for missing assets. The last line makes the API and health paths run the Worker first.
Keep the existing compatibility date while making this change; updating runtime behavior is a separate change to test. Regenerate the types so `CloudflareBindings` includes `ASSETS`:
```bash
npx wrangler types --env-interface CloudflareBindings
```
By default, a matching asset can answer without running our handler. The explicit [Worker-first paths](https://developers.cloudflare.com/workers/static-assets/routing/worker-script/) reserve the API namespace for Hono, even if a file happens to match it.
**One hostname, two ways to answer**
Explore the routing rules used in this article. These are illustrated requests; nothing is sent to an API.
1. **Open the homepage — GET /**: The asset service returns public/index.html. The Hono handler does not run.
Path: Browser → Static assets → 200 HTML
2. **Load the JavaScript — GET /app.js**: The asset service returns public/app.js. The browser then runs the file.
Path: Browser → Static assets → 200 JavaScript
3. **Analyze a paragraph — POST /api/reading-time**: Hono validates the input and calls analyzeReading(). For valid input, the page receives the estimate and displays it.
Path: Browser → Worker · Hono → 200 JSON
4. **Open the API as a page — GET /api/reading-time**: The response includes Allow: POST. Our /api/* rule keeps this request out of the HTML fallback.
Path: Browser → Worker · Hono → 405 JSON
5. **Follow a broken link — GET /missing**: The asset service returns public/404.html with status 404. The missing address stays in the URL bar.
Path: Browser navigation → Static assets → 404 HTML
API and health paths always run the Worker first. A non-navigation request for a missing file can also reach Hono, which forwards it to ASSETS.
*Loading the page and submitting the form reach the same hostname, but only the API request needs the calculation code.*
### Add the HTML
The page needs a labelled text area, a language selector, a reading-speed input, and somewhere to announce the result. In this version, the page collects input and displays the API's answer.
```html title="public/index.html"
Reading time
How long will this take to read?
Paste a paragraph and choose a pace to estimate its reading time.
```
`dir="auto"` lets the paragraph determine its text direction. It doesn't translate the interface: this is an English interface that accepts either language. The button starts disabled and becomes available when the script is ready, so a failed script won't accidentally submit the text through a default form navigation.
### Make it comfortable to use
Use readable type, visible focus, and controls that fit a narrow screen. No layout library is needed for this form.
```css title="public/styles.css"
:root {
font-family: system-ui, sans-serif;
line-height: 1.6;
color: #24211d;
background: #f8f6f1;
}
* { box-sizing: border-box; }
body { margin: 0; }
main { max-width: 42rem; margin: auto; padding: 2rem 1.25rem; }
h1 { line-height: 1.2; text-wrap: balance; }
label { display: block; margin-block: 1rem 0.35rem; font-weight: 600; }
textarea, select, input, button {
width: 100%;
font: inherit;
padding: 0.75rem;
border: 1px solid #81786d;
border-radius: 0.3rem;
}
textarea, select, input { color: inherit; background: #fff; }
textarea { resize: vertical; }
button { margin-top: 1.25rem; color: #fff; background: #29499c; }
button:disabled { opacity: 0.65; cursor: wait; }
:focus-visible { outline: 3px solid #29499c; outline-offset: 3px; }
.hint { font-size: 0.9rem; color: #5e564b; }
#result { min-height: 3rem; font-weight: 600; }
```
### Call the API from the browser
Create `public/app.js`. The relative URL is the important detail: `/api/reading-time` uses the origin of the page, whether that page is on localhost, a preview hostname, or your own domain.
```js title="public/app.js"
const form = document.querySelector("#reading-form");
const button = form.querySelector('button[type="submit"]');
const result = document.querySelector("#result");
form.addEventListener("submit", async (event) => {
event.preventDefault();
if (button.disabled) return;
const fields = new FormData(form);
button.disabled = true;
result.textContent = "Estimating…";
try {
const response = await fetch("/api/reading-time", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: fields.get("text"),
language: fields.get("language"),
wordsPerMinute: Number(fields.get("wordsPerMinute")),
}),
signal: AbortSignal.timeout(10_000),
});
const contentType = response.headers.get("content-type") ?? "";
if (!contentType.includes("application/json")) {
throw new Error("The server returned an unexpected response. Try again.");
}
const data = await response.json();
if (!response.ok) {
throw new Error(data.error ?? "The estimate could not be calculated.");
}
const words = data.words === 1 ? "word" : "words";
const seconds = data.seconds === 1 ? "second" : "seconds";
result.textContent =
`${data.words} ${words} · about ${data.seconds} ${seconds}` +
` at ${data.wordsPerMinute} words per minute.`;
} catch (error) {
if (error instanceof DOMException && error.name === "TimeoutError") {
result.textContent = "The request took too long. Please try again.";
} else if (error instanceof TypeError) {
result.textContent = "Couldn't reach the server. Check your connection.";
} else {
result.textContent = error instanceof Error
? error.message
: "Something went wrong. Please try again.";
}
} finally {
button.disabled = false;
}
});
button.disabled = false;
```
The browser checks the form's basic constraints before submitting, but the server must still validate every field. A caller can bypass the page entirely. The handler from part three also limits the request body and returns structured errors.
Notice that `fetch()` doesn't throw merely because the server returns `400` or `500`; we inspect `response.ok`. We also check the content type before reading JSON. If a routing mistake sends an HTML page, the reader gets an understandable error instead of a JSON parser complaint.
Using `textContent` displays the result without interpreting it as HTML.
The page and API share an origin, so this interaction needs no cross-origin CORS setup. The endpoint remains public; CORS does not authenticate callers.
### Set headers for the public files
For static response headers, create a `_headers` file in the asset directory:
```text title="public/_headers"
/*
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
```
These are asset-serving rules. They do not automatically add headers to JSON generated by Hono; configure those in the handler when needed. Likewise, a Hono middleware won't inspect a homepage request that the asset layer answers directly. If the files must be private, route their requests through authentication before returning any assets.
## Make missing pages useful
An unknown webpage should help a human find their way back. An unknown API endpoint should return an API error. Keep that distinction in the handler.
In `src/index.ts`, replace the existing `app.notFound(...)` block with:
```ts title="src/index.ts · replace app.notFound"
app.notFound((c) => {
const path = c.req.path;
const isApi = path === "/api" || path.startsWith("/api/");
const isPageRequest = c.req.method === "GET" || c.req.method === "HEAD";
if (isApi || !isPageRequest) {
return c.json({ error: "Not found." }, 404);
}
return c.env.ASSETS.fetch(c.req.raw);
});
```
Leave the existing routes, middleware, `app.onError`, and `export default app` in place. `ASSETS.fetch()` asks the asset service for a response; it doesn't make another public request back through Hono.
Now add the error page:
```html title="public/404.html"
Page not found · Reading time
That page isn't here.
The address may be wrong, or the page may have moved.
Open the reading-time tool
```
With the configured fallback, a missing page returns this HTML with a **404 status**, rather than redirecting every broken link to the homepage. Search engines and HTTP clients need the status as well as the message.
There is one routing detail worth testing explicitly. With `404-page` and a compatibility date of April 1, 2025 or later (including ours), browser navigation requests go straight to asset handling unless a Worker-first rule overrides it. They carry `Sec-Fetch-Mode: navigate`; an ordinary `curl` request does not. The reserved Worker-first paths keep `/health` and `/api/*` in Hono in both cases. Other missing GET requests can reach our fallback and then ask `ASSETS` for the 404 page. Cloudflare documents this in its [static-site routing guide](https://developers.cloudflare.com/workers/static-assets/routing/static-site-generation/).
Don't enable `single-page-application` just because the tool has one page. That option serves `index.html` as a successful fallback for a client-side router. Our application has no such router, so an invented address should remain a missing page.
## Run it locally and follow the requests
From the project directory:
```bash
npx tsc --noEmit
npx wrangler dev --local
```
If Wrangler reports that the compatibility date is newer than its local runtime, update the project dependency with `npm install --save-dev wrangler@latest`, regenerate types, and rerun the checks. Keep the resulting lockfile change.
Open the URL Wrangler prints, normally `http://localhost:8787`. Paste a short English paragraph, submit it, then repeat with Arabic and change the reading speed. The text goes to your local Worker in this setup.
Open the browser's Network panel before reloading. You should see the document, stylesheet, and script. Submit the form and look for the POST request. Its response should be JSON with the word count and estimate; the document itself doesn't need to reload.
These checks catch different mistakes:
| Request or action | Expected result |
| --- | --- |
| Open `/` | The form, with its styles and working button |
| Submit valid text | `POST /api/reading-time` returns `200` JSON |
| Send empty text directly to the API | `400` JSON from the server |
| Open `/api/reading-time` in the address bar | `405` JSON and `Allow: POST` |
| Open `/api/missing` | `404` JSON |
| Open `/missing` | Your error page with status `404` |
| Open `/health` | `200` JSON, even as a browser navigation |
| Go offline and submit | A connection message; the button becomes usable again |
You can reproduce the navigation distinction from the terminal:
```bash
curl -i http://localhost:8787/health \
-H 'Sec-Fetch-Mode: navigate'
curl -i http://localhost:8787/missing \
-H 'Sec-Fetch-Mode: navigate'
curl -i http://localhost:8787/api/reading-time \
-H 'Content-Type: application/json' \
--data '{"text":"Small tools deserve good interfaces.","language":"en"}'
```
The last request should count five words. At the default 200 words per minute, the API rounds the estimate up to two seconds. This is an adjustable reading-speed assumption, not a measurement of a particular reader.
## Deploy the site, then automate releases
For a first manual release, check the bundle before publishing:
```bash
npx wrangler deploy --dry-run
```
This prepares the deployment without making it live. When you want to publish the example, sign in and deploy:
```bash
npx wrangler login
npx wrangler deploy
```
Open the printed URL and submit the form there. A successful local request cannot check the deployed hostname or configuration.
Once the project is in a GitHub or GitLab repository, connect that repository under the Worker's **Settings → Builds**. Review these settings before relying on automatic deployment:
| Setting | This plain HTML project |
| --- | --- |
| Production branch | The branch you release from, for example `main` |
| Root directory | The directory containing this project's `package.json` |
| Build command | `npx wrangler types --env-interface CloudflareBindings && npx tsc --noEmit` |
| Deploy command | `npx wrangler deploy` |
| Worker name | Must match `name` in `wrangler.jsonc` |
The build command regenerates the bindings interface before checking TypeScript, so it also works in a fresh checkout without generated types. Wrangler bundles the Worker during deployment; our plain HTML needs no compilation. Commit the package lockfile so dependency installation uses the recorded versions. If you use Astro instead, its build command needs to generate the site, typically with `npm run build`, before deployment. [Workers Builds configuration](https://developers.cloudflare.com/workers/ci-cd/builds/configuration/) separates that build step from the deploy command.
**Check the application at each stage**
Each environment catches problems the previous one cannot.
1. **01 · Local — Page and API**: Run Wrangler. Test valid and invalid inputs, missing URLs, and the browser's error messages.
2. **02 · Preview — Deployed configuration**: Deploy the branch. Check its variables and bindings, then share the URL for review.
3. **03 · Production — The reader's experience**: Merge into the production branch. Open the real domain and submit the form after deployment.
Test the complete interaction at the deployed URL, including its error cases.
*Review a branch before merging, then check the real domain after deployment. Each stage catches a different class of mistake.*
### A preview is a deployed environment
A branch preview lets someone review a change at a deployed URL before it reaches the production branch. It has its own configuration; the local tests alone cannot check that configuration.
As of November 6, 2026, [Worker Previews](https://developers.cloudflare.com/workers/previews/) uses `npx wrangler preview` and requires Wrangler 4.135.0 or later. Update the project's Wrangler dependency if you need that workflow; updating a global installation won't change the version the project runs.
New Workers connected to Builds use this preview model by default. Older projects can still have the previous model until explicitly switched. In [branch controls](https://developers.cloudflare.com/workers/ci-cd/builds/build-branches/), enable preview builds and check the preview command. An older Worker may still use the previous command.
For the new preview model, add a top-level `previews` block to `wrangler.jsonc`:
```jsonc title="wrangler.jsonc · add to the existing object"
{
"previews": {
"vars": {
"SERVICE_NAME": "reading-api-preview",
"DEFAULT_WPM": 200
}
}
}
```
Keep `assets` at the top level: Wrangler uploads the branch's files when you run `npx wrangler preview`. The [preview configuration guide](https://developers.cloudflare.com/workers/previews/configuration/) explains which settings belong in each block. Top-level variables are not automatically the preview's variables.
After deploying the preview, open `/health` and confirm it reports `reading-api-preview`, then submit the form. Once we add storage, we must also choose the preview's database explicitly; a separate URL does not imply separate data.
Protect the preview with access controls if its content is private. Anyone who can reach an unprotected URL can use it.
## Put it on your own domain
The `workers.dev` URL is enough to use the application. A domain gives it a name you control.
For an active domain on Cloudflare, add a Custom Domain to the existing configuration, using an unused hostname you own:
```jsonc title="wrangler.jsonc · add to the existing object"
{
"routes": [
{ "pattern": "reading.example.com", "custom_domain": true }
]
}
```
Deploy again. Cloudflare manages the DNS record and certificate for the [Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/). An existing conflicting record can prevent setup; the [DNS article](/en/blog/series/cloudflare/understanding-cloudflare-dns) explains how to inspect the zone.
The frontend doesn't need a new API URL. Its relative fetch still goes to `/api/reading-time`, now on `reading.example.com`. Repeat the same check on a branch preview and it calls that preview's hostname instead.
Choose one canonical hostname for a public site. If you serve both `www` and the apex, redirect the secondary hostname to the preferred one, preserving paths. Give each content page a useful title and description, keep canonical URLs on the public domain, and include published content in a sitemap. Test redirects on a nested URL as well as the homepage.
## Cache the files with their next update in mind
Cloudflare's asset service manages delivery of the uploaded files. For ordinary asset responses, its documented browser-cache default is `Cache-Control: public, max-age=0, must-revalidate`, with an `ETag` for checking whether the file changed. A browser can retain a copy, then revalidate it before reuse. See the [asset headers reference](https://developers.cloudflare.com/workers/static-assets/headers/).
That default suits our fixed filenames. If we edit `app.js`, its address stays `/app.js`. Telling the browser to reuse it for a year would make the next fix harder to deliver.
Later, a bundler might generate `app.a1b2c3.js`. If every content change produces a different filename, long-lived immutable caching becomes useful: the new HTML references the new file. Apply that policy to the fingerprinted assets, not indiscriminately to HTML or everything under `/`.
**Will the browser get the new JavaScript?**
Assume the browser already cached version 1, its cache is enabled, and a later page load requests the script again. Compare three policies.
1. **Fixed filename · revalidate — /app.js · max-age=0, must-revalidate**: The URL stays the same. Because the deployed file changed, validation returns the new body. If unchanged, a 304 response lets the browser reuse its copy.
Path: Cached version 1 → Check the ETag → Download version 2
2. **Fixed filename · cache for a year — /app.js · max-age=31536000, immutable**: The browser can reuse the old file without checking the server. Deploying new bytes at the same URL does not invalidate that fresh browser copy.
Path: Cached version 1 → Copy is still fresh → Reuse version 1
3. **Hashed filename · cache for a year — /app.b2.js · max-age=31536000, immutable**: The new URL is not in this browser's cache. Each changed bundle gets a new name; HTML must still be refreshed so it references that name.
Path: Cached app.a1.js → New HTML requests app.b2.js → Download version 2
Keep revalidation for this tutorial's fixed filenames. Use long immutable caching only for files whose URLs change with their contents.
*Compare what happens on a later visit after you deploy a JavaScript change. This models browser caching, not Cloudflare's internal asset cache.*
A deployment cannot clear a reader's browser cache, and an already-open page keeps running the JavaScript it loaded. Revalidation helps on the next load; hashed filenames help when the browser receives HTML that references the new filename. MDN's [HTTP caching guide](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching) explains both mechanisms.
Our API keeps the `Cache-Control: no-store` header from part three. The calculation depends on submitted text, and this tutorial doesn't add a response cache for it.
## What changes when you use Astro?
A single form needs little templating. A blog benefits from shared layouts, navigation, article metadata, and a content collection; a framework can manage that repetition.
This website uses Astro. Its articles are prerendered into HTML, while routes that need the incoming request, such as the contact form, opt into server rendering. Both are deployed through the Cloudflare adapter. The source files differ from our small project, but the division of work is familiar: prepared pages for reading, server code for actions.
For a framework project, point hosting at the **build output**, not the folder where you edit components. A `.astro` or `.tsx` file is source code, not a finished webpage. Use the framework's current [adapter instructions](https://docs.astro.build/en/guides/integrations-guide/cloudflare/); an adapter or Cloudflare's Vite plugin may generate the Worker entry point and asset configuration for you. Don't paste our hand-written `main` and `assets.directory` over that generated setup.
**One project, two kinds of output**
An Astro project with prerendered pages and on-demand routes produces both. The browser only downloads the public output.
Pages, components, styles → Astro + Cloudflare adapter
1. **Public assets — Files the browser can request**: Prerendered articles and frontend resources become downloadable files. Anything bundled into client JavaScript is visible to visitors.
Path: HTML · CSS · client JavaScript → Static asset service
2. **Server bundle — Code the Worker executes**: The Worker handles requests for these routes and returns responses. Its bundle is not served as a downloadable asset; secrets belong in runtime bindings.
Path: On-demand routes · server logic → Worker runtime
Deploy the adapter's output. Pointing the asset directory at the repository would expose source files instead of serving the built site.
*A framework build can produce both downloadable files and a Worker bundle. The adapter decides their directory layout; inspect your project's output rather than assuming these are folder names.*
Run the build and inspect those two outputs. Check which pages exist as HTML, which routes need the Worker, and which JavaScript files a visitor will download.
## When a deployment goes wrong
Start by identifying the stage that failed. If dependency installation failed, the new page hasn't reached the build step. If the build passed but the page can't call its API, inspect the actual HTTP response.
| Symptom | First thing to check |
| --- | --- |
| Page loads but the button stays disabled | Did `/app.js` load, and does the browser console show an error? |
| Form gets HTML instead of JSON | The request URL, asset fallback, and Worker-first paths |
| Browser navigation and `curl` disagree | The `Sec-Fetch-Mode` header and routing rules |
| New HTML uses old JavaScript | Cache headers and whether filenames change with their contents |
| API works locally but fails in a preview | Preview variables, secrets, and resource bindings |
| Build never reaches the compiler | Dependency-install logs, package lockfile, and build cache |
That last case happened when publishing the previous article on this site. Cloudflare's build logs showed a corrupted cached esbuild archive, followed by an `ETXTBSY` error during installation. The failure was in dependency installation, before Astro compiled the article. Logs like those give you a reason to [clear the build cache](https://developers.cloudflare.com/workers/ci-cd/builds/build-caching/) and retry the same commit before changing application code.
If a deployed code change breaks the application, use the [rollback procedure from part three](/en/blog/series/cloudflare/understanding-cloudflare-workers#know-how-to-undo-a-deployment), then test the page and API together. A rollback doesn't remove copies already held by browsers or reverse database writes. That's another reason to think about asset filenames before choosing long cache lifetimes.
## What do the page requests cost?
At the time of writing, Cloudflare lists direct static-asset requests as free and unlimited, with no additional asset-storage charge. Requests that invoke the Worker script follow Workers pricing. The [billing reference](https://developers.cloudflare.com/workers/static-assets/billing-and-limitations/) distinguishes the two.
In our example, loading the HTML, CSS, and JavaScript through asset serving does not require the analysis handler. Submitting a paragraph does. If you configure the Worker to run before every asset request, those invocations count too, even when the eventual response is a file.
Build usage, domain registration, and any services you add have their own costs. Estimate asset requests and Worker invocations separately.
## Make one small release
Change the page heading on a branch and push it. Check that the new heading appears on the branch preview while the production page stays unchanged. After reviewing and merging it, open the real domain and submit the form again. That exercises the release workflow you have just configured.
The same structure can support a feedback form or a small dashboard: public files for the interface, Worker handlers for server-side actions, and a preview where you can check both together.
The next useful feature is remembering a draft. That brings us to persistent data: how to save it, query it, and keep preview writes away from production. We'll build on this application when we get to D1.
If you're helping someone deploy their first website on Cloudflare, share this guide with them. Which part has caused you the most trouble: routing, previews, or caching? [Send me the example](/en/contact), or share what you learned alongside the article on X or LinkedIn.
---
# استضافة موقع على Cloudflare Workers: من التجربة المحلية إلى نطاقك الخاص
- URL: https://omaralbeik.com/ar/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers
- Markdown: https://omaralbeik.com/ar/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers.md
- Translation: https://omaralbeik.com/en/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers
- Author: Omar Albeik
- Language: ar
- Type: tutorial
- Date: 6 تشرين الثاني 2026
- Topics: infrastructure
بنينا في الجزء الثالث واجهة برمجية تقدّر مدة قراءة النصوص، واختبرناها من الطرفية. سنضيف هنا صفحة يفتحها القارئ ويلصق فيها نصه، فتظهر له النتيجة.
يمكن استضافة الصفحة والواجهة البرمجية معا على Cloudflare Workers. يحمّل المتصفح ملفات HTML وCSS وJavaScript، وعندما يرسل القارئ النموذج، يستقبل Hono الطلب ويحسب النتيجة. كل ذلك على اسم المضيف نفسه، من دون فصل الواجهة في خدمة استضافة أخرى.
سنختبرها محليا، ونراجع نسخة منشورة من فرع مستقل، ثم نتيحها على نطاقك. نريد أن نعرف ما يحدث في كل طلب: أي ملف أو دالة أعادت الاستجابة؟ وما الإعدادات المستخدمة؟ وهل يعرض المتصفح آخر نسخة نشرناها؟
للمتابعة، افتح مشروع `reading-api` من [الجزء الثالث](/ar/blog/series/cloudflare/understanding-cloudflare-workers). يفترض أن يكون لديك الملفان `src/index.ts` و`src/analyze.ts`، مع تثبيت مكتبة Hono وأداة Wrangler. سنحتفظ بشيفرة الحساب والتحقق من المدخلات، ونضيف إليها ملفات HTML وJavaScript مباشرة. بهذه الطريقة يسهل تتبع الطلبات قبل إدخال إطار عمل في المشروع.
- [ما الذي يطلبه المتصفح؟](#ما-الذي-يطلبه-المتصفح)
- [إضافة صفحة للأداة](#إضافة-صفحة-للأداة)
- [التعامل مع الصفحات غير الموجودة](#التعامل-مع-الصفحات-غير-الموجودة)
- [النشر وربط المستودع](#نشر-الموقع-وربطه-بـ-git)
- [ربط نطاقك بالموقع](#ربط-نطاقك-بالموقع)
- [تحديث الملفات واستخدام أطر العمل](#التخزين-المؤقت-عند-تحديث-الملفات)
يمكن حساب مدة القراءة بالكامل داخل المتصفح، بحيث لا يغادر النص جهاز القارئ. نستخدم الواجهة البرمجية هنا لنتعلم كيف نربط صفحة بتطبيق Worker؛ وستصبح الحاجة إلى الخادم أوضح عندما نضيف وظائف مثل حفظ المسودات.
## ما الذي يطلبه المتصفح؟
عند فتح الأداة، يطلب المتصفح صفحة HTML أولا. يجد فيها رابطا لملف CSS وآخر لملف JavaScript، فيطلبهما أيضا. وعند إرسال النموذج، يرسل طلبا جديدا إلى `/api/reading-time`.
يمكن تجهيز الملفات الثلاثة قبل وصول أي زائر. أما نتيجة الحساب فتتوقف على النص المرسل في الطلب.
تتيح [Workers Static Assets](https://developers.cloudflare.com/workers/static-assets/) نشر الملفات مع تطبيق Worker نفسه. نحدد مجلدا للملفات المتاحة للزوار، ونحدد ملف الدخول الذي يحتوي على شيفرة الخادم. تتولى المنصة تقديم الملفات، فلا نحتاج إلى خادم منفصل يقرأها من القرص ويرسلها.
وصف الصفحة بأنها «ثابتة» لا يعني أنها تخلو من التفاعل. يمكن لصفحة HTML جاهزة أن تشغّل JavaScript، وتطلب بيانات من API، وتحدّث ما تعرضه. المقصود هو أن HTML جاهز مسبقا، ولا نولّده من جديد لكل طلب.
**ثلاث طرق لعرض المحتوى**
يمكن للموقع الواحد الجمع بين هذه الطرق بحسب حاجة كل صفحة.
1. **قبل الزيارة — HTML مولّد مسبقا**: يتحول المقال أثناء البناء إلى ملف HTML جاهز لتقديمه عند وصول الطلب.
2. **عند وصول الطلب — توليد HTML على الخادم**: يولّد Worker الصفحة لهذا الطلب، وقد يستخدم بيانات الجلسة أو معلومات محدثة.
3. **بعد تحميل الصفحة — تفاعل داخل المتصفح**: تحدّث JavaScript ما تعرضه الصفحة. في أداتنا، تطلب النتيجة من API ثم تضيفها إلى الصفحة.
يمكن إضافة التفاعل سواء كان HTML جاهزا مسبقا أو مولّدا عند الطلب.
*اختر وقت توليد HTML بحسب البيانات التي تحتاجها الصفحة. وجود أزرار وتفاعل لا يفرض توليدها على الخادم عند كل زيارة.*
في أداتنا، يرى جميع الزوار النموذج نفسه. لذلك سنقدمه كملف جاهز، ونشغّل دالة الحساب عند إرسال النص فقط.
## وماذا عن Cloudflare Pages؟
توصي Cloudflare حاليا [باستخدام Workers للمشاريع الجديدة](https://developers.cloudflare.com/pages/). فهي تدعم الملفات الثابتة وشيفرة الخادم والبناء من Git ومعاينة الفروع. أما Pages فما زالت لها آلية النشر الخاصة بها وPages Functions؛ لذا ستصادفها في المشاريع القائمة والشروحات الأقدم.
أما إذا كان موقعك يعمل على Pages، فراجع ما سيترتب على نقله أولا: محوّل إطار العمل (adapter)، ومسارات Functions، وقواعد إعادة التوجيه، وطريقة المعاينة. يوضح [دليل الانتقال من Pages إلى Workers](https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/) الفروق التي تحتاج إلى مراعاتها.
## إضافة صفحة للأداة
إذا كانت لديك واجهة جاهزة، فاستخدم ملفاتها بدلا من النموذج أدناه، وتابع خطوات التوجيه والنشر. وإذا كان إطار العمل يولّد حزمة Worker، فاستخدم إعدادات محوّله كما سنوضح في [قسم Astro](#ماذا-يتغير-عند-استخدام-astro).
أنشئ مجلد `public` داخل `reading-api`. بعد إضافة ملفات هذا الجزء، سيصبح ترتيب المشروع كالتالي:
```text
reading-api/
├── public/
│ ├── index.html
│ ├── styles.css
│ ├── app.js
│ ├── 404.html
│ └── _headers
├── src/
│ ├── analyze.ts
│ └── index.ts
├── package.json
├── package-lock.json
└── wrangler.jsonc
```
ضع في `public` ما يجوز للزائر تنزيله فقط. أبقِ ملف `.dev.vars` وبيانات الاعتماد وشيفرة الخادم خارجه. مجلد الملفات المنشورة يجب أن يكون محددا بوضوح؛ لا تستخدم جذر المستودع لهذا الغرض.
### تحديد الملفات في إعدادات Wrangler
أضف الخاصية التالية إلى المستوى الأعلى من `wrangler.jsonc`، مع إبقاء `main` و`vars` وبقية إعدادات الجزء الثالث:
```jsonc title="wrangler.jsonc · إضافة إلى الإعدادات الحالية"
{
"assets": {
"directory": "./public",
"binding": "ASSETS",
"not_found_handling": "404-page",
"run_worker_first": ["/api", "/api/*", "/health"]
}
}
```
يحدد `directory` مجلد الملفات، ويتيح الربط `ASSETS` طلب استجابة من خدمة الملفات داخل شيفرة Worker. أما `404-page` فيختار صفحة HTML للعنوان غير الموجود. ويضمن `run_worker_first` أن تمر مسارات الواجهة البرمجية وفحص الحالة عبر Worker أولا.
أبقِ تاريخ التوافق الحالي أثناء هذه الخطوة؛ تغيير سلوك بيئة التشغيل يحتاج إلى اختبار مستقل. ثم أعد توليد الأنواع ليشمل `CloudflareBindings` الربط الجديد `ASSETS`:
```bash
npx wrangler types --env-interface CloudflareBindings
```
في الوضع الافتراضي، تستطيع المنصة إعادة الملف المطابق للمسار من دون تشغيل شيفرتنا. أما [المسارات التي تُعالج في Worker أولا](https://developers.cloudflare.com/workers/static-assets/routing/worker-script/)، فتضمن وصول طلبات API إلى Hono حتى لو وُجد ملف يطابق عنوان الطلب.
**اسم مضيف واحد، وطريقتان للاستجابة**
اختر طلبا لترى كيف تعالجه إعدادات المقال. هذا شرح توضيحي؛ لا يرسل طلبات فعلية.
1. **فتح الصفحة الرئيسية — GET /**: تعيد خدمة الملفات public/index.html مباشرة، من دون تشغيل معالج Hono.
المسار: المتصفح ← خدمة الملفات ← HTML بالحالة 200
2. **تحميل JavaScript — GET /app.js**: تعيد خدمة الملفات public/app.js، ثم يشغّله المتصفح.
المسار: المتصفح ← خدمة الملفات ← JavaScript بالحالة 200
3. **حساب مدة القراءة — POST /api/reading-time**: يتحقق Hono من المدخلات ويستدعي analyzeReading(). إذا كانت صالحة، يعيد النتيجة لتعرضها الصفحة.
المسار: المتصفح ← Worker · Hono ← JSON بالحالة 200
4. **فتح مسار API كصفحة — GET /api/reading-time**: تتضمن الاستجابة Allow: POST. تضمن قاعدة /api/* وصول الطلب إلى Hono بدلا من إرجاع صفحة HTML بديلة.
المسار: المتصفح ← Worker · Hono ← JSON بالحالة 405
5. **فتح رابط غير موجود — GET /missing**: تعيد خدمة الملفات public/404.html بالحالة 404. يبقى العنوان المطلوب في شريط المتصفح.
المسار: انتقال من المتصفح ← خدمة الملفات ← HTML بالحالة 404
تمر مسارات API وفحص الحالة عبر Worker أولا. وقد يصل طلب ملف غير موجود إلى Hono أيضا إن لم يكن طلب انتقال؛ عندها يحيله إلى ASSETS.
*تذهب طلبات الصفحة والنموذج إلى اسم المضيف نفسه، لكن طلب الحساب وحده يحتاج إلى دالة تحليل النص.*
### كتابة الصفحة
نحتاج إلى حقل للنص له تسمية واضحة، وقائمة لاختيار اللغة، وحقل لسرعة القراءة، ومساحة لعرض النتيجة وإعلانها لقارئ الشاشة. تجمع الصفحة المدخلات وترسلها، ثم تعرض ما تعيده الواجهة البرمجية.
```html title="public/index.html"
Reading time
How long will this take to read?
Paste a paragraph and choose a pace to estimate its reading time.
```
تجعل `dir="auto"` اتجاه الكتابة في حقل النص يتبع محتواه. واجهة المثال إنجليزية وتقبل النصوص العربية والإنجليزية؛ تحديد اتجاه النص لا يغيّر لغة الأزرار والتسميات.
يبدأ زر الإرسال معطلا، وتفعّله JavaScript بعد تجهيز دالة الإرسال. إذا تعذر تحميل الشيفرة، لن يُرسل النموذج النص بالخطأ بالطريقة الافتراضية التي تنقل المتصفح إلى عنوان جديد.
### تنسيق النموذج
يكفي هنا خط مقروء، وحقول تناسب شاشة الهاتف، ومؤشر واضح للعنصر المحدد عند التنقل بلوحة المفاتيح. لا نحتاج إلى مكتبة لتنسيق هذه الصفحة.
```css title="public/styles.css"
:root {
font-family: system-ui, sans-serif;
line-height: 1.6;
color: #24211d;
background: #f8f6f1;
}
* { box-sizing: border-box; }
body { margin: 0; }
main { max-width: 42rem; margin: auto; padding: 2rem 1.25rem; }
h1 { line-height: 1.2; text-wrap: balance; }
label { display: block; margin-block: 1rem 0.35rem; font-weight: 600; }
textarea, select, input, button {
width: 100%;
font: inherit;
padding: 0.75rem;
border: 1px solid #81786d;
border-radius: 0.3rem;
}
textarea, select, input { color: inherit; background: #fff; }
textarea { resize: vertical; }
button { margin-top: 1.25rem; color: #fff; background: #29499c; }
button:disabled { opacity: 0.65; cursor: wait; }
:focus-visible { outline: 3px solid #29499c; outline-offset: 3px; }
.hint { font-size: 0.9rem; color: #5e564b; }
#result { min-height: 3rem; font-weight: 600; }
```
### إرسال النص إلى الواجهة البرمجية
أنشئ ملف `public/app.js`. نستخدم العنوان النسبي `/api/reading-time` حتى يذهب الطلب إلى أصل الصفحة نفسه، أي البروتوكول واسم المضيف والمنفذ ذاتها. سيعمل ذلك محليا، وعلى رابط المعاينة، وعلى نطاقك، من دون تعديل العنوان في الشيفرة.
```js title="public/app.js"
const form = document.querySelector("#reading-form");
const button = form.querySelector('button[type="submit"]');
const result = document.querySelector("#result");
form.addEventListener("submit", async (event) => {
event.preventDefault();
if (button.disabled) return;
const fields = new FormData(form);
button.disabled = true;
result.textContent = "Estimating…";
try {
const response = await fetch("/api/reading-time", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: fields.get("text"),
language: fields.get("language"),
wordsPerMinute: Number(fields.get("wordsPerMinute")),
}),
signal: AbortSignal.timeout(10_000),
});
const contentType = response.headers.get("content-type") ?? "";
if (!contentType.includes("application/json")) {
throw new Error("The server returned an unexpected response. Try again.");
}
const data = await response.json();
if (!response.ok) {
throw new Error(data.error ?? "The estimate could not be calculated.");
}
const words = data.words === 1 ? "word" : "words";
const seconds = data.seconds === 1 ? "second" : "seconds";
result.textContent =
`${data.words} ${words} · about ${data.seconds} ${seconds}` +
` at ${data.wordsPerMinute} words per minute.`;
} catch (error) {
if (error instanceof DOMException && error.name === "TimeoutError") {
result.textContent = "The request took too long. Please try again.";
} else if (error instanceof TypeError) {
result.textContent = "Couldn't reach the server. Check your connection.";
} else {
result.textContent = error instanceof Error
? error.message
: "Something went wrong. Please try again.";
}
} finally {
button.disabled = false;
}
});
button.disabled = false;
```
يفحص المتصفح القيود الأساسية للنموذج قبل إرساله، لكن على الخادم التحقق من كل حقل أيضا؛ يمكن لأي عميل إرسال طلب مباشر من دون استخدام الصفحة. شيفرة الجزء الثالث تتحقق من المدخلات، وتضع حدا لحجم محتوى الطلب، وتعيد أخطاء بصيغة JSON.
لا ترمي `fetch()` استثناء لمجرد أن الخادم أعاد الحالة `400` أو `500`، لذلك نفحص `response.ok`. ونفحص نوع المحتوى قبل قراءته كـ JSON: إذا أعادت إعدادات التوجيه صفحة HTML بالخطأ، تظهر رسالة مفهومة بدلا من خطأ تقني في تحليل JSON.
نستخدم `textContent` لعرض النتيجة كنص، من دون تفسيرها على أنها HTML.
ولأن الصفحة والواجهة البرمجية تشتركان في الأصل نفسه، لا نحتاج إلى إعداد CORS لهذا الاتصال. تظل الواجهة البرمجية متاحة للجميع؛ CORS لا يتحقق من هوية من يستدعيها.
### إضافة ترويسات للملفات العامة
لإضافة ترويسات إلى استجابات الملفات، أنشئ `_headers` داخل مجلد `public`:
```text title="public/_headers"
/*
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
```
تطبق هذه القواعد عند تقديم الملفات. لا تضيف الترويسات تلقائيا إلى JSON الذي يولّده Hono؛ اضبط ترويسات تلك الاستجابات داخل شيفرة الخادم عند الحاجة. كذلك، لن تفحص دالة وسيطة في Hono طلب الصفحة الرئيسية إذا أجابته خدمة الملفات مباشرة. إذا كانت الملفات خاصة، وجّه طلباتها عبر التحقق من الهوية قبل إعادتها للزائر.
## التعامل مع الصفحات غير الموجودة
إذا فتح الزائر رابطا غير موجود، نريد أن نعرض له صفحة تساعده على العودة إلى الأداة. أما طلب مسار API غير موجود، فيجب أن يتلقى خطأ بصيغة JSON. سنفصل الحالتين في معالج المسارات غير المعروفة.
في `src/index.ts`، استبدل كتلة `app.notFound(...)` الحالية بما يلي:
```ts title="src/index.ts · استبدال app.notFound"
app.notFound((c) => {
const path = c.req.path;
const isApi = path === "/api" || path.startsWith("/api/");
const isPageRequest = c.req.method === "GET" || c.req.method === "HEAD";
if (isApi || !isPageRequest) {
return c.json({ error: "Not found." }, 404);
}
return c.env.ASSETS.fetch(c.req.raw);
});
```
أبقِ المسارات والدوال الوسيطة و`app.onError` و`export default app` كما هي. يستدعي `ASSETS.fetch()` خدمة الملفات عبر الربط مباشرة؛ ولا يرسل طلبا عاما جديدا يعود إلى Hono.
أضف صفحة الخطأ:
```html title="public/404.html"
Page not found · Reading time
That page isn't here.
The address may be wrong, or the page may have moved.
Open the reading-time tool
```
بهذا الإعداد، يعيد العنوان غير الموجود صفحة الخطأ مع **رمز الحالة 404**. لا نحوّل كل رابط مكسور إلى الصفحة الرئيسية؛ تحتاج محركات البحث وعملاء HTTP إلى رمز يصف النتيجة، إلى جانب الرسالة التي يقرأها الزائر.
هناك تفصيل في التوجيه يستحق الاختبار. عند استخدام `404-page` مع تاريخ توافق يوافق 1 نيسان 2025 أو أحدث، كما في مشروعنا، تذهب طلبات الانتقال إلى صفحة مباشرة إلى خدمة الملفات، ما لم تنطبق قاعدة تشغّل Worker أولا. تحمل هذه الطلبات الترويسة `Sec-Fetch-Mode: navigate`، بينما لا يضيفها `curl` عادة.
لهذا حجزنا `/health` ومسارات API في `run_worker_first`: تصل إلى Hono سواء فُتحت من شريط العنوان أو طُلبت برمجيا. أما طلبات GET الأخرى لملفات غير موجودة، إن لم تكن طلبات انتقال، فقد تصل إلى `app.notFound` الذي يطلب صفحة الخطأ من `ASSETS`. يشرح [دليل توجيه المواقع الثابتة](https://developers.cloudflare.com/workers/static-assets/routing/static-site-generation/) هذا السلوك.
لا تفعّل `single-page-application` لمجرد أن الأداة تتكون من صفحة واحدة. يعيد هذا الخيار `index.html` باستجابة نجاح عند غياب الملف، لتتولى شيفرة التوجيه في المتصفح اختيار المحتوى. ليس لدينا مثل هذه الشيفرة، ولذلك يجب أن يظل العنوان غير الموجود خطأ 404.
## التجربة المحلية وتتبع الطلبات
نفّذ من مجلد المشروع:
```bash
npx tsc --noEmit
npx wrangler dev --local
```
إذا أبلغك Wrangler أن تاريخ التوافق أحدث من بيئة التشغيل المحلية التي يضمها، حدّث حزمة المشروع بالأمر `npm install --save-dev wrangler@latest`، ثم أعد توليد الأنواع والفحص. احتفظ بالتعديل الناتج في ملف القفل.
افتح العنوان الذي يطبعه Wrangler، وهو عادة `http://localhost:8787`. جرّب نصا إنجليزيا قصيرا، ثم نصا عربيا، وغيّر سرعة القراءة. في هذا الإعداد، يصل النص إلى Worker الذي يعمل محليا على جهازك.
افتح تبويب **Network** في أدوات المطور قبل إعادة تحميل الصفحة. سترى طلبات HTML وCSS وJavaScript. أرسل النموذج وراقب طلب POST: يجب أن تكون استجابته JSON تحتوي على عدد الكلمات والمدة المقدرة، من دون إعادة تحميل الصفحة.
اختبر الحالات التالية، فكل منها يكشف نوعا مختلفا من الأخطاء:
| ما تختبره | النتيجة المتوقعة |
| --- | --- |
| فتح `/` | النموذج بتنسيقه الصحيح وزر إرسال يعمل |
| إرسال نص صالح | استجابة JSON بالحالة `200` من `POST /api/reading-time` |
| إرسال نص فارغ مباشرة إلى API | استجابة JSON بالحالة `400` من الخادم |
| فتح `/api/reading-time` من شريط العنوان | استجابة JSON بالحالة `405` والترويسة `Allow: POST` |
| فتح `/api/missing` | استجابة JSON بالحالة `404` |
| فتح `/missing` | صفحة الخطأ مع الحالة `404` |
| فتح `/health` | استجابة JSON بالحالة `200`، حتى عند فتحه كصفحة |
| قطع الاتصال ثم الإرسال | رسالة توضح تعذر الاتصال، ثم إتاحة زر الإرسال من جديد |
لإرسال طلب يحمل ترويسة الانتقال من الطرفية، ثم تجربة طلب حساب عادي:
```bash
curl -i http://localhost:8787/health \
-H 'Sec-Fetch-Mode: navigate'
curl -i http://localhost:8787/missing \
-H 'Sec-Fetch-Mode: navigate'
curl -i http://localhost:8787/api/reading-time \
-H 'Content-Type: application/json' \
--data '{"text":"Small tools deserve good interfaces.","language":"en"}'
```
يحتوي نص الطلب الأخير على خمس كلمات. وبسرعة القراءة الافتراضية، 200 كلمة في الدقيقة، تقرّب الواجهة المدة إلى الأعلى فتعيد ثانيتين. هذه نتيجة مبنية على سرعة نفترضها ويمكن تعديلها، وليست قياسا لسرعة قارئ بعينه.
## نشر الموقع وربطه بـ Git
قبل النشر الأول، جرّب تجهيز الحزمة:
```bash
npx wrangler deploy --dry-run
```
يجهز الأمر ملفات النشر من دون نشرها فعليا. عندما تريد إتاحة المثال على الإنترنت، سجّل الدخول ثم انشره:
```bash
npx wrangler login
npx wrangler deploy
```
افتح الرابط الذي يظهر وأرسل النموذج منه. نجاح التجربة المحلية لا يختبر إعدادات النسخة المنشورة أو اسم مضيفها.
بعد وضع المشروع في مستودع على GitHub أو GitLab، اربطه بالتطبيق من **Settings → Builds**. راجع هذه الإعدادات قبل الاعتماد على النشر التلقائي:
| الإعداد | القيمة في مشروعنا |
| --- | --- |
| فرع الإنتاج | الفرع الذي تنشر منه، مثل `main` |
| المجلد الجذر | المجلد الذي يحتوي على `package.json` الخاص بالمشروع |
| أمر البناء | `npx wrangler types --env-interface CloudflareBindings && npx tsc --noEmit` |
| أمر النشر | `npx wrangler deploy` |
| اسم Worker | يطابق `name` في `wrangler.jsonc` |
يعيد أمر البناء توليد أنواع الموارد المرتبطة قبل فحص TypeScript. بذلك يعمل في نسخة جديدة من المستودع حتى لو لم تتضمن ملفات الأنواع المولّدة. يتولى Wrangler تجميع شيفرة Worker أثناء النشر، أما HTML الذي كتبناه فلا يحتاج إلى خطوة تحويل.
أضف ملف قفل الحزم إلى المستودع لتُثبّت الإصدارات المسجلة فيه. وإذا استخدمت Astro، فيجب توليد الموقع قبل نشره، عادة بالأمر `npm run build`. تفصل [إعدادات Workers Builds](https://developers.cloudflare.com/workers/ci-cd/builds/configuration/) بين أمر البناء وأمر النشر.
**اختبر التطبيق في كل مرحلة**
تختلف الإعدادات والظروف بين التجربة المحلية والمعاينة والإنتاج.
1. **١ · محليا — الصفحة والواجهة البرمجية**: شغّل Wrangler. جرّب مدخلات صالحة وأخرى غير صالحة، وروابط مفقودة، ورسائل الخطأ في المتصفح.
2. **٢ · المعاينة — إعدادات النسخة المنشورة**: انشر الفرع، وافحص متغيراته والموارد المرتبطة به، ثم شارك الرابط للمراجعة.
3. **٣ · الإنتاج — ما يراه القارئ فعليا**: ادمج التعديل في فرع الإنتاج. بعد النشر، افتح النطاق الحقيقي وأرسل النموذج.
اختبر التفاعل كاملا على الرابط المنشور، بما في ذلك حالات الخطأ.
*راجع الفرع على رابط معاينة قبل دمجه، ثم اختبر النطاق الفعلي بعد النشر. لكل مرحلة إعدادات ومشكلات لا تكشفها المرحلة السابقة.*
### معاينة الفرع تعمل على Cloudflare
تتيح معاينة الفرع مراجعة التعديل على رابط منشور قبل وصوله إلى فرع الإنتاج. ويمكنك مشاركة الرابط مع من يراجع عملك. لهذه النسخة إعداداتها الخاصة التي لا تختبرها التجربة المحلية وحدها.
حتى تاريخ كتابة المقال، 6 تشرين الثاني 2026، تستخدم [Worker Previews](https://developers.cloudflare.com/workers/previews/) الأمر `npx wrangler preview`، وتتطلب Wrangler بالإصدار 4.135.0 أو أحدث. حدّث الحزمة المثبتة في المشروع عند الحاجة؛ تحديث نسخة Wrangler العامة على جهازك لا يغيّر النسخة التي يستخدمها المشروع.
تستخدم التطبيقات الجديدة المرتبطة بـ Builds آلية المعاينة الجديدة افتراضيا. وقد تبقى التطبيقات الأقدم على الآلية السابقة إلى أن تنقلها صراحة. فعّل بناء المعاينات من [إعدادات الفروع](https://developers.cloudflare.com/workers/ci-cd/builds/build-branches/)، وافحص أمر المعاينة المسجل فيها؛ فقد يظل التطبيق القديم يستخدم الأمر السابق.
لإعداد الآلية الجديدة، أضف `previews` إلى المستوى الأعلى من `wrangler.jsonc`:
```jsonc title="wrangler.jsonc · إضافة إلى الإعدادات الحالية"
{
"previews": {
"vars": {
"SERVICE_NAME": "reading-api-preview",
"DEFAULT_WPM": 200
}
}
}
```
أبقِ `assets` في المستوى الأعلى أيضا؛ يرفع Wrangler ملفات الفرع عند تشغيل `npx wrangler preview`. يوضح [دليل إعداد المعاينات](https://developers.cloudflare.com/workers/previews/configuration/) موضع كل إعداد. متغيرات المستوى الأعلى لا تنتقل تلقائيا إلى المعاينة، ولذلك عرّفنا قيمها هنا.
بعد نشر المعاينة، افتح `/health` وتأكد من أن اسم الخدمة هو `reading-api-preview`، ثم جرّب النموذج. عندما نضيف التخزين، سنحدد قاعدة بيانات المعاينة أيضا؛ اختلاف الرابط لا يعني أن البيانات منفصلة.
إذا كان محتوى المعاينة خاصا، احمِ الوصول إليها. يستطيع أي شخص استخدام الرابط غير المحمي إذا وصل إليه.
## ربط نطاقك بالموقع
يمكن استخدام التطبيق عبر رابط `workers.dev`. ولإتاحته باسم تختاره، اربطه بنطاقك.
إذا كان النطاق مفعّلا على Cloudflare، أضف Custom Domain إلى الإعدادات. استخدم اسم مضيف غير مستخدم ضمن نطاق تملكه:
```jsonc title="wrangler.jsonc · إضافة إلى الإعدادات الحالية"
{
"routes": [
{ "pattern": "reading.example.com", "custom_domain": true }
]
}
```
انشر من جديد. تنشئ Cloudflare سجل DNS وشهادة TLS الخاصة بـ [Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/). قد يمنع سجل موجود ومتعارض إتمام الإعداد؛ يوضح [مقال DNS](/ar/blog/series/cloudflare/understanding-cloudflare-dns) طريقة فحص السجلات.
لن نغيّر عنوان API في الصفحة. يظل الطلب النسبي موجها إلى `/api/reading-time`، لكنه سيصل الآن إلى `reading.example.com`. وعند فتح معاينة فرع، سيصل إلى اسم مضيف تلك المعاينة.
اختر عنوانا أساسيا واحدا للموقع العام. إذا أتحته على النطاق مباشرة وعلى `www`، فأعد توجيه العنوان الآخر إلى الأساسي مع الاحتفاظ بالمسار. أضف عنوانا ووصفا مناسبين لكل صفحة محتوى، واجعل روابط `canonical` تشير إلى النطاق العام، وأدرج المحتوى المنشور في خريطة الموقع. اختبر إعادة التوجيه على صفحة داخلية أيضا، لا على الرئيسية فقط.
## التخزين المؤقت عند تحديث الملفات
تتولى خدمة الملفات في Cloudflare تقديم ما رفعناه. في استجابات الملفات المعتادة، تكون ترويسة التخزين المؤقت للمتصفح افتراضيا `Cache-Control: public, max-age=0, must-revalidate`، وترافقها `ETag` للتحقق مما إذا كان الملف قد تغير. يمكن للمتصفح الاحتفاظ بنسخة، لكنه يتحقق من صلاحيتها قبل إعادة استخدامها. التفاصيل في [مرجع ترويسات الملفات](https://developers.cloudflare.com/workers/static-assets/headers/).
هذا مناسب لأسماء ملفاتنا الثابتة. إذا عدّلنا `app.js` فسيظل عنوانه `/app.js`. ولو سمحنا للمتصفح باستخدام نسخته مدة سنة من دون تحقق، فقد لا يصل الإصلاح الجديد إلى من زار الموقع سابقا.
قد تولّد أداة البناء لاحقا اسما مثل `app.a1b2c3.js`، يتغير الجزء الأخير منه بتغير المحتوى. عندها يمكن الاحتفاظ بالملف مدة طويلة مع `immutable`؛ فصفحة HTML الجديدة ستطلب اسما جديدا. طبّق هذه السياسة على الملفات ذات الأسماء المرتبطة بمحتواها، لا على HTML أو جميع مسارات الموقع.
**هل سيحمّل المتصفح الشيفرة الجديدة؟**
لنفترض أن المتصفح يحتفظ بالإصدار الأول، وأن التخزين المؤقت مفعّل، ثم فتحت الصفحة مجددا فطلبت الملف. قارن بين ثلاث سياسات.
1. **اسم ثابت مع التحقق قبل الاستخدام — /app.js · max-age=0, must-revalidate**: يبقى العنوان نفسه. لأن الملف تغير، يعيد الخادم المحتوى الجديد. أما إذا لم يتغير، فتتيح استجابة 304 للمتصفح استخدام نسخته المحفوظة.
المسار: الإصدار الأول محفوظ ← التحقق باستخدام ETag ← تنزيل الإصدار الثاني
2. **اسم ثابت مع صلاحية سنة — /app.js · max-age=31536000, immutable**: قد يستخدم المتصفح الملف القديم من دون سؤال الخادم. رفع محتوى جديد إلى العنوان نفسه لا يلغي صلاحية النسخة المحفوظة لديه.
المسار: الإصدار الأول محفوظ ← النسخة ما زالت صالحة ← استخدام الإصدار الأول
3. **اسم يتغير بتغير المحتوى مع صلاحية سنة — /app.b2.js · max-age=31536000, immutable**: العنوان الجديد غير موجود في ذاكرة هذا المتصفح. يتغير اسم الحزمة بتغير محتواها، ويجب تحديث HTML ليشير إلى الاسم الجديد.
المسار: الملف app.a1.js محفوظ ← HTML الجديد يطلب app.b2.js ← تنزيل الإصدار الثاني
في مثالنا، أبقِ التحقق قبل إعادة الاستخدام لأن أسماء الملفات ثابتة. خصص التخزين الطويل مع immutable للملفات التي تتغير عناوينها بتغير محتواها.
*ماذا يحصل في الزيارة التالية بعد تعديل JavaScript ونشره؟ المقارنة هنا تخص النسخة المحفوظة في متصفح القارئ، لا ذاكرة Cloudflare المؤقتة.*
نشر إصدار جديد لا يمسح ذاكرة المتصفح المؤقتة، والصفحة المفتوحة تواصل تشغيل الشيفرة التي حمّلتها. يفيد التحقق من صلاحية الملف عند التحميل التالي، ويفيد الاسم الجديد عندما تصل إلى المتصفح صفحة HTML تشير إليه. يشرح [دليل التخزين المؤقت من MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching) الآليتين.
تحتفظ استجابات API بالترويسة `Cache-Control: no-store` التي أضفناها في الجزء الثالث. تعتمد النتيجة على النص المرسل، ولن نضيف في هذا المثال تخزينا مؤقتا لها.
## ماذا يتغير عند استخدام Astro؟
لا تحتاج صفحة النموذج إلى كثير من القوالب. أما المدونة، ففيها تخطيطات مشتركة وقوائم تنقل وبيانات للمقالات ومجموعة من ملفات المحتوى. يساعد إطار العمل على إدارة هذا التكرار.
هذا الموقع مبني باستخدام Astro. تُولّد المقالات مسبقا كملفات HTML، بينما تُولّد الصفحات التي تحتاج إلى الطلب الوارد، مثل صفحة التواصل، عند الطلب. ننشر النوعين باستخدام محوّل Cloudflare: ملفات جاهزة للقراءة، وشيفرة خادم لمعالجة التفاعل الذي يحتاج إليها.
عند نشر مشروع يستخدم إطار عمل، حدد **مخرجات البناء** بوصفها الملفات المنشورة. ملف `.astro` أو `.tsx` الذي تعدّله ليس صفحة جاهزة للمتصفح. اتبع [تعليمات المحوّل](https://docs.astro.build/en/guides/integrations-guide/cloudflare/)؛ فقد يتولى هو أو إضافة Cloudflare لـ Vite توليد ملف دخول Worker وإعدادات الملفات. لا تستبدل الإعدادات المولّدة بقيم `main` و`assets.directory` من مثالنا اليدوي.
**مشروع واحد ينتج ملفات وشيفرة خادم**
إذا جمع مشروع Astro بين صفحات مولّدة مسبقا ومسارات تعمل عند الطلب، فسيحتاج إلى النوعين. ينزّل المتصفح الملفات العامة فقط.
صفحات ومكونات وأنماط ← Astro مع محوّل Cloudflare
1. **الملفات العامة — يطلبها المتصفح وينزّلها**: تتحول المقالات المولّدة مسبقا وموارد الواجهة إلى ملفات متاحة للزوار. كل ما تضعه في JavaScript المرسلة للمتصفح يمكن للزائر قراءته.
المسار: HTML وCSS وJavaScript للمتصفح ← خدمة الملفات الثابتة
2. **حزمة الخادم — يشغّلها Worker**: يعالج Worker طلبات هذه المسارات ويعيد استجاباتها. لا تُقدّم الحزمة كملف قابل للتنزيل؛ وتقرأ الشيفرة القيم السرية من إعدادات Worker عبر env.
المسار: مسارات عند الطلب وشيفرة خادم ← بيئة تشغيل Worker
انشر المخرجات التي يجهزها المحوّل. اختيار جذر المستودع كمجلد للملفات المنشورة قد يكشف الشيفرة المصدرية بدلا من تقديم الموقع المبني.
*قد ينتج البناء ملفات ينزّلها المتصفح وحزمة يشغّلها Worker. يحدد المحوّل ترتيب المجلدات الفعلي؛ الأسماء في الشكل تصف وظيفة المخرجات.*
نفّذ البناء وافحص الناتج: أي الصفحات أصبحت ملفات HTML؟ وأي المسارات تحتاج إلى Worker؟ وما ملفات JavaScript التي سينزّلها الزائر؟
## تشخيص مشكلات النشر
ابدأ بالمرحلة التي فشلت. إذا تعذر تثبيت الحزم، فلم يصل المشروع إلى البناء أصلا. وإذا نجح البناء لكن النموذج لا يصل إلى API، فافحص استجابة HTTP الفعلية.
| المشكلة | ما تفحصه أولا |
| --- | --- |
| الصفحة تفتح لكن زر الإرسال يبقى معطلا | هل حُمّل `/app.js`؟ وهل تظهر أخطاء في وحدة تحكم المتصفح؟ |
| النموذج يتلقى HTML بدلا من JSON | عنوان الطلب، وإعداد الصفحة البديلة، وقواعد `run_worker_first` |
| فتح العنوان في المتصفح يختلف عن طلبه بـ `curl` | الترويسة `Sec-Fetch-Mode` وقواعد التوجيه |
| HTML جديد يحمّل JavaScript قديما | ترويسات التخزين المؤقت، وهل تتغير أسماء الملفات بتغير محتواها؟ |
| API تعمل محليا وتفشل في المعاينة | متغيرات المعاينة وقيمها السرية والموارد المرتبطة بها |
| البناء يتوقف قبل تجميع الشيفرة | سجلات تثبيت الحزم، وملف القفل، وذاكرة البناء المؤقتة |
حدثت المشكلة الأخيرة عند نشر المقال السابق على هذا الموقع. أظهرت سجلات Cloudflare ملفا مؤقتا تالفا لحزمة esbuild، ثم الخطأ `ETXTBSY` أثناء التثبيت. كان الفشل قبل وصول Astro إلى تجميع المقال. في مثل هذه الحالة، تعطيك السجلات سببا لـ [مسح ذاكرة البناء المؤقتة](https://developers.cloudflare.com/workers/ci-cd/builds/build-caching/) وإعادة المحاولة على نسخة الشيفرة نفسها، قبل تغيير شيفرة التطبيق.
إذا تسبب تعديل منشور في تعطيل التطبيق، فاتبع [خطوات العودة إلى إصدار سابق](/ar/blog/series/cloudflare/understanding-cloudflare-workers#العودة-إلى-إصدار-سابق)، ثم اختبر الصفحة والواجهة البرمجية معا. العودة إلى إصدار سابق لا تمسح نسخ المتصفحات المحفوظة، ولا تتراجع عن البيانات المكتوبة في قاعدة البيانات. لذلك يهم اختيار أسماء الملفات وسياسة تخزينها قبل منحها صلاحية طويلة.
## كم تكلف طلبات الموقع؟
وقت كتابة المقال، تدرج Cloudflare طلبات الملفات الثابتة المباشرة ضمن الاستخدام المجاني غير المحدود، من دون رسوم إضافية لتخزين تلك الملفات. أما الطلبات التي تشغّل شيفرة Worker فتخضع لتسعير Workers. يوضح [مرجع التكلفة والحدود](https://developers.cloudflare.com/workers/static-assets/billing-and-limitations/) الفرق.
في مثالنا، لا يتطلب تقديم HTML وCSS وJavaScript تشغيل دالة التحليل. إرسال النص هو ما يستدعيها. وإذا ضبطت Worker ليعمل قبل كل طلب ملف، فستُحتسب تلك الاستدعاءات أيضا، حتى لو كانت الاستجابة النهائية ملفا جاهزا.
لا يشمل ذلك استخدام خدمة البناء أو تسجيل النطاق أو الخدمات التي تضيفها لاحقا. عند تقدير التكلفة، افصل طلبات الملفات عن استدعاءات شيفرة Worker.
## جرّب نشر تعديل صغير
غيّر عنوان الصفحة في فرع مستقل، ثم ارفع التعديل. تأكد من ظهوره في معاينة الفرع، ومن بقاء صفحة الإنتاج كما هي. بعد المراجعة والدمج، افتح النطاق الفعلي وأرسل النموذج من جديد. بهذه التجربة تختبر خطوات النشر التي أعددتها كاملة.
يمكنك استخدام البنية نفسها لنموذج ملاحظات أو لوحة تحكم صغيرة: ملفات عامة للواجهة، ودوال في Worker للعمليات التي تحتاج إلى الخادم، ومعاينة تختبر فيها عملهما معا.
قد تكون الخطوة التالية حفظ المسودة والعودة إليها لاحقا. وهذا يفتح موضوع التخزين الدائم: كيف نحفظ البيانات ونستعلم عنها، وكيف نمنع تجارب المعاينة من تعديل بيانات الإنتاج؟ سنعود إلى هذا التطبيق عند الحديث عن D1.
إذا كنت تعرف من يستعد لنشر موقعه الأول على Cloudflare، شاركه المقال. وأي جزء أتعبك أكثر في تجاربك: التوجيه، أم المعاينة، أم التخزين المؤقت؟ [اكتب لي عما واجهته](/ar/contact)، أو شارك تجربتك مع رابط المقال على X أو LinkedIn.
---
# Cloudflare Workers: from a request to a running application
- URL: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-workers
- Markdown: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-workers.md
- Translation: https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-workers
- Author: Omar Albeik
- Language: en
- Type: tutorial
- Date: 21 September 2026
- Topics: infrastructure
In the [DNS guide](/en/blog/series/cloudflare/understanding-cloudflare-dns),
we connected a domain to an application. Now we need something to answer
the request.
A Cloudflare Worker can be that application. It receives a request, runs
your code, and returns a response. You can use it for a small API, a form
handler, or the server side of a website. This site runs on Workers too.
We'll build a bilingual reading-time API with Hono. Send it some English or Arabic text, and it returns a word count and a reading-time estimate. It's the kind of small tool you could put behind a blog editor. It needs no database, external API key, or AI model.
You'll need some JavaScript knowledge, a terminal, and a current Node.js LTS
installation with npm. TypeScript annotations are explained along the way.
A Cloudflare account is needed for deployment; a domain is optional.
- [Understand the runtime](#what-runs-inside-a-worker).
- [Build and test the API](#create-the-project).
- [Deploy and connect a domain](#give-it-a-public-url).
- [Add configuration, secrets, and storage](#what-belongs-in-env).
- [Understand limits and costs](#cpu-time-isnt-the-time-the-reader-waits).
- [Find a failing request](#follow-a-request-through-the-logs).
## What runs inside a Worker?
Your Worker is server-side code. The visitor receives its response, not its
source. Cloudflare manages the machines running it; you deploy the
application and configure what it can access.
JavaScript Workers run in **V8 isolates**: separate execution environments
within the runtime. An isolate can handle multiple requests and may later
be discarded. You aren't given a permanent process to keep alive or a
machine whose memory you can rely on between visits.
Suppose you add a global visit counter. It seems to work locally: refresh
the page and the number goes up. In production, another isolate can start
its own counter, and a replacement isolate can start over. Cloudflare's
[runtime explanation](https://developers.cloudflare.com/workers/reference/how-workers-works/)
describes this execution model.
**Same code. Separate memory.**
Imagine a visit counter stored in a global variable, starting at zero.
1. **Isolate A — 2**: Requests 1 and 2 arrive here. Its counter reaches 2.
2. **Isolate B — 1**: Request 3 reaches another isolate. Its counter starts at zero.
3. **A fresh isolate — 1**: Request 4 arrives after A is replaced. The new counter starts at zero.
Four visits, no reliable total. This is one possible sequence; isolate reuse and request placement are not guaranteed.
*An in-memory counter belongs to one isolate. It cannot tell you how many requests the whole application has handled.*
Keep request-specific data inside the handler. Immutable constants can live
at module scope; data that must survive needs persistent storage.
Workers uses familiar web APIs: `Request`, `Response`, `URL`, and `fetch()`.
There is no page or DOM here. An HTTP request enters your exported `fetch`
handler, and the returned `Response` becomes the HTTP response.
```ts
export default {
async fetch(request, env, ctx): Promise {
return new Response("The Worker answered.");
},
} satisfies ExportedHandler;
```
The [handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/)
receives three useful objects:
- `request` contains the URL, method, headers, and body sent by the client.
- `env` exposes configured variables, secrets, and service bindings.
- `ctx` controls work associated with this invocation, including work that
can continue briefly after the response.
`ExportedHandler` checks the handler's TypeScript shape. We'll generate
`CloudflareBindings` from the configuration shortly. The types disappear when the code is
built; Cloudflare runs JavaScript.
**From a URL to an answer**
Follow a successful request to our reading-time API.
1. **Client — POST /api/reading-time**: The client sends text, language, and an optional reading speed as JSON.
2. **Cloudflare — Select the Worker**: The configured hostname determines which Worker receives the request.
3. **Your handler — Validate → count**: Hono selects the route. The handler validates JSON and counts word-like segments.
4. **Back to the client — 200 · application/json**: Return the status, headers, and JSON body. Invalid input takes an earlier exit with 400.
This Worker creates the answer itself. No upstream application server or database is involved.
*For this API, the Worker produces the response itself. There is no separate application server behind it.*
The handler named `fetch` receives a request. Calling `fetch()` *inside*
the handler makes an outgoing request. Our example doesn't need that second
step: the runtime can calculate the answer itself.
This also explains where Workers fits alongside DNS. DNS helps the client
find the service; HTTP routing selects the Worker; your code decides what
`/api/reading-time` means. Changing a DNS record doesn't create an API endpoint.
### Can I use npm packages?
Yes, provided their dependencies work in the Workers runtime. Node.js
compatibility supports many built-in modules, but some APIs are partial or
import-only stubs. A successful installation doesn't prove that a package
will run.
For compatibility dates from **August 4, 2026**, Node.js compatibility is
enabled by default, including the date used below. Older examples often add a `nodejs_compat` flag;
Cloudflare's [current compatibility guide](https://developers.cloudflare.com/workers/runtime-apis/nodejs/)
explains the date-dependent behavior. Test the actual code path you need,
especially when a library expects operating-system features.
## Create the project
The native handler above is the foundation. [Hono](https://hono.dev/docs/getting-started/cloudflare-workers) adds named routes and middleware around it. Workers still supplies the runtime, deployment, and bindings. We can write the application's behavior without manually dispatching every URL.
From your projects directory, run:
```bash
npm create cloudflare@latest -- reading-api
```
Choose **Hello World**, **Worker only**, and **TypeScript**, and decline deployment for now. The [Cloudflare project generator](https://developers.cloudflare.com/workers/get-started/guide/) installs Wrangler. Then add Hono:
```bash
cd reading-api
npm install hono
```
We will use two source files: `src/analyze.ts` for the text calculation and `src/index.ts` for HTTP handling. Replace `wrangler.jsonc` with:
```jsonc title="wrangler.jsonc"
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "reading-api",
"main": "src/index.ts",
"compatibility_date": "2026-09-21",
"workers_dev": true,
"vars": {
"SERVICE_NAME": "reading-api",
"DEFAULT_WPM": 200
},
"observability": {
"enabled": true,
"head_sampling_rate": 1
}
}
```
`name` identifies the Worker; `main` is its entry file. `workers_dev` enables a public hostname when you deploy. `observability` stores logs, selecting every request with the sampling rate shown here. These settings don't publish anything yet.
The compatibility date selects runtime behavior, not npm package versions. Start with today's date and test later date changes. If Wrangler cannot support it, update Wrangler in the project. Your lockfile keeps dependency versions reproducible.
`DEFAULT_WPM` is a numeric configuration value. **200 words per minute is a starting assumption for this example, not a measured reading speed for English or Arabic.** Clients can override it within the application's 80–600 range. That range is a product choice, not a Cloudflare limit.
Generate the binding types:
```bash
npx wrangler types --env-interface CloudflareBindings
```
Regenerate them when configuration changes. Hono will use this generated interface to check `c.env`, including the numeric `DEFAULT_WPM` value.
## Try the reading-time tool
Paste a paragraph, choose its language, and adjust the assumed pace. The estimate updates as you type. Expand the API details to see the JSON a client would send and receive.
**How long would this take to read?**
Count words in English or Arabic, then estimate reading time using a pace you choose.
1. **POST /api/reading-time? — 404 / 405**: Unknown paths return 404; other methods on this path return 405 with Allow: POST.
2. **Body within 64 KiB? — 413**: The body-limit middleware rejects oversized requests before parsing JSON.
3. **JSON content type, valid JSON and fields? — 415 / 400**: Wrong content type returns 415. Invalid JSON, text, language, or speed returns 400.
4. **Count words and estimate time — 200**: Return language, words, wordsPerMinute, seconds, and minutes. No database is needed.
The playground only runs the text calculation locally. The server also checks HTTP routing, content type, and body size. A default of 200 words per minute is an adjustable assumption, not a measured average.
*The playground runs the article's analysis function in your browser. The expandable diagram describes the server's checks; no HTTP request is sent by this demo.*
The language selects word-segmentation rules; it doesn't translate the text or verify which language you typed. Mixed Arabic and English text is allowed. Reading time also depends on difficulty, familiarity, and pauses, so the interface should present it as an estimate.
## Count words before handling HTTP
Create `src/analyze.ts`:
```ts title="src/analyze.ts"
export function analyzeReading(input: unknown, defaultWpm = 200) {
if (!input || typeof input !== "object" || Array.isArray(input)) {
return { ok: false as const, error: "Send a JSON object." };
}
const data = input as Record;
if (typeof data.text !== "string" || !data.text.trim()) {
return { ok: false as const, error: "Add some text to analyze." };
}
if (data.text.length > 10_000) {
return {
ok: false as const,
error: "Keep text within 10,000 UTF-16 code units.",
};
}
if (data.language !== "en" && data.language !== "ar") {
return { ok: false as const, error: "Choose en or ar." };
}
const wordsPerMinute =
data.wordsPerMinute === undefined
? defaultWpm
: data.wordsPerMinute;
if (
typeof wordsPerMinute !== "number" ||
!Number.isInteger(wordsPerMinute) ||
wordsPerMinute < 80 ||
wordsPerMinute > 600
) {
return {
ok: false as const,
error: "Use a whole-number reading speed from 80 to 600.",
};
}
const segmenter = new Intl.Segmenter(data.language, {
granularity: "word",
});
let words = 0;
for (const segment of segmenter.segment(data.text)) {
if (segment.isWordLike) {
words++;
}
}
if (words === 0) {
return {
ok: false as const,
error: "Add text containing at least one word.",
};
}
return {
ok: true as const,
value: {
language: data.language,
words,
wordsPerMinute,
seconds: Math.ceil((words / wordsPerMinute) * 60),
minutes: Math.ceil(words / wordsPerMinute),
},
};
}
```
[`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter) identifies word boundaries using the chosen locale. We count segments marked `isWordLike`; punctuation and spaces alone don't count. This isn't Arabic morphological analysis: attached prefixes aren't necessarily separate words. Runtime language-data versions can also produce small differences in segmentation.
The function accepts `unknown` because a TypeScript annotation cannot validate incoming JSON. It checks the object, text, language, and reading speed before doing the calculation. The text limit uses JavaScript's `text.length`: 10,000 UTF-16 code units, not bytes or visible characters. Emoji, for example, may use more than one unit.
`seconds` and `minutes` are independently rounded up. Five words at 200 words per minute gives 2 seconds or 1 minute rounded up; display the unit that suits your interface. There is no artificial one-minute minimum on the seconds field.
## Add the Hono routes
Replace `src/index.ts` with:
```ts title="src/index.ts"
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { analyzeReading } from "./analyze";
const app = new Hono<{
Bindings: CloudflareBindings;
Variables: {
requestId: string;
};
}>();
app.use("*", async (c, next) => {
const requestId = crypto.randomUUID();
c.set("requestId", requestId);
c.header("X-Request-Id", requestId);
c.header("Cache-Control", "no-store");
await next();
console.log({
event: "reading_api_response",
requestId,
status: c.res.status,
});
});
app.get("/health", (c) => {
return c.json({ status: "ok", service: c.env.SERVICE_NAME });
});
app.post(
"/api/reading-time",
bodyLimit({
maxSize: 64 * 1024,
onError: (c) =>
c.json({ error: "Keep the request body within 64 KiB." }, 413),
}),
async (c) => {
const mediaType = c.req
.header("Content-Type")
?.split(";")[0]
?.trim()
.toLowerCase();
if (mediaType !== "application/json") {
return c.json(
{ error: "Use Content-Type: application/json." },
415,
);
}
let input: unknown;
try {
input = await c.req.json();
} catch (error) {
if (error instanceof SyntaxError) {
return c.json({ error: "Send valid JSON." }, 400);
}
throw error;
}
const defaultWpm = c.env.DEFAULT_WPM;
if (
!Number.isInteger(defaultWpm) ||
defaultWpm < 80 ||
defaultWpm > 600
) {
throw new Error("Invalid DEFAULT_WPM configuration.");
}
const result = analyzeReading(input, defaultWpm);
if (!result.ok) {
return c.json({ error: result.error }, 400);
}
return c.json(result.value);
},
);
app.all("/api/reading-time", (c) => {
c.header("Allow", "POST");
return c.json({ error: "Use POST." }, 405);
});
app.notFound((c) => c.json({ error: "Not found." }, 404));
app.onError((error, c) => {
console.error({
event: "reading_api_error",
requestId: c.get("requestId"),
name: error.name,
});
return c.json({ error: "Internal server error." }, 500);
});
export default app;
```
Read this in three parts. The first middleware assigns a fresh request ID, sets `no-store`, and logs the final status after `await next()`. It doesn't log submitted text. Then `GET /health` checks that the application responds, while `POST /api/reading-time` handles analysis. Finally, explicit fallbacks cover wrong methods, unknown routes, and unexpected errors.
Hono's [context](https://hono.dev/docs/api/context) gives each request its own `c`. Use `c.req` for the request, `c.env` for Workers bindings, and `c.json()` to return JSON. `Variables` describes request-scoped values set with `c.set()`; it isn't another place to configure environment bindings.
The [body-limit middleware](https://hono.dev/docs/middleware/builtin/body-limit) bounds the body at 64 KiB before we parse JSON. Its limit includes the JSON syntax and encoded text. It uses Content-Length when present and checks a stream when it isn't. This byte limit is separate from the text-length rule. Oversized bodies return `413`; other validation runs only after that check passes.
The route requires `application/json`, otherwise it returns `415`. Broken JSON syntax and invalid fields return `400`. The `app.all()` fallback returns `405` with `Allow: POST` for other methods on the analysis path. Unknown paths return `404`. Hono handles a `HEAD` request to the health route without a body; the analysis route remains POST-only.
`app.onError()` gives unexpected application exceptions a generic `500` and logs their name with the request ID. This deliberately avoids exposing or recording user text. Platform failures, such as exhausting CPU, can still happen outside application error handling. Keep reading for the runtime limits.
## Test the API locally
```bash
npx wrangler dev --local
```
Wrangler uses the Workers runtime, `workerd`, locally. `--local` disables remote binding connections; it does not block outgoing `fetch()` calls to real services. Our example makes no such calls. The [local development guide](https://developers.cloudflare.com/workers/local-development/) explains the distinction.
In another terminal, send a paragraph:
```bash
curl -i 'http://localhost:8787/api/reading-time' \
-H 'Content-Type: application/json' \
--data '{"text":"Small APIs can be useful.","language":"en"}'
```
Expect `200`, `Cache-Control: no-store`, an `X-Request-Id`, and this JSON:
```json title="Response"
{
"language": "en",
"words": 5,
"wordsPerMinute": 200,
"seconds": 2,
"minutes": 1
}
```
To use Arabic, set `language` to `ar` and send Arabic text. Add `"wordsPerMinute": 150` to override the configured default. Then try the failure cases:
```bash
# Health check: 200
curl -i 'http://localhost:8787/health'
# Empty text: 400
curl -i 'http://localhost:8787/api/reading-time' \
-H 'Content-Type: application/json' \
--data '{"text":"","language":"en"}'
# Invalid JSON: 400
curl -i 'http://localhost:8787/api/reading-time' \
-H 'Content-Type: application/json' \
--data '{'
# Wrong content type: 415
curl -i 'http://localhost:8787/api/reading-time' \
--data 'hello'
# Wrong method: 405, with Allow: POST
curl -i 'http://localhost:8787/api/reading-time'
# Unknown route: 404
curl -i 'http://localhost:8787/missing'
```
For a real article, save the JSON payload in `request.json` and use `--data-binary @request.json` with the same content-type header. This preserves UTF-8 text and avoids shell-quoting problems. Also test an unsupported language, punctuation-only text, a fractional or out-of-range speed, and a body larger than 64 KiB before relying on the endpoint.
This is a public API with no authentication. `no-store` asks caches not to retain its responses; it isn't an access-control mechanism. If a frontend on another origin calls it, add a CORS policy for that client. CORS governs browser access to responses, not caller identity.
## Give it a public URL
**When does the code become public?**
The first three steps run on your machine. The fourth publishes the Worker.
1. **01 · Edit — src/index.ts + wrangler.jsonc**: Your handler and its configuration live in the project.
2. **02 · Run locally — wrangler dev --local**: Try real HTTP requests against a local Workers runtime.
3. **03 · Check the bundle — wrangler deploy --dry-run**: Build the deployment bundle without publishing a version.
4. **04 · Publish — wrangler deploy**: Upload the Worker and make the deployment serve traffic. Check its printed URL.
A dry run checks the bundle. Only a request to the deployed URL checks the live routing and configuration.
*Editing, local requests, and a deployment dry run leave the public Worker unchanged. Deploying is the step that makes the new code live.*
First check the types and the deployment bundle:
```bash
npx tsc --noEmit
npx wrangler deploy --dry-run
```
The dry run builds the Worker without publishing it. It cannot prove that
production permissions, domains, or future remote dependencies are correct.
When you're ready to publish the example, sign in and deploy:
```bash
npx wrangler login
npx wrangler deploy
```
Wrangler prints the deployed URL, typically in the form
`https://reading-api..workers.dev`. Use the actual URL from the
command output, use `/health` for a quick check, then repeat the POST examples against
`/api/reading-time` at that hostname. You don't need to buy a domain to reach this point.
Local testing exercises the code. Testing the deployed URL also checks
that you're reaching the intended account, Worker, and configuration.
### Connect your own domain
For this API, the Worker is the application's origin. A **Custom Domain**
connects an entire hostname to it. With an active domain on Cloudflare, add
this top-level property to `wrangler.jsonc`, substituting a hostname you own:
```jsonc title="wrangler.jsonc · merge into existing config"
{
"routes": [
{
"pattern": "reading.example.com",
"custom_domain": true
}
]
}
```
Deploy again. Cloudflare manages the DNS record and certificate for the
[Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/).
Use an unused hostname: an existing CNAME can conflict with this setup.
Hono still selects the route, so send your POST request to
`https://reading.example.com/api/reading-time`.
A **Route** serves a different setup: your Worker runs in front of an
existing proxied origin, for example to inspect a request before forwarding
it to a server you already operate. A route matches a URL pattern and
requires the corresponding proxied DNS record. The
[routing guide](https://developers.cloudflare.com/workers/configuration/routing/routes/)
covers that arrangement. Our reading-time API doesn't need another origin.
## What belongs in env?
We've used `c.env.SERVICE_NAME` for a public label and `c.env.DEFAULT_WPM` for the default reading pace. As an application grows,
`env` can also expose secrets and connections to services. These have
different jobs.
**What does env give your code?**
The reading-time API uses the first entry. The others show how an application could grow.
1. **c.env.SERVICE\_NAME — A value**: A non-secret label from vars: reading-api.
2. **c.env.PROVIDER\_API\_KEY — A secret**: A credential your code can use when calling an external provider.
3. **c.env.DB — A database binding**: An interface to one configured D1 database, with permission to use it.
4. **c.env.UPLOADS — A bucket binding**: An interface to one configured R2 bucket. The files live in R2.
A resource binding provides access to the resource. It does not copy a database or bucket into the Worker's memory.
*Variables and secrets provide values. Resource bindings provide interfaces to configured services; the data stays in those services.*
A [binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/)
gives your Worker a configured interface to a resource. With a D1 binding
named `DB`, for instance, your code can query through `c.env.DB`. You don't
need to put a Cloudflare account API token in the handler to use that
binding. Choose the resource, configure the binding, then regenerate types.
The reading-time API needs no stored data. If it grew into an editorial tool,
the choice would depend on what it saves:
- **D1** for records you want to query with SQL, such as saved articles.
- **KV** for reads by key where delayed visibility of updates is acceptable.
- **R2** for files, such as exported documents.
- **Durable Objects** when operations need coordination around one object,
such as editors updating the same document.
These are starting points, not interchangeable ways to make a global
variable persistent. Cloudflare's [storage comparison](https://developers.cloudflare.com/workers/platform/storage-options/)
is a useful reference; later parts of this series will work through the
tradeoffs in detail.
### Keep credentials out of the configuration file
If you later call an external provider, add its credential as a secret:
```bash
npx wrangler secret put PROVIDER_API_KEY
```
Wrangler prompts for the value. Your code then reads `c.env.PROVIDER_API_KEY`.
For local development, use a `.dev.vars` file and add `.dev.vars*` and
`.env*` to `.gitignore`. Local secret files are not uploaded as production
secrets. The [secrets guide](https://developers.cloudflare.com/workers/configuration/secrets/)
explains both setups.
Skip this step for the reading-time API; it has no credentials.
### Separate staging from production when you need it
[Wrangler environments](https://developers.cloudflare.com/workers/wrangler/environments/)
let you deploy the same project as separate Workers. For example, add an
`env` property alongside the existing configuration:
```jsonc title="wrangler.jsonc · merge into existing config"
{
"env": {
"staging": {
"routes": [],
"vars": {
"SERVICE_NAME": "reading-api-staging",
"DEFAULT_WPM": 200
}
}
}
}
```
```bash
npx wrangler dev --local --env staging
npx wrangler deploy --env staging
```
The deployment command creates `reading-api-staging`. Its empty `routes` list
keeps it from inheriting the production domain added earlier; test it on
its own `workers.dev` URL. The original top-level configuration still
targets `reading-api`. Keep the intended target explicit in commands that
change a deployment.
Variables and resource bindings aren't inherited from the top level;
declare them for each environment. Separate Worker names alone don't
isolate data if both bindings point at the same database. Set secrets for
the intended environment too, using `--env staging` where appropriate.
**Separate the data as well as the names**
If you later add D1, give each environment its own database. Both Workers can use the binding name c.env.DB.
1. **Staging — reading-api-staging**: c.env.DB connects to a test database: reading-api-staging-db.
2. **Production — reading-api**: c.env.DB connects to a live database: reading-api-production-db.
Database names here are illustrative; the reading-time API has no database yet. Point both bindings at the same database and both Workers can change the same data.
*The same binding name can refer to different resources. Choose the database separately for each environment.*
## CPU time isn't the time the reader waits
Imagine an endpoint that validates input, waits for a database, then
formats a response. It might spend 3 ms executing validation, 200 ms waiting,
and 2 ms formatting. That's about 205 ms inside the handler, but only 5 ms
of CPU work. These are illustrative numbers, not a benchmark of our API.
**Two clocks, one request**
Keep the code's work fixed. Change only the time spent waiting for data.
1. **Validate — 3 ms CPU**: Execute the input checks.
2. **Wait for data — 200 ms waiting**: Waiting on the network adds elapsed time, without adding Worker CPU time.
3. **Format — 2 ms CPU**: Build the response.
At the default 200 ms wait: 5 ms CPU, about 205 ms elapsed in the handler. Illustrative values; not a benchmark. Other network overhead is omitted.
*Network waiting affects response time even when it doesn't count as Worker CPU time. A low CPU figure alone doesn't mean a fast application.*
That distinction matters when choosing a plan. As of September 21, 2026,
the [Workers limits](https://developers.cloudflare.com/workers/platform/limits/)
for ordinary HTTP handlers include:
| Limit | Workers Free | Workers Paid |
| --- | --- | --- |
| Incoming requests | 100,000 per day | Usage-based billing |
| CPU per request | 10 ms | 30 seconds by default; configurable up to 5 minutes |
| Memory per isolate | 128 MB | 128 MB |
The daily Free allowance is account-wide and resets at midnight UTC. Network
waiting doesn't consume CPU time. Request lifetime is a separate concern:
when a client disconnects, unfinished work can be canceled.
Memory is also shared by requests in an isolate. For large payloads,
[streaming](https://developers.cloudflare.com/workers/runtime-apis/streams/)
lets you pass data through without buffering the entire body. This API returns a small object, so Hono’s `c.json()` is appropriate.
### Nearby code can still wait for a distant database
By default, Workers runs near where the request reaches Cloudflare.
That helps our API because it needs no remote data. An application making
several round trips to a database elsewhere has a different bottleneck.
[Placement](https://developers.cloudflare.com/workers/configuration/placement/)
can run the Worker closer to its backend when that reduces overall latency.
Measure the request and its dependencies before moving it: distance to the
user is only one part of response time.
### Work after the response needs a lifetime
If a result depends on an asynchronous operation, `await` it. For optional,
short work that can finish after the response, the handler's `ctx` offers
`waitUntil()`. In Hono, access it as `c.executionCtx.waitUntil()`.
For HTTP handlers, [the documented allowance](https://developers.cloudflare.com/workers/runtime-apis/context/)
is up to 30 seconds after the response is sent or the client disconnects,
shared across that invocation's `waitUntil()` tasks. Starting a promise and
forgetting it can leave the work unfinished.
Use a Queue when the task needs durable delivery and retries. Use a
[Workflow](https://developers.cloudflare.com/workflows/) for a process
that needs durable steps and waits. Returning “saved” before
an unawaited database write finishes is a bug, even if it worked in a
local test.
## What would this cost?
The Free plan is a reasonable place to try the API. Measure its CPU usage
and traffic before deciding whether it needs a paid plan.
At the time of writing, the [Workers Standard pricing](https://developers.cloudflare.com/workers/platform/pricing/)
starts at **$5 USD per account per month**, including 10 million requests
and 30 million CPU milliseconds. Additional usage costs $0.30 per million
requests and $0.02 per million CPU milliseconds.
**How 12 million requests add up to $5.96**
Assume 4 ms of CPU per request: 12 million × 4 = 48 million CPU milliseconds. Only usage above the included amounts adds to the base charge.
1. **Base subscription — $5.00**: Includes 10 million requests and 30 million CPU milliseconds.
2. **Extra requests — $0.60**: 2 million extra requests × $0.30 per million.
3. **Extra CPU — $0.36**: 18 million extra CPU milliseconds × $0.02 per million.
Compute total: $5.96. Assumes no other application uses the account's included allowance. Excludes taxes, logs, storage, and other services.
*The solid portion of each bar is included in the subscription; the striped portion is additional usage. Rates are those listed above, as of September 21, 2026.*
This assumes the account's included compute usage is available to this
application. It excludes taxes, logs, storage, and other services. The
4 ms figure is an assumption for the calculation, not a measured result.
Treat $5 as a starting charge, not a spending cap. Review usage and logging
volume as traffic grows; a small response can still be requested often.
## Follow a request through the logs
While `wrangler dev` is running, the terminal shows the example's log
entries. After deployment, stream live logs with:
```bash
npx wrangler tail
```
Send a request and compare its `X-Request-Id` response header with the
`requestId` in the `reading_api_response` log entry. For a staging deployment,
use `npx wrangler tail --env staging`.
The [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/)
view in the dashboard provides stored logs when observability is enabled.
Our `head_sampling_rate` of `1` selects every request; a value such as `0.1`
selects roughly 10%. Sampling is useful at higher volume, but also means a
particular request may have no stored log.
Logs have their own limits, retention, and pricing. This example writes an
application log in addition to the platform's invocation logging, so log
events and requests are not the same count.
A few symptoms point to different places:
| Symptom | First thing to inspect |
| --- | --- |
| `400` with our JSON error | The JSON syntax, text, language, and reading speed |
| `404` with our JSON error | The path: `/health` or `/api/reading-time` |
| `413` or `415` | Body size or the Content-Type header |
| No matching application log | The URL, target Worker, environment, and log sampling |
| A binding is undefined | Its name and the selected environment's configuration |
| `1102` resource-limit error | CPU and memory measurements for the failing invocation |
| Low CPU time, slow response | Network calls and backend latency |
For an application exception, match the response ID to the `reading_api_error` entry. Our handler records the exception name and returns a generic `500`. A bad `DEFAULT_WPM` is a configuration failure, not a client's `400`. If there is no application response, inspect the platform's invocation errors and resource measurements too.
## Know how to undo a deployment
A Worker version records code and configuration; a deployment selects
which version serves traffic. List recent versions with:
```bash
npx wrangler versions list
```
If a deployment breaks the API, choose a known-good deployed version and
[roll back](https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/):
```bash
npx wrangler rollback
```
Replace the placeholder with the actual ID, and add `--env staging` when
that's the target. Repeat the HTTP checks against the deployed URL after
the rollback.
Rolling back code doesn't reverse database writes or restore deleted
storage resources. A deleted binding target or certain Durable Object
changes can also prevent a rollback. Once you add persistent data, migrations need their own
recovery plan and compatibility with the code you might roll back to.
## Where to take it next
You now have a small application whose behavior you can inspect end to end:
a request enters, input is checked, a response comes back, and a log records
what happened. The same handler can later use bindings to read data or call
another service.
For a useful extension, let an editor analyze several drafts in one request. Cap the batch size and total body size, then decide whether one invalid draft rejects the whole batch. Test the decision. Those are application rules; Hono organizes the routes, and Workers runs them.
The next part will add a frontend and cover serving a website on Workers,
including where Pages fits.
If you know someone moving their first API to Workers, share this guide
with them. What did you find hardest to understand in your first Worker:
the runtime, bindings, or deployment? [Send me your example](/en/contact),
or share it alongside the article on X or LinkedIn.
---
# دليل Cloudflare Workers: من أول طلب إلى تطبيق يعمل
- URL: https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-workers
- Markdown: https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-workers.md
- Translation: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-workers
- Author: Omar Albeik
- Language: ar
- Type: tutorial
- Date: 21 أيلول 2026
- Topics: infrastructure
في [دليل DNS](/ar/blog/series/cloudflare/understanding-cloudflare-dns)، تعرّفنا على إعداد النطاق وربطه بالتطبيق. نكمل هنا من جهة التطبيق نفسه: أين تعمل الشيفرة التي تستقبل الطلب، وكيف نكتبها وننشرها؟
**Cloudflare Workers** بيئة لتشغيل شيفرة الخادم. يستقبل تطبيقك، الذي نسميه Worker، الطلب وينفذ الشيفرة ثم يعيد الاستجابة. يمكنك بناء واجهة برمجية (API) صغيرة عليه، أو معالجة بيانات نموذج، أو تشغيل الجزء الخاص بالخادم من موقعك. وهذا الموقع نفسه يعمل على Workers.
سنبني باستخدام Hono واجهة تقدّر مدة قراءة النصوص العربية والإنجليزية. ترسل إليها نصا، فتعيد عدد كلماته والوقت المتوقع لقراءته. يمكنك إضافة هذه الأداة إلى محرر مقالات؛ وكل ما تحتاجه هنا هو الشيفرة نفسها، من دون قاعدة بيانات أو خدمة خارجية.
للمتابعة، تحتاج إلى أساسيات JavaScript، وطرفية، وإصدار حديث طويل الدعم (LTS) من Node.js مع npm. سنشرح ما نستخدمه من أنواع TypeScript أثناء العمل. يمكنك تجربة المثال محليا دون حساب Cloudflare؛ ستحتاج إليه عند النشر. أما شراء نطاق فاختياري.
- [فهم بيئة التشغيل](#كيف-يعمل-worker).
- [بناء الواجهة واختبارها](#إنشاء-المشروع).
- [النشر وربط النطاق](#نشر-التطبيق).
- [الإعدادات وبيانات الاعتماد والتخزين](#الإعدادات-وربط-الخدمات-عبر-env).
- [حدود الاستخدام والتكلفة](#زمن-المعالجة-ومدة-انتظار-الاستجابة).
- [تتبع الطلبات وتشخيص الأخطاء](#تتبع-الطلب-في-السجلات).
## كيف يعمل Worker؟
تتولى Cloudflare إدارة الأجهزة التي تشغّل التطبيق. تنشر أنت الشيفرة وتحدد الموارد التي يمكنها الوصول إليها، ويتلقى الزائر الاستجابة التي تنتجها. تظل شيفرة Worker على الخادم.
تعمل شيفرة JavaScript داخل **بيئات V8 معزولة (isolates)**. قد تعالج البيئة الواحدة عدة طلبات، ثم تستبدلها المنصة ببيئة جديدة. لذلك لا يمكنك الاعتماد على استمرارها أو بقاء ما وضعته في ذاكرتها بين طلب وآخر.
لنفترض أنك أضفت عدادا للزيارات في متغير عام. يبدو أنه يعمل على جهازك: تحدّث الصفحة فيزداد العدد. لكن في بيئة الإنتاج، قد يصل الطلب إلى بيئة معزولة أخرى لها عدادها الخاص، أو إلى بيئة جديدة يبدأ عدادها من الصفر. يشرح [دليل بيئة التشغيل](https://developers.cloudflare.com/workers/reference/how-workers-works/) هذا النموذج بالتفصيل.
**الشيفرة واحدة، والذاكرة منفصلة**
لنفترض أن لدينا عدادا للزيارات في متغير عام، يبدأ من الصفر.
1. **البيئة المعزولة A — 2**: وصل إليها الطلبان الأول والثاني، فارتفع العداد إلى 2.
2. **البيئة المعزولة B — 1**: وصل الطلب الثالث إلى بيئة أخرى، يبدأ عدادها من الصفر.
3. **بيئة معزولة جديدة — 1**: وصل الطلب الرابع بعد استبدال البيئة A. بدأ العداد الجديد من الصفر أيضا.
وصلت أربعة طلبات، لكن أيا من العدادات لا يحمل مجموعها. هذا مثال محتمل؛ لا تضمن المنصة إعادة استخدام البيئة نفسها لكل طلب.
*لا يمكنك معرفة مجموع طلبات التطبيق من عدّاد في ذاكرة بيئة معزولة واحدة.*
لهذا، احتفظ ببيانات كل طلب داخل دالة معالجته. يمكن وضع الثوابت خارج الدالة، أما البيانات التي تريد الاحتفاظ بها بين الطلبات فتحتاج إلى تخزين دائم.
توفر Workers واجهات ويب مألوفة مثل `Request` و`Response` و`URL` و`fetch()`، لكن من دون صفحة ويب أو شجرة DOM. يستقبل التطبيق طلب HTTP عبر دالة `fetch` التي يصدّرها، ويعيد كائن `Response` بوصفه استجابة الطلب:
```ts
export default {
async fetch(request, env, ctx): Promise {
return new Response("The Worker answered.");
},
} satisfies ExportedHandler;
```
تستقبل [دالة المعالجة](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/) ثلاثة كائنات:
- `request`: عنوان الطلب وطريقته وترويساته ومحتواه، كما أرسلها العميل.
- `env`: المتغيرات والقيم السرية والموارد التي ربطتها بالتطبيق في الإعدادات، مثل قواعد البيانات.
- `ctx`: أدوات لإدارة المهام المرتبطة بالطلب الحالي، ومنها إتاحة وقت قصير لإكمال بعض الأعمال بعد إرسال الاستجابة.
يتيح `ExportedHandler` لـ TypeScript التحقق من توقيع الدالة. سنولّد تعريف `CloudflareBindings` من ملف الإعدادات بعد قليل. هذه الأنواع تساعدنا أثناء التطوير، ثم تُحذف عند البناء؛ ما تشغّله Cloudflare هو JavaScript.
**من وصول الطلب إلى إرسال الاستجابة**
نتتبع طلبا ناجحا إلى واجهة تقدير مدة القراءة التي سنبنيها.
1. **العميل — POST /api/reading-time**: يرسل العميل النص واللغة بصيغة JSON، ويمكنه تحديد سرعة القراءة أيضا.
2. **Cloudflare — اختيار التطبيق**: تحدد إعدادات اسم المضيف تطبيق Worker الذي يستقبل الطلب.
3. **دالة معالجة الطلب — التحقق ← العد**: يختار Hono دالة المعالجة بحسب المسار، فتتحقق من JSON وتعدّ الكلمات.
4. **العودة إلى العميل — 200 · application/json**: يتلقى العميل الحالة والترويسات ونتيجة الحساب بصيغة JSON. إذا كانت المدخلات غير صالحة، نعيد 400 عند التحقق منها.
يحسب التطبيق النتيجة من النص المرسل، دون الرجوع إلى قاعدة بيانات أو خادم آخر.
*تحدد إعدادات التوجيه تطبيق Worker، ويحدد المسار داخل التطبيق الدالة التي تعالج الطلب.*
انتبه إلى الفرق بين استخدامين للاسم `fetch`: الدالة في المثال تستقبل الطلب الوارد، أما استدعاء `fetch()` داخلها فيرسل طلبا إلى خدمة أخرى. لن نحتاج إلى اتصال خارجي في واجهة تقدير القراءة؛ سنحسب النتيجة مباشرة من النص المرسل.
بهذا تكتمل صلة Workers بما شرحناه عن DNS: يساعد DNS العميل على الوصول إلى الخدمة، ويحدد توجيه HTTP تطبيق Worker المقصود، ثم تختار شيفرتك ما يحدث عند طلب `/api/reading-time`. إعداد DNS وحده لا ينشئ هذا المسار داخل التطبيق.
### هل يمكن استخدام حزم npm؟
نعم، بشرط أن تعمل الحزمة والحزم التي تعتمد عليها ضمن بيئة Workers. تدعم طبقة التوافق مع Node.js كثيرا من وحداته المدمجة، لكن الدعم جزئي لبعض الواجهات، وبعضها يمكن استيراده دون أن تتوفر وظائفه. لذلك اختبر الحزمة في بيئة Workers؛ نجاح تثبيتها وحده لا يكفي.
يُفعّل التوافق مع Node.js افتراضيا عندما يكون تاريخ التوافق **4 آب 2026** أو أحدث، وهو ما ينطبق على مثالنا. قد ترى في أمثلة أقدم الخيار `nodejs_compat` مضافا صراحة. يشرح [دليل التوافق](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) هذا الاختلاف. وتظل تجربة الوظائف التي تحتاجها ضرورية، خاصة إذا كانت الحزمة تعتمد على إمكانات نظام التشغيل.
## إنشاء المشروع
رأينا كيف تستقبل دالة واحدة الطلب وتعيد الاستجابة. سنستخدم الآن [Hono](https://hono.dev/docs/getting-started/cloudflare-workers) لتنظيم التطبيق: نعرّف مسارا لكل وظيفة، ونضيف دوال وسيطة (middleware) لفحص الطلبات. تتولى Workers تشغيل هذه الشيفرة ونشرها وإتاحة الموارد المرتبطة بها.
افتح الطرفية في مجلد مشاريعك، ثم نفّذ:
```bash
npm create cloudflare@latest -- reading-api
```
اختر **Hello World**، ثم **Worker only** و**TypeScript**، واختر عدم النشر في هذه الخطوة. تتكفل [أداة إنشاء المشروع](https://developers.cloudflare.com/workers/get-started/guide/) بتثبيت Wrangler، الأداة التي سنستخدمها للتشغيل المحلي والنشر. ادخل إلى مجلد المشروع وأضف Hono:
```bash
cd reading-api
npm install hono
```
سنفصل العمل بين ملفين: `src/analyze.ts` لعدّ الكلمات وحساب المدة، و`src/index.ts` لاستقبال طلبات HTTP والرد عليها. لنبدأ بالإعدادات؛ استبدل محتوى `wrangler.jsonc` بما يلي:
```jsonc title="wrangler.jsonc"
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "reading-api",
"main": "src/index.ts",
"compatibility_date": "2026-09-21",
"workers_dev": true,
"vars": {
"SERVICE_NAME": "reading-api",
"DEFAULT_WPM": 200
},
"observability": {
"enabled": true,
"head_sampling_rate": 1
}
}
```
يحدد `name` اسم التطبيق، و`main` الملف الذي يبدأ منه التنفيذ. يتيح `workers_dev` الوصول إلى التطبيق عبر عنوان عام بعد النشر. وتفعّل `observability` حفظ السجلات؛ اخترنا هنا تسجيل جميع الطلبات بوضع `head_sampling_rate` عند `1`. سنعود إلى السجلات لاحقا.
أما تاريخ التوافق فيحدد سلوك بيئة التشغيل. ابدأ بتاريخ اليوم، واختبر التطبيق إذا غيّرت هذا التاريخ لاحقا. إذا كان إصدار Wrangler لا يدعمه، فحدّث Wrangler داخل المشروع. تاريخ التوافق مستقل عن إصدارات حزم npm؛ تلك يحفظها ملف القفل.
حددنا سرعة القراءة الافتراضية في `DEFAULT_WPM`. **اخترنا 200 كلمة في الدقيقة للتجربة، لا بوصفها متوسطا مقاسا للقراءة بالعربية أو الإنجليزية.** يستطيع العميل إرسال سرعة مختلفة بين 80 و600 كلمة في الدقيقة. وضعنا هذا النطاق في تطبيقنا؛ وهو ليس من حدود Cloudflare.
ولّد الآن تعريفات TypeScript من الإعدادات:
```bash
npx wrangler types --env-interface CloudflareBindings
```
أعد تشغيل الأمر كلما غيّرت الإعدادات. يستخدم Hono التعريف الناتج للتحقق من أنواع القيم التي نقرأها عبر `c.env`، ومنها `DEFAULT_WPM` الرقمية.
## جرب أداة تقدير مدة القراءة
قبل كتابة الشيفرة، جرّب النتيجة التي نريد الوصول إليها. ألصق فقرة واختر لغتها، ثم غيّر سرعة القراءة لترى أثرها في المدة. افتح تفاصيل الطلب والاستجابة إذا أردت رؤية شكل JSON الذي ستتعامل معه الواجهة.
**كم تستغرق قراءة هذا النص؟**
جرّب نصا عربيا أو إنجليزيا، وغيّر سرعة القراءة لترى أثرها في المدة.
1. **POST /api/reading-time؟ — 404 / 405**: المسار المجهول يعيد 404. وأي طريقة أخرى على مسار التحليل تعيد 405 مع Allow: POST.
2. **هل جسم الطلب ضمن حد 64 كيبيبايت؟ — 413**: ترفض الدالة الوسيطة الطلب إذا تجاوز حجمه الحد، قبل تحليل JSON.
3. **هل نوع المحتوى وصيغة JSON والحقول صحيحة؟ — 415 / 400**: نعيد 415 إذا كان نوع المحتوى غير مقبول، و400 إذا كان الخلل في JSON أو النص أو اللغة أو السرعة.
4. **عدّ الكلمات وحساب المدة — 200**: تتضمن النتيجة اللغة وعدد الكلمات وسرعة القراءة والمدة بالثواني والدقائق.
وضعنا السرعة الافتراضية عند 200 كلمة في الدقيقة للتجربة. يمكنك تغييرها؛ فهي ليست متوسطا مقاسا للقراءة.
*تعمل أداة القراءة داخل المتصفح. افتح مخطط التحقق لترى الفحوص الإضافية التي سيجريها الخادم عند استقبال طلب HTTP.*
يحدد اختيار اللغة قواعد تقسيم النص إلى كلمات؛ ولا يترجم النص أو يتحقق من اللغة المكتوب بها. ويمكنك تجربة نص يجمع العربية والإنجليزية. أما المدة فهي تقديرية، لأن صعوبة النص وإلمام القارئ بموضوعه يؤثران في سرعة قراءته.
## عدّ الكلمات وتقدير مدة القراءة
نبدأ بدالة مستقلة عن HTTP: تتحقق من النص واللغة والسرعة، ثم تعدّ الكلمات وتحسب المدة. هذا هو الجزء الذي شغّلته الأداة السابقة داخل متصفحك. أنشئ الملف `src/analyze.ts`:
```ts title="src/analyze.ts"
export function analyzeReading(input: unknown, defaultWpm = 200) {
if (!input || typeof input !== "object" || Array.isArray(input)) {
return { ok: false as const, error: "Send a JSON object." };
}
const data = input as Record;
if (typeof data.text !== "string" || !data.text.trim()) {
return { ok: false as const, error: "Add some text to analyze." };
}
if (data.text.length > 10_000) {
return {
ok: false as const,
error: "Keep text within 10,000 UTF-16 code units.",
};
}
if (data.language !== "en" && data.language !== "ar") {
return { ok: false as const, error: "Choose en or ar." };
}
const wordsPerMinute =
data.wordsPerMinute === undefined
? defaultWpm
: data.wordsPerMinute;
if (
typeof wordsPerMinute !== "number" ||
!Number.isInteger(wordsPerMinute) ||
wordsPerMinute < 80 ||
wordsPerMinute > 600
) {
return {
ok: false as const,
error: "Use a whole-number reading speed from 80 to 600.",
};
}
const segmenter = new Intl.Segmenter(data.language, {
granularity: "word",
});
let words = 0;
for (const segment of segmenter.segment(data.text)) {
if (segment.isWordLike) {
words++;
}
}
if (words === 0) {
return {
ok: false as const,
error: "Add text containing at least one word.",
};
}
return {
ok: true as const,
value: {
language: data.language,
words,
wordsPerMinute,
seconds: Math.ceil((words / wordsPerMinute) * 60),
minutes: Math.ceil(words / wordsPerMinute),
},
};
}
```
نستخدم [`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter) لتقسيم النص بحسب قواعد اللغة المختارة، ونعدّ المقاطع التي تحمل `isWordLike`. بذلك لا تدخل المسافات وعلامات الترقيم وحدها في العدد. لا يجري هذا تحليلا صرفيا للعربية؛ فالحروف المتصلة بالكلمة ليست بالضرورة كلمات مستقلة في الحساب. وقد تختلف بعض النتائج قليلا بين بيئات التشغيل، بحسب إصدار بيانات اللغة فيها.
تقبل الدالة قيمة من النوع `unknown` لأن أنواع TypeScript لا تفحص JSON عند وصوله. نتحقق من البيانات بأنفسنا قبل الحساب. كذلك، يقيس `text.length` طول النص بوحدات UTF-16: الحد هنا 10,000 وحدة، لا 10,000 بايت أو حرف ظاهر. فالرمز التعبيري الواحد قد يشغل أكثر من وحدة.
نقرّب قيمتي `seconds` و`minutes` إلى العدد الصحيح الأعلى، كل قيمة على حدة. مثلا، يعطي حساب خمس كلمات بسرعة 200 كلمة في الدقيقة مدة قدرها 1.5 ثانية. نقرّبها إلى ثانيتين، أو إلى دقيقة واحدة إذا اخترنا عرض المدة بالدقائق. لهذا تعرض الأداة السابقة الثواني، حتى تكون النتيجة مفيدة للنصوص القصيرة.
## إضافة المسارات باستخدام Hono
لدينا الآن دالة الحساب. سنستخدمها في تطبيق له مساران: أحدهما للتأكد من أن التطبيق يستجيب، والآخر لاستقبال النص وإعادة النتيجة.
يوفر Hono لكل طلب [كائن سياق](https://hono.dev/docs/api/context) نسميه `c`. نقرأ الطلب عبر `c.req`، ونصل إلى إعدادات Workers ومواردها عبر `c.env`، ونعيد JSON باستخدام `c.json()`. أما `Variables` فيصف القيم التي نحفظها للطلب الحالي عبر `c.set()`، مثل معرّف الطلب، ولا يعرّف إعدادات البيئة.
استبدل محتوى `src/index.ts` بما يلي:
```ts title="src/index.ts"
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { analyzeReading } from "./analyze";
const app = new Hono<{
Bindings: CloudflareBindings;
Variables: {
requestId: string;
};
}>();
app.use("*", async (c, next) => {
const requestId = crypto.randomUUID();
c.set("requestId", requestId);
c.header("X-Request-Id", requestId);
c.header("Cache-Control", "no-store");
await next();
console.log({
event: "reading_api_response",
requestId,
status: c.res.status,
});
});
app.get("/health", (c) => {
return c.json({ status: "ok", service: c.env.SERVICE_NAME });
});
app.post(
"/api/reading-time",
bodyLimit({
maxSize: 64 * 1024,
onError: (c) =>
c.json({ error: "Keep the request body within 64 KiB." }, 413),
}),
async (c) => {
const mediaType = c.req
.header("Content-Type")
?.split(";")[0]
?.trim()
.toLowerCase();
if (mediaType !== "application/json") {
return c.json(
{ error: "Use Content-Type: application/json." },
415,
);
}
let input: unknown;
try {
input = await c.req.json();
} catch (error) {
if (error instanceof SyntaxError) {
return c.json({ error: "Send valid JSON." }, 400);
}
throw error;
}
const defaultWpm = c.env.DEFAULT_WPM;
if (
!Number.isInteger(defaultWpm) ||
defaultWpm < 80 ||
defaultWpm > 600
) {
throw new Error("Invalid DEFAULT_WPM configuration.");
}
const result = analyzeReading(input, defaultWpm);
if (!result.ok) {
return c.json({ error: result.error }, 400);
}
return c.json(result.value);
},
);
app.all("/api/reading-time", (c) => {
c.header("Allow", "POST");
return c.json({ error: "Use POST." }, 405);
});
app.notFound((c) => c.json({ error: "Not found." }, 404));
app.onError((error, c) => {
console.error({
event: "reading_api_error",
requestId: c.get("requestId"),
name: error.name,
});
return c.json({ error: "Internal server error." }, 500);
});
export default app;
```
تتكون الشيفرة من ثلاثة أجزاء:
1. **إعداد الطلب وتسجيل نتيجته:** تنشئ الدالة الوسيطة معرّفا جديدا للطلب وتضبط `no-store`، ثم تسجل حالة الاستجابة بعد `await next()`. يبقى النص المرسل خارج السجل.
2. **معالجة المسارات:** يتيح `GET /health` التأكد من أن التطبيق يستجيب، ويستقبل `POST /api/reading-time` النص لتحليله.
3. **معالجة الأخطاء:** نعيد استجابة واضحة للمسارات المجهولة وطرق HTTP غير المدعومة والاستثناءات غير المتوقعة.
تمنع [الدالة الوسيطة `bodyLimit`](https://hono.dev/docs/middleware/builtin/body-limit) تجاوز حجم جسم الطلب 64 كيبيبايت، أي 65,536 بايت، قبل تحليل JSON. يشمل الحجم النص وصيغة JSON المحيطة به. تعتمد الدالة على ترويسة `Content-Length` عند وجودها، وتفحص تدفق البيانات عند غيابها. إذا تجاوز الطلب الحد، تعيد `413` قبل الوصول إلى بقية الفحوص. وهذا حد مستقل عن طول النص الذي فحصناه في دالة الحساب.
بعد فحص الحجم، نشترط نوع المحتوى `application/json` وإلا نعيد `415`. وإذا كانت صيغة JSON أو قيم الحقول غير صالحة، نعيد `400`. ولأي طريقة HTTP أخرى على مسار التحليل، تعيد `app.all()` الحالة `405` مع `Allow: POST`. المسارات المجهولة تعيد `404`. ويستجيب Hono لطلب `HEAD` على `/health` دون محتوى، بينما يظل مسار التحليل مخصصا لـ POST.
إذا وقع استثناء غير متوقع داخل التطبيق، تعيد `app.onError()` الحالة `500` برسالة عامة، وتسجل اسم الخطأ ومعرّف الطلب دون النص المرسل. لكن بعض أخطاء المنصة، مثل استنفاد زمن المعالجة، قد تقع خارج نطاق هذه الدالة. سنناقش حدود التشغيل بعد النشر.
## اختبار الواجهة محليا
شغّل التطبيق على جهازك:
```bash
npx wrangler dev --local
```
يشغّل Wrangler الشيفرة على جهازك باستخدام `workerd`، بيئة تشغيل Workers. يمنع `--local` استخدام الموارد البعيدة عبر إعدادات الربط، لكنه لا يمنع الشيفرة من إرسال طلبات `fetch()` إلى خدمات حقيقية. مثالنا لا يرسل مثل هذه الطلبات. يوضح [دليل التطوير المحلي](https://developers.cloudflare.com/workers/local-development/) هذا الفرق.
افتح نافذة طرفية أخرى وأرسل نصا:
```bash
curl -i 'http://localhost:8787/api/reading-time' \
-H 'Content-Type: application/json' \
--data '{"text":"Small APIs can be useful.","language":"en"}'
```
ينبغي أن تحصل على الحالة `200`، وترويستي `Cache-Control: no-store` و`X-Request-Id`، والنتيجة التالية:
```json title="الاستجابة"
{
"language": "en",
"words": 5,
"wordsPerMinute": 200,
"seconds": 2,
"minutes": 1
}
```
لتجربة العربية، أرسل نصا عربيا وغيّر `language` إلى `ar`. ويمكنك إضافة `"wordsPerMinute": 150` لتغيير سرعة القراءة. بعد نجاح الطلب، جرّب الحالات التي ينبغي أن ترفضها الواجهة:
```bash
# Health check: 200
curl -i 'http://localhost:8787/health'
# Empty text: 400
curl -i 'http://localhost:8787/api/reading-time' \
-H 'Content-Type: application/json' \
--data '{"text":"","language":"en"}'
# Invalid JSON: 400
curl -i 'http://localhost:8787/api/reading-time' \
-H 'Content-Type: application/json' \
--data '{'
# Wrong content type: 415
curl -i 'http://localhost:8787/api/reading-time' \
--data 'hello'
# Wrong method: 405, with Allow: POST
curl -i 'http://localhost:8787/api/reading-time'
# Unknown route: 404
curl -i 'http://localhost:8787/missing'
```
إذا أردت تجربة مقال كامل، فاحفظ محتوى الطلب بصيغة JSON في `request.json`، واستخدم `--data-binary @request.json` مع ترويسة نوع المحتوى نفسها. بهذا ترسل نص UTF-8 كما هو، وتتجنب مشكلات علامات الاقتباس في الطرفية. اختبر أيضا لغة غير مدعومة، ونصا لا يحتوي إلا على علامات ترقيم، وسرعة بقيمة كسرية أو خارج النطاق، وجسم طلب يتجاوز 64 كيبيبايت.
المثال متاح دون مصادقة. تطلب `no-store` عدم تخزين الاستجابة مؤقتا، لكنها لا تحدد من يحق له استدعاء الواجهة. وإذا استدعيتها من واجهة أمامية على أصل مختلف، فستحتاج إلى إعداد CORS للسماح لها بقراءة الاستجابة. تنظم CORS هذا الوصول داخل المتصفح، ولا تتحقق من هوية المتصل.
## نشر التطبيق
**متى يصبح التطبيق متاحا للناس؟**
تعمل في الخطوات الثلاث الأولى على جهازك. عند الخطوة الرابعة يصبح التطبيق متاحا عبر عنوان عام.
1. **01 · كتابة الشيفرة — src/index.ts + wrangler.jsonc**: يحتوي المشروع على دالة معالجة الطلبات وإعدادات تشغيلها.
2. **02 · التشغيل المحلي — wrangler dev --local**: جرّب إرسال طلبات HTTP إلى التطبيق على جهازك.
3. **03 · فحص حزمة النشر — wrangler deploy --dry-run**: تأكد من إمكانية بناء الحزمة دون نشر التطبيق.
4. **04 · النشر — wrangler deploy**: انشر التطبيق، ثم جرّب عنوانه الذي يظهر في الطرفية.
يتحقق dry-run من بناء الحزمة. وللتأكد من التوجيه والإعدادات بعد النشر، أرسل طلبا إلى العنوان المنشور.
*يبقى التطبيق المنشور كما هو أثناء العمل المحلي. لا تصل إليه الشيفرة الجديدة إلا عند تنفيذ أمر النشر.*
بعد تجربة الطلبات، تحقق من أنواع TypeScript وابن حزمة التطبيق للتأكد من جاهزيتها للنشر:
```bash
npx tsc --noEmit
npx wrangler deploy --dry-run
```
يبني الأمر `deploy --dry-run` الحزمة دون نشرها. لكنه لا يتحقق من صلاحيات بيئة الإنتاج أو إعدادات النطاقات أو الخدمات البعيدة التي قد تضيفها لاحقا.
لنشر المثال، سجّل الدخول ثم نفّذ أمر النشر:
```bash
npx wrangler login
npx wrangler deploy
```
يعرض Wrangler عنوان التطبيق بعد النشر، وغالبا يكون بالشكل `https://reading-api..workers.dev`. استخدم العنوان الذي ظهر لك في الطرفية: اختبر `/health` أولا، ثم أعد إرسال أمثلة POST إلى `/api/reading-time` على العنوان الجديد. يمكنك استخدام هذا العنوان مباشرة دون شراء نطاق.
تؤكد هذه الخطوة أن الطلب يصل إلى التطبيق المنشور بالحساب والإعدادات المقصودة. نجاح التجربة المحلية وحده لا يتحقق من ذلك.
### ربط نطاقك الخاص
في مثالنا، ينشئ Worker الاستجابة النهائية بنفسه، فيؤدي دور خادم الأصل. يمكنك ربطه **بنطاق مخصص (Custom Domain)** ليستقبل الطلبات الموجهة إلى اسم مضيف مثل `reading.example.com`. إذا كان نطاقك مفعّلا على Cloudflare، فأضف `routes` إلى المستوى الأعلى من `wrangler.jsonc`، واستبدل الاسم باسم مضيف تملكه:
```jsonc title="wrangler.jsonc · إضافة إلى الإعدادات الحالية"
{
"routes": [
{
"pattern": "reading.example.com",
"custom_domain": true
}
]
}
```
أعد النشر بعد تعديل الإعدادات. تتولى Cloudflare إدارة سجل DNS وشهادة الاتصال المشفر [للنطاق المخصص](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/). اختر اسم مضيف غير مستخدم؛ فقد يتعارض سجل CNAME موجود مع هذا الإعداد. ويظل اختيار المسار داخل التطبيق مسؤولية Hono، فيصبح عنوان واجهتنا `https://reading.example.com/api/reading-time`.
أما **Route** فتستخدمه عندما يكون لديك خادم أصل بالفعل وتريد تشغيل Worker أمامه، كأن يفحص الطلب قبل تمريره إلى الخادم. يطابق Route نمطا في العنوان، ويتطلب سجل DNS مناسبا مع تفعيل وكيل Cloudflare. يشرح [دليل التوجيه](https://developers.cloudflare.com/workers/configuration/routing/routes/) هذا الاستخدام. في مثالنا، يكفي النطاق المخصص لأن Worker ينتج الاستجابة بنفسه.
## الإعدادات وربط الخدمات عبر env
قرأنا اسم الخدمة من `c.env.SERVICE_NAME` وسرعة القراءة الافتراضية من `c.env.DEFAULT_WPM`. ويمكن أن يتيح `env` أيضا قيما سرية أو وصولا إلى موارد مثل قواعد البيانات وحاويات الملفات:
**ما الذي يتيحه env لشيفرتك؟**
المثال الأول قيمة إعداد استخدمناها في الواجهة. أما البقية فتوضح ما قد تضيفه لاحقا.
1. **c.env.SERVICE\_NAME — قيمة إعداد**: اسم الخدمة كما حددناه في vars: reading-api. لا يحتاج إلى إخفاء.
2. **c.env.PROVIDER\_API\_KEY — قيمة سرية**: بيانات اعتماد تستخدمها الشيفرة عند الاتصال بخدمة خارجية.
3. **c.env.DB — ربط بقاعدة بيانات**: وصول إلى قاعدة D1 محددة في الإعدادات، مع صلاحية استخدامها.
4. **c.env.UPLOADS — ربط بحاوية ملفات**: وصول إلى حاوية R2 محددة. تبقى الملفات مخزنة في R2.
يتيح الربط الوصول إلى المورد؛ وتبقى قاعدة البيانات والملفات في خدمات التخزين، خارج ذاكرة التطبيق.
*قد تجد في env قيمة تقرؤها مباشرة، أو واجهة تتعامل عبرها مع مورد ربطته بالتطبيق، مثل قاعدة بيانات.*
نسمي هذا [ربطا (binding)](https://developers.cloudflare.com/workers/runtime-apis/bindings/): تحدد المورد في الإعدادات، فتتيح Workers للشيفرة التعامل معه. مثلا، إذا ربطت قاعدة D1 باسم `DB`، أمكنك الاستعلام عنها عبر `c.env.DB` دون تضمين رمز API لحساب Cloudflare في الشيفرة. أضف إعداد الربط ثم أعد توليد الأنواع.
لا تحتاج أداة تقدير القراءة إلى حفظ النصوص. لكن إذا طوّرتها إلى محرر مقالات، فاختر التخزين بحسب البيانات وطريقة استخدامها:
- **D1** للسجلات التي تريد الاستعلام عنها باستخدام SQL، مثل المقالات المحفوظة.
- **KV** للقيم التي تقرؤها بمفاتيحها، عندما يكون التأخر في ظهور التحديثات مقبولا.
- **R2** للملفات، مثل المستندات المصدرة.
- **Durable Objects** لتنسيق العمل على كائن واحد، كأن يعدّل محرران المستند نفسه.
لكل خيار سلوكه وحدوده. حدد ما يحتاجه التطبيق قبل الاختيار؛ حفظ قيمة بين الطلبات ليس المعيار الوحيد. تفيدك [مقارنة خيارات التخزين](https://developers.cloudflare.com/workers/platform/storage-options/) هنا، وسنفصل هذه الخيارات في مقالات لاحقة من السلسلة.
### حفظ بيانات الاعتماد بأمان
إذا احتجت لاحقا إلى بيانات اعتماد لخدمة خارجية، فاحفظها كقيمة سرية:
```bash
npx wrangler secret put PROVIDER_API_KEY
```
سيطلب Wrangler إدخال القيمة، وتقرأها الشيفرة بعد ذلك عبر `c.env.PROVIDER_API_KEY`. أثناء التطوير المحلي، ضعها في `.dev.vars` وأضف النمطين `.dev.vars*` و`.env*` إلى `.gitignore`.
لا يرفع Wrangler القيم المحلية تلقائيا إلى بيئة الإنتاج؛ أضفها هناك بأمر `secret put`. يوضح [دليل القيم السرية](https://developers.cloudflare.com/workers/configuration/secrets/) كيفية إعدادها لكل بيئة.
لا نحتاج إلى هذه الخطوة في مثالنا، لأن الأداة لا تتصل بخدمة خارجية.
### فصل البيئة التجريبية عن الإنتاج
قبل تجربة تغييرات على تطبيق منشور، قد تحتاج إلى نسخة تجريبية مستقلة عنه. تتيح [بيئات Wrangler](https://developers.cloudflare.com/workers/wrangler/environments/) نشر المشروع نفسه كتطبيقات Workers منفصلة. أضف `env` إلى الإعدادات الحالية:
```jsonc title="wrangler.jsonc · إضافة إلى الإعدادات الحالية"
{
"env": {
"staging": {
"routes": [],
"vars": {
"SERVICE_NAME": "reading-api-staging",
"DEFAULT_WPM": 200
}
}
}
}
```
استخدم `--env staging` عند تشغيل النسخة التجريبية أو نشرها:
```bash
npx wrangler dev --local --env staging
npx wrangler deploy --env staging
```
ينشئ أمر النشر هنا تطبيقا باسم `reading-api-staging`. تمنع قائمة `routes` الفارغة استخدام نطاق الإنتاج الذي أضفناه سابقا؛ اختبر النسخة التجريبية على عنوان `workers.dev` الخاص بها. وتبقى إعدادات المستوى الأعلى خاصة بالتطبيق الأصلي `reading-api`. لذلك حدد البيئة المقصودة عند تنفيذ أوامر تغيّر التطبيق المنشور.
لا ترث البيئة التجريبية متغيرات المستوى الأعلى أو إعدادات ربط الموارد؛ عرّفها لكل بيئة على حدة. أضف القيم السرية لكل بيئة أيضا، باستخدام `--env staging` عند الحاجة. وانتبه إلى أن فصل التطبيقين لا يفصل بياناتهما إذا ربطتهما بقاعدة البيانات نفسها.
**قاعدة بيانات مستقلة لكل بيئة**
إذا أضفت D1 لاحقا، فخصص قاعدة بيانات لكل بيئة. يمكن للتطبيقين استخدام اسم الربط نفسه: c.env.DB.
1. **البيئة التجريبية — reading-api-staging**: يصل c.env.DB إلى قاعدة بيانات للاختبار: reading-api-staging-db.
2. **الإنتاج — reading-api**: يصل c.env.DB إلى قاعدة بيانات الإنتاج: reading-api-production-db.
هذه أسماء توضيحية لقواعد قد نضيفها لاحقا. إذا ربطت التطبيقين بالقاعدة نفسها، فسيتعاملان مع البيانات نفسها.
*استخدام اسم الربط نفسه في البيئتين لا يعني استخدام قاعدة البيانات نفسها؛ تحدد الإعدادات المورد المقصود في كل بيئة.*
## زمن المعالجة ومدة انتظار الاستجابة
بعد تشغيل التطبيق، كيف تقيس الوقت الذي يستهلكه؟ تخيل طلبا تمر معالجته بثلاث خطوات: التحقق من المدخلات، وانتظار قاعدة بيانات، ثم إعداد الاستجابة. لنفترض أن التحقق يستهلك 3 مللي ثانية من عمل المعالج، والانتظار 200 مللي ثانية، وإعداد الاستجابة 2 مللي ثانية.
استغرقت المعالجة نحو 205 مللي ثانية داخل الدالة، لكن **زمن المعالجة الفعلي على المعالج (CPU time) كان 5 مللي ثانية فقط**. هذه أرقام توضيحية لفهم الفرق، وليست قياسا لأداء واجهتنا.
**طلب واحد، وقياسان للوقت**
غيّر مدة انتظار البيانات، ولاحظ أن زمن المعالجة يبقى ثابتا.
1. **التحقق — 3 مللي ثانية معالجة**: تنفيذ فحوص المدخلات.
2. **انتظار البيانات — 200 مللي ثانية انتظار**: يزيد انتظار الشبكة مدة الطلب، من دون أن يزيد زمن معالجة Worker.
3. **التنسيق — 2 مللي ثانية معالجة**: إعداد الاستجابة.
عند انتظار 200 مللي ثانية: زمن المعالجة 5 مللي ثانية، والوقت داخل دالة المعالجة نحو 205 مللي ثانية. هذه أرقام توضيحية وليست نتائج قياس، ولا تشمل بقية وقت الاتصال عبر الشبكة.
*قد ينتظر المستخدم طويلا رغم أن الشيفرة لا تستهلك إلا زمنا قصيرا من عمل المعالج. قِس زمن الاستجابة أيضا.*
نحتاج إلى هذا الفرق لفهم حدود الخطة وتكلفتها. بحسب [حدود Workers](https://developers.cloudflare.com/workers/platform/limits/) بتاريخ 21 أيلول 2026، تنطبق الحدود التالية على معالجة طلبات HTTP العادية:
| الحد | Workers Free | Workers Paid |
| --- | --- | --- |
| الطلبات الواردة | 100,000 يوميا | الفوترة بحسب الاستخدام |
| زمن المعالجة لكل طلب | 10 مللي ثانية | 30 ثانية افتراضيا، ويمكن رفعه إلى 5 دقائق |
| الذاكرة لكل بيئة معزولة | 128 ميغابايت | 128 ميغابايت |
تتشارك تطبيقات الحساب حصة الخطة المجانية اليومية، وتتجدد عند منتصف الليل بتوقيت UTC. لا يحتسب انتظار الشبكة ضمن زمن المعالجة، لكن ذلك لا يضمن استمرار الطلب إلى ما لا نهاية: إذا قطع العميل الاتصال، فقد تُلغى الأعمال التي لم تنته.
كذلك تتشارك الطلبات داخل البيئة المعزولة ذاكرتها. إذا تعاملت مع محتوى كبير، فاستخدم [البث المتدفق (streaming)](https://developers.cloudflare.com/workers/runtime-apis/streams/) لتمريره تدريجيا بدلا من تحميله كله في الذاكرة. أما واجهتنا فتعيد كائن JSON صغيرا، وتناسبها `c.json()` في Hono.
### ماذا لو كانت قاعدة البيانات بعيدة؟
تشغّل Cloudflare تطبيق Worker افتراضيا قرب نقطة دخول الطلب إلى شبكتها. يناسب ذلك مثالنا، لأن كل ما نحتاجه موجود في الطلب نفسه. أما إذا كان التطبيق يتصل مرارا بقاعدة بيانات بعيدة، فقد يقضي معظم وقته في انتظارها.
تتيح إعدادات [موضع التنفيذ (Placement)](https://developers.cloudflare.com/workers/configuration/placement/) تشغيل التطبيق أقرب إلى خدماته الخلفية إذا كان ذلك يقلل زمن الاستجابة الإجمالي. قِس مدة الطلب والاتصالات الخارجية قبل تغيير موضع التنفيذ؛ فالقرب من المستخدم لا يكفي وحده.
### هل يمكن إكمال مهمة بعد إرسال الاستجابة؟
إذا كانت الاستجابة تعتمد على نتيجة عملية غير متزامنة، فانتظرها باستخدام `await`. أما الأعمال القصيرة التي لا تتوقف عليها الاستجابة، فيمكن منحها وقتا إضافيا عبر `ctx.waitUntil()`، أو `c.executionCtx.waitUntil()` في Hono.
تصل [المهلة الموثقة](https://developers.cloudflare.com/workers/runtime-apis/context/) لطلبات HTTP إلى 30 ثانية بعد إرسال الاستجابة أو انقطاع اتصال العميل. تتشارك جميع مهام `waitUntil()` التابعة للطلب نفسه هذه المهلة. وإذا بدأت عملية تعيد `Promise` دون انتظارها أو تمريرها إلى `waitUntil()`، فقد تتوقف قبل أن تكتمل.
للمهام التي تحتاج إلى تسليم موثوق وإعادة المحاولة عند الفشل، استخدم Queue. وللعمليات التي تتكون من خطوات وفترات انتظار وتحتاج إلى حفظ تقدمها، استخدم [Workflow](https://developers.cloudflare.com/workflows/). وفي كل الأحوال، لا ترسل «تم الحفظ» قبل اكتمال الكتابة في قاعدة البيانات؛ نجاحها لاحقا أثناء التجربة المحلية لا يضمن أن يحدث ذلك في الإنتاج.
## كم تبلغ التكلفة؟
ابدأ بالخطة المجانية لتجربة الواجهة، ثم قِس استهلاك المعالج وعدد الطلبات لتعرف متى تحتاج إلى خطة مدفوعة.
وقت كتابة المقال، يبدأ الاشتراك في [خطة Workers Standard](https://developers.cloudflare.com/workers/platform/pricing/) من **5 دولارات أمريكية للحساب شهريا**. يشمل ذلك 10 ملايين طلب و30 مليون مللي ثانية من زمن المعالجة. وتبلغ تكلفة الاستخدام الزائد 0.30 دولار لكل مليون طلب، و0.02 دولار لكل مليون مللي ثانية من المعالجة.
**كيف نحسب تكلفة 12 مليون طلب؟**
عند افتراض 4 مللي ثانية من المعالجة لكل طلب، نستهلك 48 مليون مللي ثانية. نضيف إلى الاشتراك الأساسي تكلفة ما يتجاوز الحصة المشمولة.
1. **الاشتراك الأساسي — $5.00**: يشمل 10 ملايين طلب و30 مليون مللي ثانية من المعالجة.
2. **الطلبات الإضافية — $0.60**: مليونا طلب فوق الحصة المشمولة، بسعر 0.30 دولار لكل مليون.
3. **المعالجة الإضافية — $0.36**: 18 مليون مللي ثانية إضافية، بسعر 0.02 دولار لكل مليون.
إجمالي تكلفة الحوسبة: 5.96 دولارات. نفترض توفر الحصة المشمولة كاملة، ولا نحسب الضرائب أو السجلات أو التخزين أو الخدمات الأخرى.
*يمثل الجزء الملون الحصة المشمولة بالاشتراك، والجزء ذو الخطوط المائلة الاستخدام الزائد. يعتمد الحساب على أسعار 21 أيلول 2026 المذكورة أعلاه.*
يفترض المثال أن الحصة المشمولة بالاشتراك متاحة كاملة لهذا التطبيق، وأن التطبيقات الأخرى في الحساب لم تستهلك منها شيئا. ولا يشمل الضرائب أو السجلات أو التخزين أو الخدمات الأخرى. أما متوسط 4 مللي ثانية لكل طلب فافتراض للحساب، وليس قياسا لأداء المثال.
الاشتراك الأساسي هو بداية الفاتورة، وليس سقفا لها. راقب الاستخدام والسجلات مع زيادة عدد الطلبات؛ فالاستجابة الصغيرة قد تُطلب ملايين المرات.
## تتبع الطلب في السجلات
أثناء تشغيل `wrangler dev`، تظهر سجلات المثال في الطرفية. وبعد النشر، يمكنك متابعة السجلات مباشرة بالأمر:
```bash
npx wrangler tail
```
أرسل طلبا، وقارن قيمة ترويسة الاستجابة `X-Request-Id` مع `requestId` في سجل `reading_api_response`. ولمتابعة البيئة التجريبية، استخدم `npx wrangler tail --env staging`.
تجد السجلات المحفوظة في صفحة [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/) بلوحة التحكم، بعد تفعيل `observability`. عندما تكون `head_sampling_rate` مساوية لـ `1`، تُختار جميع الطلبات للتسجيل؛ وعند `0.1` تُختار نحو 10% منها. يقلل أخذ العينات حجم السجلات، لكنه يعني أنك قد لا تجد سجلا لطلب محدد.
للسجلات حدود استخدام ومدة احتفاظ وتسعير خاص بها. ويكتب مثالنا حدثا في السجل من داخل الشيفرة، إضافة إلى حدث الاستدعاء الذي تسجله المنصة. لذلك قد ينتج عن الطلب الواحد أكثر من حدث.
إذا واجهت مشكلة، فابدأ بما يظهر لك في الاستجابة أو السجل:
| ما الذي تراه؟ | ما الذي تفحصه أولا؟ |
| --- | --- |
| `400` مع رسالة JSON من تطبيقنا | صيغة JSON والنص واللغة وسرعة القراءة |
| `404` مع رسالة JSON من تطبيقنا | المسار؛ `/health` أو `/api/reading-time` |
| `413` أو `415` | حجم جسم الطلب أو ترويسة Content-Type |
| لا يوجد سجل تطبيق مطابق | العنوان والتطبيق المستهدف والبيئة ونسبة أخذ العينات |
| قيمة ربط تساوي `undefined` | اسم الربط وإعدادات البيئة المختارة |
| الخطأ `1102` لتجاوز الموارد | استهلاك المعالج والذاكرة في الاستدعاء الذي فشل |
| زمن معالجة منخفض واستجابة بطيئة | اتصالات الشبكة وتأخر الخدمات الخلفية |
عند حدوث استثناء داخل التطبيق، ابحث عن قيمة `X-Request-Id` في سجل `reading_api_error`. ستجد اسم الخطأ، بينما يتلقى العميل رسالة عامة مع الحالة `500`. مثلا، القيمة غير الصحيحة لـ `DEFAULT_WPM` خطأ في إعدادات التطبيق؛ لذلك نعيد `500` بدلا من `400` التي تدل على مشكلة في بيانات العميل. وإذا لم تصل استجابة من التطبيق أصلا، فافحص أخطاء التنفيذ واستهلاك الموارد في المنصة.
## العودة إلى إصدار سابق
عند نشر تغيير، من المفيد أن تعرف كيف ترجع عنه. يسجّل إصدار Worker الشيفرة والإعدادات، وتحدد عملية النشر أي إصدار يستقبل الطلبات. اعرض الإصدارات الأخيرة بالأمر:
```bash
npx wrangler versions list
```
إذا تعطلت الواجهة بعد نشر تغيير، فاختر إصدارا سبق نشره وتأكدت من عمله، ثم [ارجع إليه](https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/):
```bash
npx wrangler rollback
```
استبدل `` بالمعرّف الفعلي، وأضف `--env staging` إذا كانت البيئة التجريبية هي المقصودة. أعد اختبارات HTTP على العنوان المنشور بعد الرجوع.
العودة إلى إصدار سابق تعيد الشيفرة، لكنها لا تتراجع عن عمليات الكتابة في قاعدة البيانات ولا تستعيد الموارد المحذوفة. وقد يتعذر الرجوع بعد حذف مورد مرتبط بالتطبيق أو إجراء بعض تغييرات Durable Objects. لذلك، عندما تضيف بيانات دائمة، ضع خطة مستقلة لاستعادتها وتأكد من توافق بنيتها مع الشيفرة التي قد ترجع إليها.
## ماذا تبني بعد ذلك؟
أصبح لديك تطبيق يعمل على Workers، ويمكنك تتبع ما يحدث فيه من وصول الطلب إلى ظهور نتيجته في السجل. فصلنا حساب المدة عن معالجة HTTP، واستخدمنا Hono لتنظيم المسارات، ثم جرّبنا الواجهة وتناولنا نشرها ومتابعة تشغيلها.
لتوسيع المثال، جرّب إتاحة تحليل عدة مسودات في طلب واحد. حدد عدد المسودات وحجم الطلب الإجمالي، وقرر ما يحدث إذا كانت إحداها غير صالحة: هل ترفض الدفعة كلها أم تعيد نتيجة مستقلة لكل مسودة؟ طبّق القرار واختبره.
في الجزء المقبل، سنضيف واجهة أمامية ونناقش خيارات استضافة المواقع على Workers، وما يقدمه Pages في هذا الجانب.
إذا كان هذا الدليل سيساعد أحد زملائك في بناء أول واجهة API على Workers، فشاركه معه. وما الجزء الذي احتجت وقتا أطول لفهمه في تجربتك: بيئة التشغيل، أم ربط الخدمات، أم النشر؟ [راسلني بتجربتك](/ar/contact)، أو شارك المقال مع ملاحظاتك على X أو LinkedIn.
---
# Cloudflare DNS: from buying a domain to a working website
- URL: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-dns
- Markdown: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-dns.md
- Translation: https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-dns
- Author: Omar Albeik
- Language: en
- Type: tutorial
- Date: 17 September 2026
- Topics: infrastructure
Moving DNS to Cloudflare lets you keep your website at its current host.
Moving the website itself is a separate choice. Understanding that
distinction makes the rest of the setup easier to follow.
This site runs on Workers. We'll use its public DNS records to follow a
request from the domain name to the application, then work through domain
registration, website and email setup, and troubleshooting. You don't need
a Cloudflare account to try the lookup commands.
The guide uses Cloudflare's standard setup for a public website, with a
short section on alternative DNS arrangements near the end.
If you're returning with a particular job in mind:
- [Choose a registrar](#is-cloudflare-a-good-place-to-buy-the-domain).
- [Set up an existing domain](#move-dns-to-cloudflare).
- [Read and add records](#read-the-record-before-you-edit-it).
- [Connect the website](#connect-the-name-to-the-application) or [email](#keep-email-working-too).
- [Understand caching](#why-a-dns-change-takes-time) or [diagnose a problem](#check-dns-then-check-http).
## Who answers for your domain?
The registrar is where you register and renew a domain. Its nameserver
settings tell the rest of the DNS system which servers are responsible for
the domain's records. Those are its **authoritative nameservers**. The host
is where the website runs. These jobs can belong to different companies.
When your browser needs an address, a DNS resolver looks it up. That resolver
may already have a cached answer; otherwise it follows the DNS hierarchy to
find the authoritative servers. Cloudflare's
[DNS walkthrough](https://www.cloudflare.com/learning/dns/what-is-dns/)
explains that lookup in more detail.
For `www.example.com`, the root servers can refer the resolver to the
servers for `.com`. Those can point it to the nameservers for `example.com`,
which answer for `www`. The resolver does the searching; the browser doesn't
visit each nameserver itself. Cached answers can skip much of this work.
**How the resolver finds an answer**
An uncached lookup: the browser asks its resolver, which makes these queries.
1. **01 · Root — Root nameserver**: Refers the resolver to the nameservers for .com.
2. **02 · .com — TLD nameserver**: Refers it to the assigned nameservers for example.com.
3. **03 · Cloudflare — Authoritative nameserver**: Answers for the requested name. A CNAME may require more lookups.
4. **04 · Resolver — Answer returns to the browser**: The resolver caches the answer using its TTL. The web connection follows.
*A simplified, hypothetical lookup for a domain using Cloudflare DNS. Fetching the web page is a separate step, shown later.*
Cloudflare has two roles here that are easy to confuse. Its public resolver,
[1.1.1.1](https://developers.cloudflare.com/1.1.1.1/), looks up names for clients. Its authoritative DNS service
answers for domains managed on Cloudflare. Using 1.1.1.1 on your laptop
neither moves your domain to Cloudflare nor turns on the orange cloud.
The records you manage together for a domain form a **zone**. The zone's
root, or **apex**, is `example.com`; `www.example.com` is a subdomain. The
`/articles` part of a URL belongs to HTTP routing. DNS never chooses which
article to show.
Here is a small piece of this site's setup you can check from a terminal
with `dig` installed:
```bash
dig +short NS omaralbeik.com
```
When I checked on September 17, 2026, it returned:
```text
alan.ns.cloudflare.com.
demi.ns.cloudflare.com.
```
That tells us Cloudflare provides the authoritative DNS. It doesn't tell us
who registered the domain or where the application runs. A site on a rented
server could give the same kind of answer.
## Is Cloudflare a good place to buy the domain?
If you already want Cloudflare to manage DNS, its Registrar is a good
option to consider. You may keep the name for years, so renewal pricing
and everyday administration matter as much as the purchase itself.
[Cloudflare Registrar](https://developers.cloudflare.com/registrar/) charges
registry and ICANN costs without adding a markup, for both registration and
renewal. Compare the renewal price as well as the first-year offer when
shopping around. At-cost pricing doesn't mean a price frozen forever:
underlying registry charges can change, and it doesn't guarantee the lowest
promotional price at every moment.
There are practical benefits beyond price:
- Registration and DNS live in the same account, so there is less switching
between dashboards when you connect a service.
- DNSSEC activation is integrated with the registrar, avoiding the manual
transfer of DS values between providers.
- [Personal contact details are redacted](https://developers.cloudflare.com/registrar/account-options/whois-redaction/)
from public registration records where registry rules permit. This isn't
anonymity: Cloudflare still needs accurate registration details, and
some fields remain public.
**The tradeoff is nameserver choice.** A domain registered at Cloudflare
[must use Cloudflare's nameservers](https://developers.cloudflare.com/registrar/get-started/register-domain/).
You can host the website elsewhere, but you can't switch the domain to
another provider's nameservers while keeping Cloudflare as its registrar.
If that flexibility matters, register elsewhere and use Cloudflare for DNS.
Also check the [supported extensions](https://developers.cloudflare.com/registrar/top-level-domains/)
before committing to a name. Cloudflare Registrar currently doesn't support
internationalized domain names, including Arabic-script names or their
Punycode equivalents. That is a Registrar restriction, not a statement
that DNS itself is limited to English names.
### Buying a new domain
In **Domain Registration → Register Domains**, search for the name, check
the registration period and renewal terms, and enter accurate contact
information. Review the total before completing the purchase. Then complete
email verification and check auto-renewal and your payment method. The
[registration guide](https://developers.cloudflare.com/registrar/get-started/register-domain/)
explains the current flow; auto-renewal is enabled by default.
Your new domain uses Cloudflare nameservers already. You still need to
connect the website and email. Buying the name doesn't deploy an application
or create a mailbox.
### Bringing an existing registration
You can move DNS without transferring registration. If you do want to
[transfer registration to Cloudflare](https://developers.cloudflare.com/registrar/get-started/transfer-domain-to-cloudflare/),
first make the zone active on Cloudflare. Check transfer eligibility and
follow the instructions for your extension. For most generic TLDs, this
means unlocking the domain and obtaining an authorization code from its
current registrar. Recent registrations, transfers, or contact
changes may trigger transfer locks. The fee and any extra registration
period depend on the extension; don't assume every TLD follows `.com` rules.
**Two ways to arrive at Cloudflare DNS**
A new purchase avoids a DNS migration. An existing domain needs its records checked before delegation changes.
1. **A · Registrar — Buy a new domain at Cloudflare**: Choose the name and renewal terms, register, and verify email. Cloudflare nameservers are assigned.
2. **B · Existing domain — Keep an existing registration**: Copy records, handle existing DNSSEC, change nameservers at the registrar, and wait for activation.
3. **A + B — Connect and verify the services**: Set up the website, email, and DNSSEC. Transferring an existing registration remains a separate choice.
*Both paths lead to the same DNS tools. A registration transfer changes who manages renewal; a nameserver change determines who answers DNS queries.*
## What the orange cloud changes
For a site hosted elsewhere, Cloudflare's
[proxy setting](https://developers.cloudflare.com/dns/proxy-status/)
decides whether web traffic passes through its network. With **DNS only**,
the lookup exposes the hosting destination and the browser connects there.
With **Proxied**, the answer contains Cloudflare addresses, and the browser
connects to Cloudflare first. This is where its HTTP security and caching
features can act on the request.
**After DNS, where does the browser connect?**
- **DNS only** — Externally hosted site
1. Browser
2. Website server
- **Proxied** — Externally hosted site
1. Browser
2. Cloudflare
3. Website server
- **Worker + Custom Domain** — Application on Cloudflare
1. Browser
2. Cloudflare
3. Worker
DNS happens before these connections. In the third path, the Worker runs within Cloudflare.
*DNS finds an address before the web connection begins. A Worker can serve as the application itself, without a separate website server behind Cloudflare.*
The orange cloud doesn't mean every response is now cached. Cloudflare's
ordinary CDN [doesn't cache HTML or JSON by default](https://developers.cloudflare.com/cache/concepts/default-cache-behavior/).
Workers and static assets have their own delivery behavior, which we'll get
to in the hosting installment.
Nor is that toggle a general-purpose proxy for every protocol. Keep mail
server records and third-party ownership-verification records DNS-only;
follow the service provider's instructions. Cloudflare documents the
[proxy's limits](https://developers.cloudflare.com/dns/proxy-status/limitations/)
separately from its DNS service. `A`, `AAAA`, and `CNAME` records can be
proxied when used for supported traffic; `MX` and `TXT` cannot be proxied.
For a proxied external origin, the public answer hides the configured
origin address, but that alone doesn't make the origin inaccessible.
[Other DNS-only names](https://developers.cloudflare.com/dns/manage-dns-records/troubleshooting/exposed-ip-address/)
or historical records may reveal it. Protecting direct
access to the server is a separate hosting decision.
## Read the record before you edit it
The records you'll meet most often each answer a different question. This
is the short version of Cloudflare's
[record-type reference](https://developers.cloudflare.com/dns/manage-dns-records/reference/dns-record-types/):
| Record | What it supplies |
| --- | --- |
| `A` | An IPv4 address for a name |
| `AAAA` | An IPv6 address for a name |
| `CNAME` | Another hostname to resolve |
| `MX` | The mail servers that receive email for the domain |
| `TXT` | Text used for purposes such as ownership checks and email authentication |
| `CAA` | Which certificate authorities may issue certificates for the name |
| `SRV` | A service location, including its host and port |
| `NS` | The nameservers responsible for a zone or delegated subdomain |
| `PTR` | A reverse lookup from IP address to name, usually managed by the IP provider |
To add one, open your domain's **DNS → Records → Add record**. Choose the
type, name, and content, then the proxy status and TTL where applicable.
The [record editor](https://developers.cloudflare.com/dns/manage-dns-records/how-to/create-dns-records/)
also supports comments. Note which service requested the record so you can
identify it later.
**Reading the Add record form**
Illustrative external-server setup. 192.0.2.10 is reserved for documentation and does not host a real website.
1. **Type · A — The kind of answer**: Map a name to IPv4. Use AAAA for an IPv6 address.
2. **Name · @ — The name you are configuring**: Here, @ means example.com. Entering www means www.example.com.
3. **Content · 192.0.2.10 — The destination**: Replace this with the server address supplied by your host.
4. **Proxy · Proxied / TTL · Auto — Traffic path and cache lifetime**: Orange sends web traffic through Cloudflare. TTL governs the DNS answer's lifetime.
*An annotated example, not a screenshot of a live account. The fields describe a name, an answer, and how Cloudflare should handle it. Use your host's actual values.*
Suppose a host asks you to create a CNAME for `www.example.com`, pointing to
`project.host.example`. The value is that hostname, without `https://` or a
path. The host also needs to recognize `www.example.com` as a name it serves.
DNS alone doesn't configure the application at the other end.
It doesn't redirect the browser, either. A CNAME from `www` to the bare
domain leaves `www` in the address bar. To choose one public address and send
visitors there, configure an HTTP redirect on your host or at Cloudflare.
You may see `@` in the dashboard: it means the zone's root, such as
`example.com`. Cloudflare can also use
[CNAME flattening](https://developers.cloudflare.com/dns/cname-flattening/)
to return a target's IP addresses, including for a CNAME at that root.
Consequently, an address returned by `dig` doesn't necessarily reveal the
record type you entered in the dashboard.
For an ordinary hostname, don't add a CNAME alongside an A or AAAA record
with the same name. Cloudflare rejects these
[conflicting records](https://developers.cloudflare.com/dns/manage-dns-records/troubleshooting/records-with-same-name/).
An A and an AAAA can coexist: they answer different address-family queries.
Only add an origin AAAA record when that server serves the site over IPv6.
For DNS-only names, an old AAAA can send IPv6 visitors to the previous host
while your IPv4 test succeeds. For proxied names, Cloudflare can
[advertise its own IPv6 addresses](https://developers.cloudflare.com/network/ipv6-compatibility/)
even when your origin uses IPv4; you don't need an origin AAAA for that.
## Move DNS to Cloudflare
For a domain registered elsewhere, use Cloudflare's
[full setup](https://developers.cloudflare.com/dns/zone-setups/full-setup/setup/).
[DNS is available on the Free plan](https://developers.cloudflare.com/dns/);
domain registration and any paid products are separate costs.
Work through the move in this order:
1. Save a copy of the records at your current DNS provider.
2. Add the root domain to Cloudflare and compare the imported records with
that copy; the automatic scan can miss entries. Include the website,
mail, verification, and less-used names.
3. Handle existing DNSSEC before switching, as described below.
4. At the registrar, replace the old nameservers with the exact pair assigned
to this zone. Don't copy the pair from my site's example.
5. Keep the old DNS service and hosting available during the transition.
Check that Cloudflare marks the zone **Active**, then test the services.
Adding NS records inside the old DNS dashboard isn't a substitute for
changing the registrar's nameserver setting. The delegation at the parent
zone is what sends resolvers to the new provider.
If DNSSEC is already enabled, follow the
[DNSSEC migration procedure](https://developers.cloudflare.com/dns/dnssec/#migrate-to-cloudflare-with-dnssec-active)
before the switch. In the standard migration, remove the old DS record at
the registrar and allow its cached copies to expire before changing
nameservers. Keep the old zone signed while cached DS records remain valid.
After the switch, wait for the old nameserver records' TTL to expire before
enabling DNSSEC at Cloudflare and publishing its new DS record. This avoids
validating resolvers pairing one provider's keys with the other's answers.
The procedure leaves a temporary gap in DNSSEC protection; the linked guide
also covers migration with continuous signing for providers that support it.
### What DNSSEC actually protects
DNSSEC uses signatures and a chain of trust through the parent zone to let
validating resolvers check the origin and integrity of DNS answers. It
doesn't encrypt queries or replace HTTPS.
[DNS over HTTPS](https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/)
encrypts the connection between a client and its resolver.
For a new Cloudflare zone, open **DNS → Settings → DNSSEC** and follow the
activation instructions. The DS record links the parent zone to your DNS
signing key. With an external registrar, publish the DS values
Cloudflare supplies at that registrar. With Cloudflare Registrar, the
integration handles that part. Confirm the resulting status rather than
assuming the switch alone completed the chain.
If you later move DNS away, plan DNSSEC again. A DS record still pointing
to the old keys can break resolution even when every A and MX record has
been copied correctly.
## Connect the name to the application
For an external host, use the DNS values it supplies and confirm whether it
supports Cloudflare proxying. Don't copy another site's public IP address:
with a proxied site, that may simply be a Cloudflare address.
For example, a host might supply an IPv4 address for the root name and
ask for `www` to alias it. Add the A record for `@`, the CNAME for `www`,
and register both names in the hosting service. Choose a canonical hostname
and configure the redirect there, or use Cloudflare
[Redirect Rules](https://developers.cloudflare.com/rules/url-forwarding/).
A Cloudflare redirect requires the source hostname's traffic to reach its
proxy. Test both names over HTTPS; DNS, certificate coverage, and redirects
all need to agree.
For an application running on Workers, a
[Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/)
connects a hostname directly to the Worker. With an active Cloudflare zone
and an existing Worker, open the Worker's **Settings → Domains & Routes →
Add → Custom Domain**. Cloudflare creates the DNS record and certificate.
An existing CNAME at that hostname must be resolved before adding it; check
what it serves before replacing it.
A Custom Domain matches the hostname exactly. Attaching `example.com`
doesn't attach `www.example.com`; account for both if you want both to work.
This is different from a Worker Route, which can run code in front of an
existing origin. We'll use that distinction in the next installment.
For an external server behind the proxy, HTTPS also has two connections:
browser to Cloudflare, then Cloudflare to the server. Use
[Full (strict)](https://developers.cloudflare.com/ssl/origin-configuration/ssl-modes/full-strict/)
with an unexpired, hostname-matching certificate issued by a publicly
trusted authority or Cloudflare Origin CA. In DNS-only mode, the browser
connects to your host directly and needs a publicly trusted certificate;
[Cloudflare Origin CA certificates aren't trusted by browsers](https://developers.cloudflare.com/ssl/origin-configuration/origin-ca/#3-change-ssltls-mode).
Cloudflare's standard
[Universal SSL coverage](https://developers.cloudflare.com/ssl/edge-certificates/universal-ssl/limitations/)
on a full zone includes the apex and first-level subdomains. Don't assume
it also covers `api.staging.example.com`. A DNS record can resolve perfectly
while that deeper hostname needs additional certificate coverage.
## Keep email working too
Your website and email can use different providers. Keep the
[email records](https://developers.cloudflare.com/dns/manage-dns-records/how-to/email-records/)
supplied by your mail provider when you change DNS.
MX records identify the receiving mail servers; lower priority numbers are
preferred. If an MX points to `mail.example.com`, that name needs an address
record too, and that mail-server address should stay DNS-only. Cloudflare's
normal web proxy doesn't carry SMTP traffic.
Sending mail brings three more names into the dashboard:
- **SPF** uses a TXT record to authorize sending servers for the SMTP
envelope-sender domain, which can differ from the visible From address.
Your provider specifies whether to publish it at `@` or a subdomain.
- **DKIM** publishes the information receivers use to verify a message's
signature. Providers often supply TXT or CNAME records under
`selector._domainkey`.
- **DMARC**, published as TXT under `_dmarc`, requests handling and reports
for mail using your visible From domain. A
[DMARC pass](https://www.rfc-editor.org/rfc/rfc9989.html#section-4.1)
requires SPF or DKIM to pass with a domain aligned to that From domain;
one aligned pass is enough.
Use the provider's actual values. Don't copy a mail policy from an unrelated
site, and don't publish a separate SPF policy for each sending service:
[SPF permits one policy record per name](https://www.rfc-editor.org/rfc/rfc7208#section-3.2).
Combine authorized senders according to your providers' instructions. Work
out all legitimate sending services before enforcing a strict DMARC policy.
An ownership-check CNAME should usually remain DNS-only. Disable any
optional per-record flattening and the zone-wide “flatten all” setting.
Some services need to see the CNAME itself, not its target's IP address.
Cloudflare's
[verification troubleshooting guide](https://developers.cloudflare.com/dns/manage-dns-records/troubleshooting/cname-domain-verification/)
explains why an apparently correct record can fail that check.
Publishing these records doesn't create a mailbox. Cloudflare Email Routing
and application email are separate services; we'll cover those in the email
installment.
## Why a DNS change takes time
A DNS edit updates the authoritative answer. It doesn't push a notification
to every resolver, phone, and browser that has an older answer cached.
During this period, often called “propagation,” clients may use different
copies of the answer.
**Why an old answer can outlive your edit**
A simplified DNS-only example with an original one-hour TTL. Times are illustrative.
1. **12:00 · TTL 3600 — Resolver caches the old answer**: It may reuse that address for up to an hour.
2. **12:10 · TTL 300 — You change the address and lower TTL**: Authoritative servers now have the new value. The existing cache gets no push notification.
3. **13:00 — The original cache lifetime ends**: On its next needed lookup, the resolver asks again and gets the new value.
*Lowering TTL after an answer has been cached doesn't shorten that existing cache entry. In this example, a change made at 12:10 can coexist with the old answer until 13:00.*
For a planned DNS-only address change, lower its TTL in advance and allow
the previous TTL to pass before moving the service. Keep both destinations
working during the transition where possible. Cloudflare's proxied records
use [Auto TTL, currently 300 seconds](https://developers.cloudflare.com/dns/manage-dns-records/reference/ttl/),
which isn't an end-to-end promise that every client will see a change within
five minutes. Delegation and local caches have their own lifetimes.
Also distinguish DNS caching from caching a page. Purging Cloudflare's CDN
cache doesn't clear a resolver's DNS cache. If the hostname reaches the
right application but displays an old article, inspect HTTP caching and the
deployment before changing DNS.
## Check DNS, then check HTTP
Back to this website. Query its addresses:
```bash
dig +short A omaralbeik.com
dig +short AAAA omaralbeik.com
```
At the same check on September 17, the A query returned `188.114.96.0` and
`188.114.97.0`. Treat these as an observation, not configuration values to
copy. DNS shows where a client can connect; it won't identify my Worker or
show how the application handles `/en` and `/ar`.
To inspect the HTTP response, ask for its headers:
```bash
curl -I https://omaralbeik.com/en
```
A response with `server: cloudflare` and a `cf-ray` header gives you evidence
that Cloudflare handled the request. It doesn't establish a cache hit.
Read the status code too: a redirect is a valid HTTP response, but the page
you want is at the destination in its `location` header.
When a changed record seems stuck, compare a recursive resolver's answer
with an authoritative answer. For this site's nameservers at the time of
writing:
```bash
dig @1.1.1.1 omaralbeik.com A +noall +answer
dig @alan.ns.cloudflare.com omaralbeik.com A +noall +answer
```
For your own domain, substitute its name and one of its assigned
nameservers. The number before `IN A` is the answer's TTL in seconds.
Proxied responses may contain different Cloudflare addresses; unequal IPs
alone don't prove stale data. DNS won't expose a proxied origin change,
so check the configured destination in the dashboard and test HTTP too.
If `+short` prints nothing, repeat the query without it. An empty answer
isn't a diagnosis: the full response distinguishes an absent record from
errors such as `NXDOMAIN` or `SERVFAIL`. If DNS resolves but HTTPS fails,
move on to certificates, routing, and the application.
### Match the symptom to the next check
| What you see | Where to look next |
| --- | --- |
| Zone stays Pending | The registrar's assigned nameservers and existing DNSSEC delegation |
| `NXDOMAIN` | Spelling, the selected zone, and whether that name exists at the authoritative provider |
| `NOERROR` with no answer | Whether the queried record type exists; an empty AAAA answer need not mean the A record is broken |
| `SERVFAIL` | DNSSEC validation, delegation, and nameserver availability; it isn't proof of a DNSSEC fault by itself |
| Some visitors reach the old host | Cached answers and any A/AAAA records still pointing at the old destination |
| DNS works, HTTPS fails | Certificate coverage, proxy mode, origin TLS, and the host's domain configuration |
| Homepage works, email fails | MX destinations, mail-server address records, and authentication records |
| Ownership check fails | Exact record name, CNAME proxy/flattening settings, and any subdomain delegation |
These are starting points, not diagnoses. Keep the full command output
before changing settings so you can tell whether the next change helped.
You can also inspect the delegation chain with:
```bash
dig +trace omaralbeik.com
```
That follows referrals rather than relying on your usual recursive resolver.
It can fail on networks that block direct DNS queries; that failure alone
doesn't establish that the website is broken.
## Wildcards, delegation, and other setups
**Wildcards** such as `*.example.com` can supply answers for otherwise
unmatched subdomains. They don't replace the apex record, and an existing
name or delegation can stop wildcard matching. Cloudflare's
[wildcard examples](https://developers.cloudflare.com/dns/manage-dns-records/reference/wildcard-dns-records/)
cover the less obvious cases, including deeper labels. DNS wildcard matching
and certificate wildcard coverage are different rules; don't infer one
from the other.
**Subdomain delegation** gives another DNS provider responsibility for a
branch such as `team.example.com`. Add the provider's NS records for `team`
in the parent zone; manage that branch's records at the delegated provider.
This is different from simply creating an A record for a subdomain. Follow
[the delegation guide](https://developers.cloudflare.com/dns/manage-dns-records/how-to/subdomains-outside-cloudflare/)
if that branch also needs DNSSEC.
**Partial and secondary setups** serve organizations with existing DNS
requirements. A partial CNAME setup lets eligible Business or Enterprise
zones retain another authoritative provider while proxying selected names.
Enterprise zone transfers support primary or secondary DNS arrangements.
These are [alternative setups](https://developers.cloudflare.com/dns/zone-setups/),
not steps required to connect an ordinary website.
## Leave yourself a setup you can maintain
Before a substantial edit, export the zone from **DNS → Records → Import
and Export**. Cloudflare's
[zone-file export](https://developers.cloudflare.com/dns/manage-dns-records/how-to/import-and-export/)
includes record data and Cloudflare-specific tags. Keep a separate note of
settings outside DNS, such as redirects, TLS, and Worker domains; the zone
file isn't a backup of the whole account.
For automated updates, use a scoped
[API token](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/)
with only the DNS permissions and zone the job needs. A read-only inventory
shouldn't have permission to rewrite your domain. Store the token as a
secret, and make the same record changes through one maintained workflow
rather than competing dashboard edits and scripts.
Finally, check the things a visitor actually uses: the apex and `www`, their
HTTPS certificates, the preferred redirect, and email in both directions.
Confirm DNSSEC and renewal settings too.
Next we'll look inside the Worker that receives the request.
Know someone connecting their first domain? Share this guide with them. If
your setup behaves differently,
[send me the symptom and what you checked](/en/contact).
---
# دليل Cloudflare DNS: من شراء النطاق إلى تشغيل الموقع
- URL: https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-dns
- Markdown: https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-dns.md
- Translation: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-dns
- Author: Omar Albeik
- Language: ar
- Type: tutorial
- Date: 17 أيلول 2026
- Topics: infrastructure
يمكنك نقل إدارة DNS إلى Cloudflare وإبقاء الموقع على استضافته الحالية.
أما نقل الموقع نفسه فهو قرار مستقل. فهم هذا الفرق يسهّل بقية الإعداد.
يعمل هذا الموقع على Workers. سنستخدم سجلاته العامة لنتتبع الوصول من
اسم النطاق إلى التطبيق، ثم نتناول تسجيل النطاق وربط الموقع والبريد
وتشخيص المشكلات. يمكنك تجربة أوامر الفحص دون حساب على Cloudflare.
نعتمد الإعداد المعتاد لموقع على الإنترنت، مع قسم مختصر لطرق إعداد
DNS الأخرى في نهاية الدليل.
إذا عدت إلى المقال لإنجاز مهمة محددة، يمكنك الانتقال مباشرة إلى:
- [اختيار مسجّل النطاق](#لماذا-قد-تشتري-النطاق-من-cloudflare).
- [إعداد نطاق موجود](#انقل-إدارة-dns-إلى-cloudflare).
- [فهم السجلات وإضافتها](#افهم-السجل-قبل-تعديله).
- [ربط الموقع](#اربط-الاسم-بالتطبيق-الذي-سيستقبل-الطلبات) أو [ضبط البريد](#حافظ-على-عمل-البريد-أيضا).
- [فهم تأخر التغييرات](#لماذا-لا-يظهر-تعديل-dns-فورا) أو [تشخيص مشكلة](#افحص-dns-ثم-استجابة-الموقع).
## من يجيب عن الاستعلامات الخاصة بنطاقك؟
مسجّل النطاق هو الجهة التي تشتري منها النطاق وتجدّد اشتراكه لديها.
وفي إعداداته تحدّد خوادم الأسماء المسؤولة عن سجلات النطاق، وتسمّى
**خوادم الأسماء الموثوقة**، أو authoritative nameservers. أما الاستضافة
فهي المكان الذي يعمل فيه الموقع. وقد تتولى ثلاث شركات مختلفة هذه المهام.
عندما يحتاج المتصفح إلى عنوان الموقع، يستعين بخادم لحل أسماء النطاقات
يسمّى DNS resolver. قد يجد الإجابة محفوظة لديه، أو يبحث عنها عبر تسلسل
خوادم DNS حتى يصل إلى الخوادم المسؤولة عن النطاق. يشرح
[دليل Cloudflare لعمل DNS](https://www.cloudflare.com/learning/dns/what-is-dns/)
هذه الخطوات بالتفصيل.
في مثال `www.example.com`، يدلّ خادم الجذر على خوادم `.com`، وهذه
تدلّ على خوادم `example.com` التي تجيب عن الاسم `www`. خادم حل
الأسماء هو الذي يتابع البحث؛ المتصفح لا يسأل كل هذه الخوادم بنفسه.
وإذا وُجدت إجابة محفوظة، فقد يختصر البحث كثيرًا من هذه الخطوات.
**كيف يجد خادم حل الأسماء الإجابة؟**
مثال لاستعلام بلا إجابة مخزّنة: المتصفح يسأل خادم حل الأسماء، وهو يتولى الخطوات التالية.
1. **01 · Root — خادم الجذر**: يدلّ خادم حل الأسماء على خوادم نطاق .com.
2. **02 · .com — خادم النطاق الأعلى**: يدلّه على خوادم الأسماء المعيّنة لـexample.com.
3. **03 · Cloudflare — الخادم الموثوق للنطاق**: يجيب عن سجل الاسم المطلوب. وقد يستلزم CNAME استعلامات إضافية.
4. **04 · Resolver — الإجابة تعود إلى المتصفح**: يحفظ خادم حل الأسماء الإجابة وفق TTL. ثم يبدأ المتصفح اتصال الويب.
*مثال افتراضي مبسّط لنطاق يستخدم Cloudflare DNS. جلب الصفحة خطوة مستقلة نوضّحها في رسم لاحق.*
تؤدي Cloudflare دورين مختلفين هنا. خدمة [1.1.1.1](https://developers.cloudflare.com/1.1.1.1/) تحلّ الأسماء لمن
يستخدمها، أما خوادم DNS الموثوقة فتجيب عن النطاقات التي تدير Cloudflare
سجلاتها. ضبط جهازك ليستخدم 1.1.1.1 لا ينقل إدارة نطاقك إلى Cloudflare
ولا يفعّل السحابة البرتقالية.
تسمّى مجموعة السجلات التي تديرها للنطاق **منطقة DNS**، أو zone.
يمثّل `example.com` جذر هذه المنطقة، ويسمّى apex، بينما
`www.example.com` نطاق فرعي. أما `/articles` في عنوان الصفحة فهو
مسار يعالجه التطبيق عبر HTTP؛ لا يختار DNS المقال الذي سيظهر للقارئ.
لنجرّب ذلك على هذا الموقع. إذا كانت أداة `dig` مثبتة لديك، نفّذ:
```bash
dig +short NS omaralbeik.com
```
عند الفحص في 17 أيلول 2026، كانت النتيجة:
```text
alan.ns.cloudflare.com.
demi.ns.cloudflare.com.
```
نعرف من هذه الإجابة أن Cloudflare تدير DNS للنطاق. لكننا لا نعرف منها
الجهة التي سجّلتُ النطاق لديها، ولا مكان تشغيل التطبيق. فقد نجد إجابة
مشابهة لموقع يعمل على خادم مستأجر لدى شركة أخرى.
## لماذا قد تشتري النطاق من Cloudflare؟
إذا كنت تنوي استخدام Cloudflare لإدارة DNS، فمن المنطقي أن تنظر في
خدمة تسجيل النطاقات لديها أيضًا. ما يجعلها خيارًا جيدًا هو بساطة أمور
ستعود إليها سنوات: التجديد وإدارة النطاق وربطه بخدماتك.
تتقاضى [Cloudflare Registrar](https://developers.cloudflare.com/registrar/)
رسوم الجهة المشغّلة لامتداد النطاق، مثل `.com`، ورسوم ICANN دون هامش
ربح إضافي، في التسجيل والتجديد.
لذلك قارن سعر التجديد أيضًا عند المفاضلة بين الشركات، لا عرض السنة الأولى
فقط. والبيع بالتكلفة لا يعني ثبات السعر إلى الأبد؛ فقد تتغير رسوم الجهة
المشغّلة للامتداد. كما لا يعني أنه أقل من كل عرض ترويجي لدى الشركات الأخرى.
وتوجد أسباب عملية أخرى لاختيارها:
- إدارة التسجيل وDNS في حساب واحد تقلّل التنقل بين لوحات التحكم عند ربط
خدمة جديدة.
- تكامل DNSSEC مع المسجّل يختصر نقل بيانات DS يدويًا بين شركتين.
- [تُحجب بيانات الاتصال الشخصية](https://developers.cloudflare.com/registrar/account-options/whois-redaction/)
من بيانات التسجيل العامة حين تسمح قواعد سجلّ النطاق بذلك. لا يعني هذا
إخفاء الهوية بالكامل؛ ما زالت Cloudflare تحتاج إلى بيانات تسجيل صحيحة،
وتبقى بعض الحقول متاحة للجميع.
لكن لهذا الاختيار قيدًا مهمًا: **يلزمك استخدام خوادم أسماء Cloudflare**
[ما دام النطاق مسجّلًا لديها](https://developers.cloudflare.com/registrar/get-started/register-domain/).
يمكنك استضافة الموقع لدى أي جهة، لكن لا يمكنك تحويل خوادم أسماء النطاق
إلى مزوّد DNS آخر مع إبقاء التسجيل لدى Cloudflare. إذا أردت هذه الحرية،
يمكنك تسجيل النطاق لدى شركة أخرى واستخدام Cloudflare لإدارة DNS فقط.
راجع أيضًا [الامتدادات المدعومة](https://developers.cloudflare.com/registrar/top-level-domains/).
لا تدعم Registrar حاليًا أسماء النطاقات الدولية IDN، ومنها الأسماء
المكتوبة بالعربية وصيغ Punycode المقابلة لها. هذا قيد في خدمة التسجيل،
ولا يعني أن نظام DNS نفسه يقتصر على الأسماء الإنجليزية.
### شراء نطاق جديد
افتح **Domain Registration → Register Domains** وابحث عن الاسم.
راجع مدة التسجيل وشروط التجديد، وأدخل بيانات اتصال صحيحة وتحقق من
المبلغ قبل إتمام الشراء. بعد ذلك أكمل التحقق من البريد، وراجع التجديد
التلقائي ووسيلة الدفع. يوضح
[دليل التسجيل](https://developers.cloudflare.com/registrar/get-started/register-domain/)
الخطوات الحالية؛ والتجديد التلقائي مفعّل افتراضيًا.
تكون خوادم أسماء Cloudflare معيّنة للنطاق الجديد بالفعل. يبقى عليك ربط
الموقع والبريد؛ شراء الاسم وحده لا ينشر تطبيقًا ولا ينشئ صندوق بريد.
### نقل تسجيل نطاق موجود
يمكنك نقل إدارة DNS دون نقل التسجيل. وإذا أردت
[نقل التسجيل إلى Cloudflare](https://developers.cloudflare.com/registrar/get-started/transfer-domain-to-cloudflare/)،
فعليك أولًا تفعيل منطقة النطاق لديها. تحقق من أهلية النقل واتبع تعليمات
الامتداد الذي تستخدمه. لمعظم الامتدادات العامة، تحتاج إلى فتح قفل النقل
والحصول على رمز التفويض من المسجّل الحالي. قد تمنع قيود مؤقتة نقل
نطاق سُجّل أو نُقل أو عُدّلت بيانات صاحبه
مؤخرًا. وتختلف الرسوم ومدة التسجيل الإضافية حسب الامتداد؛ فلا تفترض أن
كل الامتدادات تتبع قواعد `.com`.
**طريقان إلى إدارة النطاق على Cloudflare**
شراء نطاق جديد يختصر نقل DNS. أما النطاق الموجود، فيحتاج إلى مراجعة إعداداته قبل تغيير خوادم أسمائه.
1. **A · Registrar — نطاق جديد من Cloudflare**: اختر الاسم وراجع التجديد، ثم أكمل التسجيل وتحقق من البريد. تكون خوادم Cloudflare معيّنة للنطاق.
2. **B · Existing domain — نطاق مسجّل لدى جهة أخرى**: انسخ السجلات وراجع DNSSEC، ثم غيّر خوادم الأسماء لدى المسجّل وانتظر تفعيل النطاق.
3. **A + B — اربط الخدمات وافحصها**: اضبط الموقع والبريد وDNSSEC. نقل تسجيل النطاق الموجود إلى Cloudflare يظل قرارًا مستقلًا.
*يصل الطريقان إلى أدوات DNS نفسها. نقل التسجيل يغيّر الجهة المسؤولة عن التجديد، بينما تغيير خوادم الأسماء يحدّد من يجيب عن استعلامات DNS.*
## ماذا تغيّر السحابة البرتقالية؟
إذا كان الموقع على استضافة خارجية، فإن
[إعداد البروكسي](https://developers.cloudflare.com/dns/proxy-status/)
يحدّد مسار اتصال المتصفح. عند اختيار **DNS only**، يحصل المتصفح على
عنوان الاستضافة ويتصل بها. وعند اختيار **Proxied**، يحصل على عنوان تابع
لـCloudflare ويتصل بشبكتها أولًا، حيث يمكن تطبيق قواعد الحماية والتخزين
المؤقت على طلب الويب.
**بعد معرفة العنوان، إلى أين يتصل المتصفح؟**
- **DNS only** — موقع على استضافة خارجية
1. المتصفح
2. خادم الموقع
- **Proxied** — موقع على استضافة خارجية
1. المتصفح
2. Cloudflare
3. خادم الموقع
- **Worker + Custom Domain** — تطبيق يعمل على Cloudflare
1. المتصفح
2. Cloudflare
3. Worker
يسبق DNS هذه الاتصالات. في المسار الثالث، يعمل الـWorker داخل Cloudflare.
*يسبق استعلام DNS اتصال المتصفح بالموقع. وإذا كان التطبيق يعمل على Worker، فلا حاجة إلى خادم موقع منفصل خلف Cloudflare.*
تفعيل السحابة البرتقالية لا يعني تخزين كل استجابة مؤقتًا. فشبكة CDN
التقليدية لدى Cloudflare
[لا تخزّن HTML أو JSON افتراضيًا](https://developers.cloudflare.com/cache/concepts/default-cache-behavior/).
أما Workers والملفات الثابتة فلها آلياتها في تقديم المحتوى، وسنعود إليها
في جزء الاستضافة.
كذلك، لا يحوّل هذا الخيار Cloudflare إلى وسيط لكل أنواع الاتصال.
اترك سجلات خوادم البريد وسجلات إثبات ملكية النطاق للخدمات الخارجية على
DNS-only، واتبع تعليمات مزوّد الخدمة. توضح وثائق
[حدود البروكسي](https://developers.cloudflare.com/dns/proxy-status/limitations/)
ما يمكن تمريره عبره. يمكن تفعيل البروكسي لسجلات `A` و`AAAA` و`CNAME`
المستخدمة للاتصالات المدعومة، أما `MX` و`TXT` فليست لها وظيفة مماثلة.
السحابة الرمادية هي الاختيار الصحيح لبعض الخدمات.
ومع البروكسي، تخفي إجابة DNS العامة عنوان الخادم الذي أدخلته، لكن ذلك
لا يمنع الوصول إليه مباشرة إذا كان عنوانه معروفًا من سجلات قديمة أو
[أسماء أخرى على DNS-only](https://developers.cloudflare.com/dns/manage-dns-records/troubleshooting/exposed-ip-address/). حماية الاتصال المباشر بالخادم جزء مستقل من
إعداد الاستضافة.
## افهم السجل قبل تعديله
لكل نوع من السجلات وظيفة. هذه أكثر الأنواع التي ستصادفها، ويمكن الرجوع
إلى [مرجع السجلات](https://developers.cloudflare.com/dns/manage-dns-records/reference/dns-record-types/)
للتفاصيل:
| السجل | ما الذي يحدّده؟ |
| --- | --- |
| `A` | عنوان IPv4 لاسم معيّن |
| `AAAA` | عنوان IPv6 لاسم معيّن |
| `CNAME` | اسم مضيف آخر يُستكمل البحث عن العنوان من خلاله |
| `MX` | خوادم استقبال البريد الخاص بالنطاق |
| `TXT` | نصوص تستخدمها الخدمات، مثل بيانات إثبات الملكية وتوثيق البريد |
| `CAA` | الجهات المسموح لها بإصدار شهادات للاسم |
| `SRV` | موقع خدمة، بما فيه اسم المضيف والمنفذ |
| `NS` | خوادم الأسماء المسؤولة عن منطقة أو نطاق فرعي مفوّض |
| `PTR` | البحث العكسي من عنوان IP إلى اسم، ويديره عادة مزوّد العنوان |
لإضافة سجل، افتح **DNS → Records → Add record** في إعدادات النطاق.
اختر النوع والاسم والقيمة، ثم حالة البروكسي وTTL حين تتاحان.
ويتيح [محرّر السجلات](https://developers.cloudflare.com/dns/manage-dns-records/how-to/create-dns-records/)
إضافة تعليق. اكتب اسم الخدمة التي طلبت السجل لتعرف سبب وجوده لاحقًا.
**قراءة نموذج إضافة سجل**
مثال توضيحي لخادم خارجي. العنوان 192.0.2.10 محجوز للتوثيق ولا يشغّل موقعًا حقيقيًا.
1. **Type · A — نوع الإجابة**: ربط اسم بعنوان IPv4. استخدم AAAA لعنوان IPv6.
2. **Name · @ — الاسم الذي تضبطه**: يعني example.com في هذه المنطقة. أما www فيعني www.example.com.
3. **Content · 192.0.2.10 — الوجهة**: استبدله بعنوان الخادم الذي تعطيك إياه شركة الاستضافة.
4. **Proxy · Proxied / TTL · Auto — مسار الاتصال ومدة الحفظ**: السحابة البرتقالية تمرّر الويب عبر Cloudflare؛ وTTL تخص حفظ إجابة DNS.
*مثال مشروح لحقول الإعداد، وليس لقطة من حساب فعلي. تحدّد الحقول الاسم والإجابة وطريقة تعامل Cloudflare معها. استخدم قيم الاستضافة الخاصة بك.*
لنفترض أن شركة الاستضافة طلبت سجل CNAME للاسم `www.example.com` يشير
إلى `project.host.example`. تكتب اسم المضيف وحده في قيمة السجل، دون
`https://` أو مسار صفحة. وعليك أيضًا إضافة `www.example.com` إلى
إعدادات النطاقات في الاستضافة؛ فسجل DNS لا يضبط التطبيق الذي سيستقبل الطلب.
ولا يعيد CNAME توجيه المتصفح إلى عنوان آخر. إذا ربطت `www` بالنطاق
الرئيسي بهذه الطريقة، يبقى `www` ظاهرًا في شريط العنوان. لتوجيه الزوار
إلى عنوان واحد تختاره، تحتاج إلى إعادة توجيه HTTP في الاستضافة أو في
Cloudflare.
أما الرمز `@` في لوحة التحكم فيشير إلى النطاق الأساسي، مثل
`example.com`. وتتيح Cloudflare استخدام CNAME عند هذا الاسم بفضل
[CNAME flattening](https://developers.cloudflare.com/dns/cname-flattening/):
تبحث عن عناوين IP للاسم المستهدف وتعيدها في الإجابة. لذلك لا يمكنك دائمًا
استنتاج نوع السجل الذي أضفته من العنوان الذي يعيده `dig`.
لا تضف CNAME إلى جانب سجل A أو AAAA للاسم العادي نفسه؛ ترفض
Cloudflare هذا [التعارض بين السجلات](https://developers.cloudflare.com/dns/manage-dns-records/troubleshooting/records-with-same-name/).
أما A وAAAA فيمكن أن يجتمعا لأن كلًا منهما يجيب عن نوع مختلف من
العناوين. أضف AAAA لخادم الاستضافة فقط إذا كان يخدم الموقع عبر IPv6.
مع DNS-only، قد يرسل سجل AAAA قديم زوار IPv6 إلى الاستضافة السابقة،
رغم نجاح اختبارك عبر IPv4. أما مع البروكسي، فيمكن لـCloudflare
[توفير عناوين IPv6 للزوار](https://developers.cloudflare.com/network/ipv6-compatibility/)
حتى لو كان خادمك يستخدم IPv4؛ فلا تحتاج إلى إضافة AAAA للخادم لهذا الغرض.
## انقل إدارة DNS إلى Cloudflare
للنطاق المسجّل لدى شركة أخرى، اتبع
[طريقة الإعداد الكامل](https://developers.cloudflare.com/dns/zone-setups/full-setup/setup/).
[تتوفر خدمة DNS على خطة Free](https://developers.cloudflare.com/dns/)،
وتبقى تكلفة تسجيل النطاق وأي منتجات مدفوعة مستقلة عنها.
رتّب العمل على النحو التالي:
1. احتفظ بنسخة من سجلاتك لدى مزوّد DNS الحالي.
2. أضف النطاق الأساسي إلى Cloudflare وقارن السجلات المستوردة بهذه
النسخة؛ فقد يفوت الفحص التلقائي بعضها. راجع الموقع والبريد وإثبات
الملكية والأسماء الأقل استخدامًا.
3. عالج إعداد DNSSEC الحالي قبل التبديل، كما سنشرح بعد قليل.
4. استبدل خوادم الأسماء لدى المسجّل بالزوج الذي عيّنته Cloudflare لنطاقك.
لا تنسخ خوادم موقعي من المثال.
5. أبقِ خدمة DNS القديمة والاستضافة متاحتين خلال الانتقال. تحقق من ظهور
حالة **Active** في Cloudflare، ثم اختبر الخدمات.
إضافة سجلات NS داخل لوحة DNS القديمة لا تغني عن تغيير خوادم الأسماء
لدى مسجّل النطاق؛ فالتفويض من المنطقة الأعلى هو الذي يوجّه الاستعلامات
إلى المزوّد الجديد.
إذا كان DNSSEC مفعّلًا، اتبع
[إرشادات نقله](https://developers.cloudflare.com/dns/dnssec/#migrate-to-cloudflare-with-dnssec-active)
قبل التغيير. في الطريقة المعتادة، تحذف سجل DS القديم لدى مسجّل النطاق،
وتنتظر انتهاء صلاحية نسخه المخزّنة مؤقتًا، ثم تغيّر خوادم الأسماء.
أبقِ توقيع المنطقة القديمة مفعّلًا ما دامت نسخ DS المخزّنة صالحة.
وبعد التبديل، انتظر انتهاء TTL لسجلات خوادم الأسماء القديمة قبل تفعيل
DNSSEC في Cloudflare ونشر سجل DS الجديد. بذلك تتجنب مقارنة إجابات
مزوّد بمفاتيح المزوّد الآخر. تتوقف حماية DNSSEC مؤقتًا خلال هذه الطريقة؛
ويشرح الدليل أيضًا نقلها دون انقطاع التوقيع لدى المزوّدين الذين يدعمون ذلك.
### ما الذي تحميه DNSSEC؟
تستخدم DNSSEC التوقيعات وسلسلة ثقة تمر بالنطاق الأعلى للتحقق من مصدر
إجابات DNS وسلامتها. لكنها لا تشفّر الاستعلامات ولا تحل محل HTTPS.
أما [DNS over HTTPS](https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/)
فيشفّر الاتصال بين الجهاز وخادم حل الأسماء.
لمنطقة جديدة، افتح **DNS → Settings → DNSSEC** واتبع خطوات التفعيل.
يربط سجل DS المنطقة الأعلى بمفتاح توقيع DNS لنطاقك. إذا كان المسجّل
خارجيًا، فأضف لديه بيانات DS التي تعطيك إياها Cloudflare.
أما مع Cloudflare Registrar فيتولى التكامل بين الخدمتين هذه الخطوة.
تحقق من الحالة النهائية؛ الضغط على زر التفعيل وحده لا يثبت اكتمال سلسلة
الثقة.
وإذا نقلت DNS إلى جهة أخرى لاحقًا، فخطط لنقل DNSSEC معها. سجل DS
يشير إلى مفاتيح قديمة قد يعطّل حل الأسماء حتى لو نسخت جميع سجلات A
وMX نسخًا صحيحًا.
## اربط الاسم بالتطبيق الذي سيستقبل الطلبات
للاستضافة الخارجية، استخدم القيم التي يزوّدك بها المضيف، وتأكد من دعمه
للعمل خلف بروكسي Cloudflare. لا تنسخ عنوان IP من موقع آخر؛ فقد يكون
العنوان الذي تراه تابعًا لـCloudflare، لا لخادم الموقع.
قد تعطيك شركة الاستضافة عنوان IPv4 للنطاق الأساسي، وتطلب ربط `www`
به. تضيف حينها سجل A للاسم `@` وسجل CNAME للاسم `www`، وتعرّف
الاستضافة بالاسمين. اختر العنوان الذي تريد ظهوره للزوار، واضبط إعادة
التوجيه في الاستضافة أو باستخدام
[Redirect Rules](https://developers.cloudflare.com/rules/url-forwarding/).
ولكي تطبّق Cloudflare قاعدة إعادة توجيه، يجب أن يصل اتصال الاسم المصدر
إلى البروكسي لديها. اختبر الاسمين عبر HTTPS؛ إذ ينبغي أن تتوافق سجلات
DNS والشهادات وإعادة التوجيه.
أما التطبيق الذي يعمل على Workers، فيمكن ربطه مباشرة باسم مضيف عبر
[Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/).
بعد تفعيل النطاق على Cloudflare وإنشاء Worker، افتح إعدادات الـWorker
واتبع **Settings → Domains & Routes → Add → Custom Domain**.
تنشئ Cloudflare سجل DNS والشهادة. وإذا وُجد سجل CNAME بالاسم نفسه،
فعليك معالجة هذا التعارض أولًا؛ تحقق مما يخدمه السجل قبل استبداله.
يطابق Custom Domain اسم المضيف كما هو. فربط `example.com` لا يشمل
`www.example.com` تلقائيًا؛ اضبط الاسمين إذا أردت أن يعمل كلاهما.
ويختلف هذا عن Worker Route الذي يمكنه تشغيل كود أمام خادم موقع موجود.
سنحتاج إلى هذا الفرق في الجزء التالي.
وفي حالة خادم خارجي خلف البروكسي، يتكوّن اتصال HTTPS من مرحلتين:
من المتصفح إلى Cloudflare، ثم منها إلى الخادم. استخدم
[Full (strict)](https://developers.cloudflare.com/ssl/origin-configuration/ssl-modes/full-strict/)
مع شهادة غير منتهية تطابق اسم المضيف، صادرة عن جهة موثوقة لدى المتصفحات
أو عن Cloudflare Origin CA. أما مع DNS-only، فيتصل المتصفح بالخادم
مباشرة ويحتاج إلى شهادة يثق بها؛
[شهادات Cloudflare Origin CA لا تفي بهذا الشرط](https://developers.cloudflare.com/ssl/origin-configuration/origin-ca/#3-change-ssltls-mode).
وتغطي [شهادة Universal SSL المعتادة](https://developers.cloudflare.com/ssl/edge-certificates/universal-ssl/limitations/)
في إعداد المنطقة الكامل النطاق الأساسي والنطاقات الفرعية من المستوى
الأول. لا تفترض أنها تشمل `api.staging.example.com` أيضًا؛ فقد يعمل
DNS لهذا الاسم بلا مشكلة، بينما تحتاج شهادته إلى تغطية إضافية.
## حافظ على عمل البريد أيضا
يمكن أن يكون الموقع والبريد لدى مزوّدين مختلفين. احتفظ
[بسجلات البريد](https://developers.cloudflare.com/dns/manage-dns-records/how-to/email-records/)
التي يطلبها مزوّدك حين تنقل DNS.
تحدّد سجلات MX خوادم الاستقبال، وتُفضّل القيم الأصغر في حقل الأولوية.
وإذا كان MX يشير إلى `mail.example.com`، فذلك الاسم يحتاج إلى سجل
عنوان بدوره، ويجب إبقاء سجل خادم البريد على DNS-only؛ فبروكسي الويب
المعتاد لدى Cloudflare لا يمرّر SMTP.
أما إرسال الرسائل، فتتعلق به ثلاثة إعدادات ستراها كثيرًا:
- **SPF** يستخدم سجل TXT لتحديد خوادم الإرسال المسموح لها باستخدام
نطاق المرسِل في اتصال SMTP. قد يختلف هذا النطاق عن الظاهر في حقل
From. يحدّد مزوّدك موضع السجل، سواء عند `@` أو نطاق فرعي.
- **DKIM** ينشر البيانات التي يستخدمها المستقبِل للتحقق من توقيع
الرسالة. يزوّدك مزوّد البريد غالبًا بسجل TXT أو CNAME تحت اسم مثل
`selector._domainkey`.
- **DMARC** يستخدم سجل TXT عند `_dmarc` لطلب تقارير وتحديد طريقة
التعامل مع البريد الذي يحمل نطاقك في حقل From. يتطلب
[اجتياز DMARC](https://www.rfc-editor.org/rfc/rfc9989.html#section-4.1)
نجاح SPF أو DKIM مع توافق نطاقه مع نطاق From؛ لا يُشترط نجاح كليهما.
استخدم قيم مزوّدك الفعلية. لا تنسخ سياسة بريد من موقع آخر، ولا تضف
سياسة SPF مستقلة لكل خدمة إرسال؛ إذ
[يسمح SPF بسجل سياسة واحد لكل اسم](https://www.rfc-editor.org/rfc/rfc7208#section-3.2).
اجمع الجهات المصرّح لها وفق تعليمات مزوّديك، واحصر خدمات الإرسال
المشروعة قبل تطبيق سياسة DMARC صارمة.
أما CNAME الذي تستخدمه خدمة لإثبات الملكية، فاتركه عادة على DNS-only.
أوقف flattening الاختياري للسجل وخيار تطبيقه على جميع سجلات CNAME.
فقد تحتاج الخدمة إلى رؤية CNAME نفسه،
لا عنوان IP الناتج عن تتبّعه. يشرح
[دليل مشكلات التحقق](https://developers.cloudflare.com/dns/manage-dns-records/troubleshooting/cname-domain-verification/)
لماذا قد تفشل هذه الخطوة رغم أن القيمة التي أدخلتها تبدو صحيحة.
إضافة السجلات لا تنشئ صندوق بريد. خدمة Cloudflare Email Routing وبريد
التطبيق خدمات مستقلة، وسنتناولها في الجزء الخاص بالبريد.
## لماذا لا يظهر تعديل DNS فورا؟
يغيّر تعديل السجل الإجابة لدى الخوادم الموثوقة، لكنه لا يرسل إشعارًا
إلى كل خادم وجهاز ومتصفح يحتفظ بإجابة أقدم. لهذا قد يرى زائر القيمة
الجديدة، بينما يظل آخر يستخدم نسخة محفوظة. تسمّى هذه الفترة عادة
«انتشار تغييرات DNS».
**لماذا قد تبقى الإجابة القديمة؟**
مثال مبسّط لسجل DNS-only ومدّة حفظ قديمة تبلغ ساعة. الأوقات للتوضيح.
1. **12:00 · TTL 3600 — حفظ الإجابة القديمة**: يحتفظ خادم حل الأسماء بالعنوان لمدة تصل إلى ساعة.
2. **12:10 · TTL 300 — تعديل العنوان وخفض TTL**: تعرض الخوادم الموثوقة القيمة الجديدة. النسخة القديمة لا تتلقى إشعارًا بالتعديل.
3. **13:00 — انتهاء مدة الإجابة القديمة**: يعيد خادم حل الأسماء الاستعلام عند الحاجة، فيحصل على القيمة الجديدة.
*خفض TTL بعد حفظ الإجابة لا يقلّص المدة المتبقية للنسخة المحفوظة. في هذا المثال، قد يبقى العنوان القديم مستخدمًا حتى الساعة 13:00 رغم تعديله عند 12:10.*
إذا كنت تخطط لتغيير عنوان سجل على DNS-only، فخفّض TTL مسبقًا
وانتظر مرور المدة القديمة، ثم غيّر الوجهة. وأبقِ الوجهتين تعملان خلال الانتقال إن
أمكن. أما السجلات المفعّل عليها البروكسي فتستخدم
[Auto TTL، وقيمتها حاليًا 300 ثانية](https://developers.cloudflare.com/dns/manage-dns-records/reference/ttl/).
وهذا ليس ضمانًا بأن كل جهاز سيرى التغيير خلال خمس دقائق؛ فللتفويض
والتخزين المحلي مدد أخرى.
وافصل بين حفظ إجابة DNS وحفظ صفحة ويب. مسح ذاكرة CDN المؤقتة في
Cloudflare لا يمسح إجابات خوادم حل الأسماء. إذا وصل النطاق إلى التطبيق
الصحيح لكنه عرض مقالًا قديمًا، فافحص تخزين HTTP والنشر قبل تعديل DNS.
## افحص DNS، ثم استجابة الموقع
لنعد إلى هذا الموقع ونطلب عناوينه:
```bash
dig +short A omaralbeik.com
dig +short AAAA omaralbeik.com
```
في فحص 17 أيلول نفسه، أعاد استعلام A العنوانين `188.114.96.0`
و`188.114.97.0`. هذه نتيجة فحص، وليست قيمًا تنسخها إلى إعداداتك.
يوضح DNS أين يمكن بدء الاتصال، لكنه لا يكشف اسم الـWorker الذي يشغّل
موقعي، ولا كيف يعالج التطبيق المسارين `/en` و`/ar`.
لفحص استجابة HTTP، اطلب ترويساتها:
```bash
curl -I https://omaralbeik.com/en
```
وجود `server: cloudflare` وترويسة `cf-ray` يدل على أن Cloudflare
عالجت الطلب، لكنه لا يثبت أن الاستجابة جاءت من التخزين المؤقت.
اقرأ رمز الحالة أيضًا؛ فإعادة التوجيه استجابة HTTP صحيحة، لكن الصفحة
المطلوبة تقع عند العنوان المذكور في ترويسة `location`.
إذا عدّلت سجلًا ولم ترَ النتيجة المتوقعة، قارن إجابة خادم يحلّ الأسماء
بإجابة أحد خوادم النطاق الموثوقة. باستخدام إعدادات موقعي وقت الكتابة:
```bash
dig @1.1.1.1 omaralbeik.com A +noall +answer
dig @alan.ns.cloudflare.com omaralbeik.com A +noall +answer
```
عند فحص نطاقك، استبدل الاسم وأحد خوادمه المعيّنة له بالقيم المناسبة.
العدد الذي يسبق `IN A` هو مدة TTL بالثواني. وقد تختلف عناوين Cloudflare
بين إجابتين صحيحتين لسجل مفعّل عليه البروكسي، فلا تعتبر اختلاف IP وحده
دليلًا على قدم الإجابة. ولأن DNS لا يكشف تغيير الخادم خلف البروكسي،
راجع الوجهة في لوحة التحكم واختبر استجابة HTTP أيضًا.
وإذا لم يطبع `+short` شيئًا، أعد الاستعلام دونه لترى تفاصيل الاستجابة.
غياب الناتج وحده لا يحدّد السبب؛ فقد لا يوجد سجل من النوع المطلوب، أو
قد تكون هناك حالة مثل `NXDOMAIN` أو `SERVFAIL`. أما إذا نجح استعلام
DNS وفشل HTTPS، فانتقل إلى فحص الشهادات والتوجيه والتطبيق.
### ابدأ الفحص مما تراه
| ما الذي ظهر؟ | ما الذي تفحصه بعده؟ |
| --- | --- |
| بقي النطاق بحالة Pending | خوادم الأسماء لدى المسجّل وإعداد DNSSEC القديم |
| `NXDOMAIN` | تهجئة الاسم والمنطقة المختارة ووجود الاسم لدى المزوّد المسؤول |
| `NOERROR` دون إجابة | وجود النوع المطلوب؛ غياب AAAA لا يعني بالضرورة وجود خلل في A |
| `SERVFAIL` | التحقق من DNSSEC والتفويض وتوافر الخوادم؛ النتيجة وحدها لا تثبت خلل DNSSEC |
| بعض الزوار يصلون إلى الخادم القديم | الإجابات المخزّنة وسجلات A أو AAAA التي لم تُعدّل |
| DNS يعمل وHTTPS يفشل | تغطية الشهادة ووضع البروكسي وTLS على الخادم وإعداد النطاق في الاستضافة |
| الموقع يعمل والبريد لا يصل | وجهات MX وعناوين خوادم البريد وسجلات التوثيق |
| فشل إثبات الملكية | الاسم الدقيق وحالة البروكسي وflattening وأي تفويض للنطاق الفرعي |
هذه نقاط بدء للفحص، وليست تشخيصًا نهائيًا. احتفظ بناتج الأمر كاملًا قبل
تغيير الإعدادات حتى تستطيع مقارنة النتيجة بعد كل تعديل. ويمكنك تتبّع
التفويض باستخدام:
```bash
dig +trace omaralbeik.com
```
يتابع هذا الأمر الإحالات بين الخوادم بدل الاعتماد على خادم حل الأسماء
المعتاد. وقد يفشل في شبكة تمنع استعلامات DNS المباشرة؛ فلا تعتبر فشله
وحده دليلًا على تعطل الموقع.
## سجلات النجمة وتفويض النطاقات والإعدادات الأخرى
**سجلات النجمة، أو wildcards**، مثل `*.example.com`، توفّر إجابات
لأسماء فرعية غير مطابقة لسجلات محددة. لا تحلّ محل سجل النطاق الأساسي،
وقد يمنع وجود اسم أو تفويض تطبيق سجل النجمة. تعرض
[أمثلة Cloudflare](https://developers.cloudflare.com/dns/manage-dns-records/reference/wildcard-dns-records/)
الحالات الأقل وضوحًا، ومنها الأسماء الأعمق. قواعد wildcard في DNS تختلف
عن نطاق تغطية الشهادة؛ لا تستنتج إحداهما من الأخرى.
**تفويض نطاق فرعي** يعني إسناد DNS لفرع مثل `team.example.com`
إلى مزوّد آخر. تضيف سجلات NS التي يحدّدها المزوّد للاسم `team` في
المنطقة الأم، ثم تدير سجلات الفرع لديه. يختلف هذا عن إضافة سجل A
لنطاق فرعي داخل منطقتك. اتبع
[دليل التفويض](https://developers.cloudflare.com/dns/manage-dns-records/how-to/subdomains-outside-cloudflare/)
إذا أردت تفعيل DNSSEC لذلك الفرع أيضًا.
**الإعداد الجزئي وDNS الثانوي** مناسبان لمؤسسات لديها متطلبات قائمة.
يتيح إعداد CNAME الجزئي للمناطق المؤهلة على خطتي Business وEnterprise
الاحتفاظ بمزوّد DNS آخر وتمرير أسماء مختارة عبر بروكسي Cloudflare.
وتتيح عمليات نقل المناطق على Enterprise ترتيبات DNS أساسية أو ثانوية.
هذه [طرق إعداد بديلة](https://developers.cloudflare.com/dns/zone-setups/)، وليست
خطوات إضافية مطلوبة لتشغيل موقع عادي.
## اجعل الإعداد سهل الصيانة
قبل تعديل كبير، صدّر المنطقة من **DNS → Records → Import and Export**.
يتضمن [ملف تصدير المنطقة](https://developers.cloudflare.com/dns/manage-dns-records/how-to/import-and-export/)
السجلات ووسومًا خاصة بـCloudflare. دوّن بصورة مستقلة الإعدادات التي لا
تندرج تحت DNS، مثل إعادة التوجيه وTLS ونطاقات Workers؛ فملف المنطقة
ليس نسخة احتياطية من الحساب كله.
إذا أردت تحديث السجلات برمجيًا، فاستخدم
[رمز API محدود الصلاحيات](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/)
للمنطقة والعمليات التي تحتاجها المهمة فقط. أداة حصر السجلات لا تحتاج إلى
صلاحية تعديلها. احتفظ بالرمز كسرّ، واجعل التعديلات تأتي من مسار عمل واضح
مع توثيق مصدر كل تعديل، حتى لا يلغي سكربت تعديلًا يدويًا دون أن تنتبه.
وأخيرًا، افحص ما يستخدمه الزائر: النطاق الأساسي و`www`، وشهادة HTTPS
لكل منهما، وإعادة التوجيه إلى العنوان المختار، والبريد إرسالًا واستقبالًا.
وتحقق من DNSSEC والتجديد أيضًا.
في الجزء التالي ننظر إلى ما يجري داخل الـWorker بعد وصول الطلب إليه.
إذا كنت تعرف شخصًا يربط نطاقه الأول بموقع، فقد يساعده هذا الدليل.
وإن واجهت نتيجة لم تتضح لك، [أرسل لي ما ظهر وما جرّبته لفحصه](/ar/contact).
---
# An introduction to Cloudflare's ecosystem
- URL: https://omaralbeik.com/en/blog/series/cloudflare/introduction-to-cloudflare
- Markdown: https://omaralbeik.com/en/blog/series/cloudflare/introduction-to-cloudflare.md
- Translation: https://omaralbeik.com/ar/blog/series/cloudflare/introduction-to-cloudflare
- Author: Omar Albeik
- Language: en
- Type: article
- Date: 7 September 2026
- Topics: infrastructure
A website starts with a name and a page. Before long, it needs somewhere to
save a form submission, a place for uploaded files, a way to send email, and
some protection from requests nobody wanted. Each addition is small. Together,
they become the infrastructure you have to look after.
Cloudflare covers much of that ground. You can use it to manage DNS and cache
traffic for a site hosted elsewhere, or you can run the application itself
there. Its developer platform includes code execution, databases, file
storage, background jobs, and AI services, alongside the networking and
security tools.
I use it for this site and [Unblock Syria](https://unblocksyria.com). What
appeals to me is being able to connect those parts without maintaining a
server for each job. This series will explain how I use them, where they help,
and what you need to understand before relying on them. First, a tour of how
the pieces fit together.
## Start with the domain and the incoming request
There are two separate jobs here: owning a domain and telling browsers where
to find it. Registrar handles registration and renewal; DNS holds the records
that point names at services. You can use Cloudflare DNS while keeping your
domain registered elsewhere.
For a site on another host, the next choice is whether web traffic should
pass through Cloudflare. A
[proxied DNS record](https://developers.cloudflare.com/dns/proxy-status/)
sends it through Cloudflare's network before it reaches your server. That
allows Cloudflare to serve cached content and apply traffic rules. A DNS-only
record leaves the web connection going directly to your host.
This is where the familiar CDN fits: keep reusable content on a distributed
network so every visitor doesn't need a fresh response from your server.
Security works along that path too. DDoS protection deals with attack traffic,
while the [web application firewall](https://developers.cloudflare.com/waf/)
can filter requests according to managed and custom rules. The available
controls depend on the plan and configuration.
You can stop here. Your existing application can stay where it is while
Cloudflare handles this part of the request's journey.
## Run the application on Workers
[Workers](https://developers.cloudflare.com/workers/) lets you deploy
application code to Cloudflare's network. A Worker can answer an API request,
render a page, or process an event. Cloudflare operates the runtime; you
provide the code and configure the resources it can use.
For a website, Workers can serve
[static assets](https://developers.cloudflare.com/workers/static-assets/)
alongside that code. You'll
also encounter Pages, Cloudflare's other website deployment product. We'll
look at the deployment choices in the frontend installment; either way, you
need to distinguish the files a browser downloads from the code that runs to
produce a response.
The connection to other services is a large part of the appeal. A
[binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/)
gives a Worker access to a resource such as a database or storage bucket
through its configuration. Service bindings let Workers call each other.
You still decide which part of the application may access which resource,
but the platform supplies the connection.
## Give each kind of data a home
An application usually needs more than one kind of storage. Cloudflare's
[data and storage guide](https://developers.cloudflare.com/workers/platform/storage-options/)
groups the options by the work they do:
- **D1** is a SQL database for records you need to query and relate.
- **R2** stores files and other objects: uploads, documents, and downloads.
- **KV** stores values by key and distributes reads across the network. It
suits data that can tolerate a delay before updates appear everywhere.
- **Durable Objects** combine code with state for work that needs coordination,
such as a shared session or a room of connected clients.
An existing database can remain outside Cloudflare too. Hyperdrive helps
Workers connect to supported Postgres and MySQL databases. Moving the
application code does not require moving every piece of data on day one.
Media has another set of needs. R2 can hold an image or video file;
[Images](https://developers.cloudflare.com/images/) adds image processing and
delivery, while [Stream](https://developers.cloudflare.com/stream/) handles
video encoding and playback delivery. Choose according to how the application
uses the file, not just its extension.
## Handle the work around a page load
Some work should happen after a response has gone back to the visitor.
[Queues](https://developers.cloudflare.com/queues/) passes messages to
consumers for processing. [Workflows](https://developers.cloudflare.com/workflows/)
organizes longer jobs into steps that can retry or resume. A file import,
for example, might need to fetch data, validate it, and wait for another
service before finishing.
Email belongs here as well. Email Sending handles mail from the application;
Email Routing forwards incoming mail addressed to your domain. Sending a
confirmation and receiving a message at `hello@example.com` are different
jobs, even though both involve email.
## Control access to the application
Access control is broader than protecting a public page.
[Cloudflare One](https://developers.cloudflare.com/cloudflare-one/) includes
Access for controlling who may reach applications, Gateway for policies on
outbound traffic, and Tunnel for connecting services hosted elsewhere.
Those tools can protect an internal dashboard or connect a private service.
Your public application's own users and permissions still need a design.
For public forms, [Turnstile](https://developers.cloudflare.com/turnstile/get-started/)
provides a bot-checking component. You integrate it into the page and validate
its token on the server. It is one part of accepting a submission safely.
## Add AI where the application needs it
Cloudflare also supplies services for AI features.
[Workers AI](https://developers.cloudflare.com/workers-ai/) runs models;
Vectorize stores embeddings for similarity search.
[AI Gateway](https://developers.cloudflare.com/ai-gateway/) helps observe and
control requests to model providers. These solve different parts of a feature:
a document search needs retrieval, while a generated answer also needs a
model call.
The Agents SDK supports stateful agents and MCP servers, which expose tools
to AI clients. We'll cover those after the underlying runtime and storage.
They are easier to reason about once you know where the code runs and where
its state lives.
## What this looks like in Unblock Syria
Unblock Syria uses a small selection of these services. Its public site,
admin dashboard, API, and MCP server each run on a Worker. The API uses D1 for
records, R2 for uploads, KV for cached responses, and Email Sending for mail.
Durable Objects handle rate-limit counters and MCP sessions.
Follow a submission through it: the site sends data to the API, the API
validates it, a record goes into D1, and an uploaded file goes into R2. The
public site and dashboard reach the API through service bindings; the MCP
server calls its public HTTPS endpoint with a signed token.
The choices have changed as the application has grown. Our rate-limit
counter moved from KV to a Durable Object when it needed coordinated updates.
We'll work through that choice in the storage installment. Here, it is an
example of why these services have distinct jobs despite sharing a platform.
## Where the five-dollar plan fits
Cloudflare has several plans and separately billed products. The
[Workers Paid plan](https://developers.cloudflare.com/workers/platform/pricing/)
starts at **US$5 per month per account**. It includes ten million requests and
thirty million milliseconds of CPU time each month, with additional usage
billed beyond those allowances. Those are the published prices as of
September 7, 2026.
That makes the entry cost attractive for a small application. It does not
put the entire ecosystem on a five-dollar subscription. Storage has its own
allowances and usage charges, domain registration costs extra, and products
such as Stream and Workers AI have separate pricing. Website security plans
are also distinct from the Workers subscription.
We'll calculate costs alongside the services that generate them. A page-view
count alone won't tell you how much database work, file processing, or model
inference the application performs.
## Building with it, and depending on it
[Wrangler](https://developers.cloudflare.com/workers/local-development/) is
the command-line tool for local development and deployment. Workers Builds
can deploy from a connected repository. In Unblock Syria, Builds deploys the
four Workers while tests run in GitHub Actions. Logs and usage metrics then
help explain what happens after a release.
Sharing a platform reduces some setup, but it also creates dependencies.
Code built around bindings and Durable Objects takes work to move. And a
global network does not put every database next to every visitor: where data
lives still affects response time. Those are decisions we'll examine as we
build, alongside the convenient parts.
The next installment starts with the domain and DNS. From there, we'll add
code, storage, and the services around them in the order an application needs
them. The [series page](/en/blog/series/cloudflare) has the planned guides.
What are you building, and which part of Cloudflare would you like this series
to explain? [Tell me about it](/en/contact). If someone on your team is
exploring the platform, share this introduction with them and compare which
services you would actually use.
---
# مدخل إلى منظومة Cloudflare
- URL: https://omaralbeik.com/ar/blog/series/cloudflare/introduction-to-cloudflare
- Markdown: https://omaralbeik.com/ar/blog/series/cloudflare/introduction-to-cloudflare.md
- Translation: https://omaralbeik.com/en/blog/series/cloudflare/introduction-to-cloudflare
- Author: Omar Albeik
- Language: ar
- Type: article
- Date: 7 أيلول 2026
- Topics: infrastructure
يبدأ الموقع باسم وصفحة. ثم تحتاج إلى حفظ بيانات نموذج، واستقبال ملفات من
المستخدمين، وإرسال رسائل بريد، وحماية التطبيق من الطلبات المزعجة. تبدو كل
إضافة بسيطة وحدها، لكن مجموعها يصبح بنية تحتية تحتاج إلى تشغيل ومتابعة.
توفر Cloudflare خدمات لكثير من هذه المهام. يمكنك استخدامها لإدارة DNS
وتسريع موقع تستضيفه في مكان آخر، أو تشغيل التطبيق نفسه عليها. إلى جانب
خدمات الشبكات والحماية، تضم المنصة أدوات لتشغيل الشيفرة وقواعد البيانات
وتخزين الملفات والمهام الخلفية والذكاء الاصطناعي.
أستخدمها في هذا الموقع وفي [Unblock Syria](https://unblocksyria.com).
ما يعجبني فيها هو سهولة ربط هذه الأجزاء دون إدارة خادم لكل مهمة. في هذه
السلسلة سأشرح كيف أستخدم خدماتها، وما الذي تسهّله، وما الذي ينبغي فهمه قبل
الاعتماد عليها. نبدأ بصورة عامة للمنصة، ثم ننتقل إلى التفاصيل في الأجزاء
التالية.
## من اسم الموقع إلى وصول الطلب
هناك فرق بين تسجيل النطاق وضبط وجهته. تتولى Registrar تسجيل اسم النطاق
وتجديده، بينما تحتفظ DNS بالسجلات التي تربط الأسماء بالخدمات. يمكنك استخدام
Cloudflare لإدارة DNS مع إبقاء النطاق مسجلًا لدى شركة أخرى.
إذا كان الموقع مستضافًا خارج Cloudflare، فالخطوة التالية هي اختيار مسار
طلبات الويب. عند تفعيل الوكيل على
[سجل DNS](https://developers.cloudflare.com/dns/proxy-status/)، تمر الطلبات
عبر شبكة Cloudflare قبل الوصول إلى خادمك. تستطيع المنصة عندها تقديم محتوى
مخزّن مؤقتًا وتطبيق قواعد على حركة الطلبات. أما وضع DNS-only، فيُبقي اتصال
الزائر مباشرًا بخادم الاستضافة.
هنا يأتي دور شبكة توزيع المحتوى، أو CDN: الاحتفاظ بنسخ من المحتوى القابل
لإعادة الاستخدام، حتى لا يحتاج كل زائر إلى استجابة جديدة من خادمك. وتعمل
خدمات الحماية على هذا المسار أيضًا؛ تخفف حماية DDoS هجمات حجب الخدمة،
ويفحص [جدار حماية تطبيقات الويب](https://developers.cloudflare.com/waf/)
الطلبات وفق قواعد جاهزة أو تضعها أنت. تختلف الأدوات المتاحة بحسب الخطة
والإعدادات.
قد يكون هذا كل ما تحتاج إليه من Cloudflare. يبقى التطبيق لدى مزوّد
الاستضافة الحالي، وتتولى Cloudflare هذا الجزء من وصول الطلبات إليه.
## تشغيل التطبيق على Workers
تتيح [Workers](https://developers.cloudflare.com/workers/) نشر شيفرة
التطبيق وتشغيلها على شبكة Cloudflare. يمكن لـ Worker الرد على طلب إلى
واجهة برمجية، أو توليد صفحة، أو معالجة حدث. تتولى Cloudflare تشغيل البيئة،
وأنت تكتب الشيفرة وتحدد الموارد التي تستطيع الوصول إليها.
يمكنك أيضًا تقديم
[ملفات الموقع الثابتة](https://developers.cloudflare.com/workers/static-assets/)
من Workers إلى جانب الشيفرة.
وستجد Pages، وهي خدمة أخرى لدى Cloudflare لنشر المواقع. سنقارن خيارات
النشر في الجزء الخاص بالواجهة الأمامية. ما يهم الآن هو التمييز بين الملفات
التي ينزّلها المتصفح، والشيفرة التي تعمل لتوليد استجابة له.
وتظهر فائدة المنصة عند توصيل الشيفرة بالخدمات الأخرى. تمنح
[الروابط (bindings)](https://developers.cloudflare.com/workers/runtime-apis/bindings/) تطبيق Worker إمكانية الوصول إلى مورد، مثل قاعدة بيانات أو
مساحة لتخزين الملفات، من خلال ملف الإعداد. وتتيح روابط الخدمات استدعاء
Worker من آخر. تبقى مسؤولًا عن تحديد من يستطيع الوصول إلى كل مورد، لكن
المنصة توفر طريقة الاتصال.
## أين تضع بيانات التطبيق؟
تختلف طريقة حفظ سجل مستخدم عن طريقة حفظ ملف رفعه. لذلك توجد عدة خدمات
للتخزين، ويشرح [دليل الاختيار بينها](https://developers.cloudflare.com/workers/platform/storage-options/)
المهام التي تناسب كلًا منها:
- **D1** قاعدة بيانات SQL للسجلات التي تحتاج إلى الاستعلام عنها وربطها ببعضها.
- **R2** لتخزين الملفات، مثل الصور المرفوعة والمستندات والملفات القابلة للتنزيل.
- **KV** لحفظ قيم تحت مفاتيح وقراءتها عبر الشبكة. تناسب البيانات التي تتحمل
بعض التأخير قبل ظهور تحديثاتها في جميع المواقع.
- **Durable Objects** تجمع الشيفرة والحالة التي تديرها، للمهام التي تحتاج
إلى تنسيق، مثل جلسة مشتركة أو غرفة تضم عدة مستخدمين متصلين.
ويمكن إبقاء قاعدة البيانات خارج Cloudflare. تساعد Hyperdrive على الاتصال
بقواعد Postgres وMySQL المدعومة من Workers، فلا يستلزم نقل الشيفرة نقل كل
البيانات معها منذ البداية.
وللصور والفيديو احتياجات إضافية. تستطيع R2 حفظ الملف، بينما تضيف
[Images](https://developers.cloudflare.com/images/) معالجة الصور وتقديمها،
وتتولى [Stream](https://developers.cloudflare.com/stream/) ترميز الفيديو
وتقديمه للتشغيل. يعتمد الاختيار على ما سيفعله التطبيق بالملف، لا على
امتداده وحده.
## ما يحدث بعد إرسال الصفحة
بعض المهام لا ينبغي أن ينتظر الزائر اكتمالها. تنقل
[Queues](https://developers.cloudflare.com/queues/) رسائل إلى شيفرة
تتولى معالجتها لاحقًا. وتنظم
[Workflows](https://developers.cloudflare.com/workflows/) المهام الأطول في
خطوات يمكن إعادة محاولتها أو استئنافها. قد يحتاج استيراد ملف، مثلًا، إلى
جلب بيانات وفحصها وانتظار خدمة أخرى قبل اكتماله.
والبريد جزء من عمل التطبيق أيضًا. تستخدم Email Sending لإرسال رسائله،
بينما توجّه Email Routing الرسائل الواردة إلى عناوين نطاقك. إرسال تأكيد
للمستخدم واستقبال رسالة على `hello@example.com` مهمتان مختلفتان.
## حماية النماذج والخدمات الداخلية
لا تقتصر الحماية على الصفحات العامة. تضم
[Cloudflare One](https://developers.cloudflare.com/cloudflare-one/)
خدمة Access للتحكم بمن يستطيع الوصول إلى التطبيقات، وGateway لوضع سياسات
على حركة الاتصال الصادرة، وTunnel لربط خدمات مستضافة في مكان آخر. يمكن
استخدام هذه الأدوات لحماية لوحة داخلية أو ربط خدمة خاصة. أما حسابات
مستخدمي تطبيقك العام وصلاحياتهم، فتحتاج إلى تصميمها داخل التطبيق.
وللنماذج العامة، توفر
[Turnstile](https://developers.cloudflare.com/turnstile/get-started/) مكوّنًا
للتحقق من الطلبات الآلية. تضيفه إلى الصفحة وتتحقق من رمزه على الخادم؛ وهو
جزء من معالجة إرسال النموذج بأمان.
## إضافة ميزات الذكاء الاصطناعي
توفر Cloudflare خدمات لمراحل مختلفة من بناء هذه الميزات.
تشغّل [Workers AI](https://developers.cloudflare.com/workers-ai/) النماذج،
وتحفظ Vectorize التمثيلات العددية للبيانات التي تستخدمها في البحث بالتشابه.
وتساعد [AI Gateway](https://developers.cloudflare.com/ai-gateway/) على
مراقبة الطلبات إلى مزوّدي النماذج والتحكم فيها. فالبحث في المستندات يحتاج
إلى استرجاع المحتوى المناسب، وإنتاج إجابة منه يحتاج أيضًا إلى استدعاء نموذج.
وتتيح Agents SDK بناء وكلاء يحتفظون بحالتهم وخوادم MCP تعرض أدوات لبرامج
الذكاء الاصطناعي. سنصل إليها بعد شرح تشغيل الشيفرة والتخزين؛ فهم مكان
تنفيذ الوكيل ومكان حفظ حالته يجعل بقية التفاصيل أوضح.
## مثال من Unblock Syria
يستخدم Unblock Syria مجموعة صغيرة من هذه الخدمات. يعمل الموقع العام
ولوحة الإدارة والواجهة البرمجية وخادم MCP على أربعة Workers. تستخدم
الواجهة D1 للسجلات، وR2 للملفات المرفوعة، وKV للاستجابات المخزّنة مؤقتًا،
وEmail Sending للبريد. ونستخدم Durable Objects لعدّادات الطلبات وجلسات MCP.
يمكن تتبع إرسال نموذج عبر هذه الأجزاء: يرسل الموقع البيانات إلى الواجهة
البرمجية، فتتحقق منها وتحفظ السجل في D1، بينما يذهب الملف المرفوع إلى R2.
يتصل الموقع ولوحة الإدارة بالواجهة من خلال روابط الخدمات، ويتصل خادم MCP
بعنوان HTTPS العام مع رمز موقّع.
تغيرت بعض الاختيارات مع نمو التطبيق. نقلنا عدّاد تحديد معدل الطلبات من
KV إلى Durable Object عندما احتجنا إلى تنسيق التحديثات. سنشرح هذه المسألة
في الجزء الخاص بالتخزين. يكفي هنا أنها توضح سبب وجود خدمات مختلفة داخل
المنصة نفسها: لكل منها مهمة تناسبها.
## ما علاقة الخمسة دولارات بكل هذا؟
لدى Cloudflare عدة خطط ومنتجات تُحسب رسومها بصورة مستقلة. يبدأ اشتراك
[Workers المدفوع](https://developers.cloudflare.com/workers/platform/pricing/)
من **خمسة دولارات أمريكية شهريًا للحساب**. يشمل عشرة ملايين طلب وثلاثين
مليون ميلي ثانية من وقت المعالج كل شهر، وتُضاف رسوم لما يتجاوز هذه الحصص.
هذه هي الأسعار المنشورة في 7 أيلول 2026.
هذا يجعل تكلفة البداية مناسبة لتطبيق صغير، لكنه لا يعني أن جميع الخدمات
تدخل في الاشتراك نفسه. للتخزين حصص ورسوم استخدام، ولتسجيل النطاق تكلفة
إضافية، ولمنتجات مثل Stream وWorkers AI تسعير مستقل. كذلك تختلف خطط حماية
المواقع عن اشتراك Workers.
سنحسب التكلفة عند شرح كل خدمة. عدد مشاهدات الصفحات وحده لا يوضح حجم العمل
الذي يؤديه التطبيق في قاعدة البيانات أو معالجة الملفات أو تشغيل النماذج.
## التطوير والاعتماد على المنصة
نستخدم [Wrangler](https://developers.cloudflare.com/workers/local-development/)
من سطر الأوامر للتطوير المحلي والنشر. ويمكن لـ Workers Builds النشر من
مستودع متصل به. في Unblock Syria، تتولى Builds نشر خدمات Workers الأربع،
بينما تعمل الاختبارات على GitHub Actions. وبعد النشر، تساعد السجلات
ومقاييس الاستخدام على فهم ما يحدث في التطبيق.
اجتماع هذه الخدمات يقلل بعض أعمال الإعداد، لكنه يزيد اعتماد التطبيق على
واجهات المنصة. تحتاج الشيفرة المبنية على الروابط وDurable Objects إلى
تعديل عند الانتقال إلى مزوّد آخر. كذلك لا تعني الشبكة العالمية وجود كل
قاعدة بيانات قرب كل زائر؛ يظل مكان البيانات مؤثرًا في زمن الاستجابة.
سنناقش هذه الاختيارات أثناء البناء، إلى جانب ما تسهّله المنصة.
نبدأ في الجزء القادم بالنطاق وDNS، ثم نضيف الشيفرة والتخزين والخدمات
المحيطة بهما بحسب حاجة التطبيق. تجد الأدلة المخطط لها في
[صفحة السلسلة](/ar/blog/series/cloudflare).
ما الذي تبنيه، وأي جانب من Cloudflare تود أن نشرحه في السلسلة؟ [أخبرني
عنه](/ar/contact). وإذا كان أحد زملائك يستكشف المنصة، فشارك معه هذا المدخل
وناقشا الخدمات التي قد تحتاجان إليها فعلًا.
---
# Drawing link previews that work in Arabic
- URL: https://omaralbeik.com/en/blog/link-previews-that-work-in-arabic
- Markdown: https://omaralbeik.com/en/blog/link-previews-that-work-in-arabic.md
- Translation: https://omaralbeik.com/ar/blog/link-previews-that-work-in-arabic
- Author: Omar Albeik
- Language: en
- Type: tutorial
- Date: 31 August 2026
- Topics: typography, tooling, software, engineering
A link preview is a PNG. You put a URL in `og:image`, a crawler fetches it and
caches it, and every platform that shows your link — Slack, X, LinkedIn,
WhatsApp, iMessage, Telegram — draws that file. Nothing about the page is
consulted at display time, and no browser of yours ever renders it — so
nothing a browser does for text is done for you here.
Most sites ship one image for every URL. It tells a reader which site the link
belongs to, which the domain already did. A per-route card can carry the
page's own title and description instead.
I have two of these in production, built opposite ways. omaralbeik.com draws
its cards at build time in plain Node. unblocksyria.com draws them per request
at the edge. Both are bilingual, and that is where most of the work went.
Arabic is where a renderer's shortcuts stop working.
## The short version
- One card per route, `og:image` absolute, with width, height, alt and
`twitter:card`.
- Build time unless the card's content can change after deploy.
- Load fonts as bytes you control, and know which container your renderer can
read.
- Decide the order of preference for what gets dropped before you need it.
- Every path has to end in a picture; a 500 means no image at all, not a
default one.
- For right-to-left: order, face selection and measurement are three separate
problems. Pure Arabic will look fine while all three are broken.
- Verify the ordering mechanically. You cannot see it.
## The tags, briefly
```html
```
The URL must be absolute; crawlers do not resolve a relative one. Without
`twitter:card` set to `summary_large_image` you get a small square thumbnail
instead of the card you drew. `og:title`, `og:description`, `og:url` and
`og:type` still have to be there as well.
1200×630 is what everything accepts, and platforms crop it differently — X to
16:9 in my testing. Keep the text inside a margin. Mine is 96px, arrived at by
looking at crops: nobody publishes a safe area, only an image size.
## Where the card gets drawn
One question decides it: can the card's content change after the deploy that
produced it?
If it cannot, draw at build time. Nothing sits in the request path and the
renderer can be any program you like. On omaralbeik.com that is an ordinary
Node script run after the build, reading each built page's own `` for
the title and description, so a card cannot disagree with the page it
previews.
```json
"build": "astro build && node scripts/og-render.mjs"
```
Outside the framework on purpose. With the Cloudflare adapter, Astro
prerenders routes inside workerd, where there is no filesystem to load a font
from and no way to load a native rasterizer.
If the content can change, draw per request. An unblocksyria.com service card
carries the blocking status and the outreach progress, and either can change
without a deploy. A build-time image would be a picture of the catalog on
deploy day.
That route is `ImageResponse` from `next/og` — satori for layout, a rasterizer
behind it. Fonts are the awkward part, and the part that matters later. There
is no filesystem on Workers, so the faces are base64 in the bundle: two
weights each of a Latin and an Arabic face, 129KB of font binary and 172KB
after base64, on every deploy. Both families ship whatever the locale, because
a Latin wordmark sits inside the Arabic card and an Arabic name sits inside
the English one.
WOFF, not WOFF2 — satori cannot read WOFF2, and it fails by throwing rather
than by falling back to a default face.
## Every path ends in a picture
A crawler that gets a 500 for `og:image` does not fall back to your site
default. It renders the card with no image at all.
So the per-request path needs a fallback, and the obvious code puts the
failure where the `catch` cannot see it: `new ImageResponse(...)` returns
before it rasterizes. `arrayBuffer()` is where the work is forced, so call it
inside the `try`.
```ts
export function renderCard(element: ReactElement): Promise {
return new ImageResponse(element, { width: OG_WIDTH, height: OG_HEIGHT, fonts })
.arrayBuffer();
}
```
Then fall back in layers: the full card, the card without the remote logo —
the most likely thing to have failed — and last a brand card that draws no
page data at all, so no page can break it. Cache a missing slug like any other
card and a 5xx not at all. Cache that one and you pin the generic card onto a
real page's link for the whole stale-while-revalidate window.
## Fitting the text
Given a real measure function, wrapping is ordinary: greedy wrap to a line
limit, an ellipsis when text is left over, a mid-word break for a token wider
than the column. Estimates are where it goes wrong, and across two scripts
they go wrong by about a factor of two. Sizing a title by character count set
"المرصد الأورومتوسطي لرصد الزلازل" at 28px beside an "EMSC" at 104px — both
ordinary names for the same kind of organization.
Satori has no line clamp either. A four-line sentence grows the block into
whatever sits under it. The clamp comes from the same metrics as everything
else.
Then there is the case where nothing fits. A three-line title cannot also
carry two lines of description at full size; the block runs over the rule
above and the mark below. Step the type down instead. Decide the order of
preference before you need it: keep the whole description, then the
unabbreviated title, then the large type.
```js
for (const descLines of card.description ? [2, 1, 0] : [0]) {
for (const size of [64, 57, 50]) {
const block = layout(card, { size, descLines });
if (block.height <= BAND) return block; // first fit wins
}
}
```
The outer loop keeps both description lines while the inner loop tries all
three type sizes. Only then does it try a one-line description, and finally
none. The type shrinks before a description line is removed, preserving the
information the description adds to the title for as long as it fits.
## Right to left
This is usually described as one problem, "RTL support". It is three, they
fail independently, and they have three different fixes.
### Word order
resvg does not implement the Unicode Bidirectional Algorithm. `direction` and
`unicode-bidi` are ignored entirely: setting `embed`, `isolate` or `plaintext`
produces byte-identical output, so there is nothing to configure your way out
of. Satori has the same gap from the other side — it places words in logical
order, left to right, so every Arabic name comes out backwards.
Pure Arabic looks right anyway, which is what makes this expensive to catch.
HarfBuzz infers direction from the script. A line with nothing Latin in it
renders correctly, and the bug appears only once a product name or a version
number joins the sentence. On a site about software, that is most of them.
At build time, do the ordering yourself. bidi-js resolves visual order — rule
L2 of the algorithm: from the highest embedding level down to the lowest odd
one, reverse every contiguous stretch of runs at or above it. Break lines in
logical order, then reorder each line separately. That is what a browser does.
Split into runs first. A run is the largest stretch you can hand a shaper as a
unit: one direction, one font.
```js
const bidi = bidiFactory();
function logicalRuns(text, stack, baseDir) {
const { levels } = bidi.getEmbeddingLevels(text, baseDir);
const runs = [];
for (let i = 0; i < text.length; ) {
const char = String.fromCodePoint(text.codePointAt(i));
const level = levels[i];
const face = faceFor(stack, text.codePointAt(i));
const last = runs[runs.length - 1];
if (last && last.level === level && last.face === face) last.text += char;
else runs.push({ level, face, text: char });
i += char.length;
}
return runs;
}
```
Then rule L2 itself, which is shorter than its description:
```js
function reorder(runs) {
const levels = runs.map((r) => r.level);
const highest = Math.max(...levels);
const odd = levels.filter((l) => l % 2 === 1);
const lowestOdd = odd.length ? Math.min(...odd) : highest + 1;
const out = [...runs];
for (let level = highest; level >= lowestOdd; level--) {
for (let start = 0; start < out.length; start++) {
if (out[start].level < level) continue;
let end = start;
while (end + 1 < out.length && out[end + 1].level >= level) end++;
out.splice(start, end - start + 1, ...out.slice(start, end + 1).reverse());
start = end;
}
}
return out;
}
```
Shaping a run is six lines, and two of them are traps:
```js
function shapeRun(run) {
const buffer = new HbBuffer();
buffer.addText(run.text);
buffer.guessSegmentProperties();
buffer.setDirection(run.level % 2 === 1 ? Direction.RTL : Direction.LTR);
shape(run.face.font, buffer);
return buffer.getGlyphInfosAndPositions();
}
```
Guess first: that sets the script and the language. Then state the direction,
or the shaper infers it from the characters and undoes the bidi pass you just
ran. And the direction is a numeric enum. Passing the string `"rtl"` is not a
type error — it means `INVALID`, and every advance comes back zero.
At the edge, where you cannot run HarfBuzz yourself, `row-reverse` on a flex
row gets you the same result. One caveat. Reorder directional runs, not
whitespace-delimited words: bidi never reverses the order inside a Latin run.
Split on spaces and reverse the tokens and "متجر Google Play" becomes "Play
Google" — wrong in the one place a mixed name actually occurs.
### Which face draws the glyph
The empty boxes in that figure are the second failure. It is not really about
Arabic. It is about font fallback in a renderer that has none.
Fontsource splits a family into one file per script, and you load files, not
families. The Arabic file of IBM Plex Sans Arabic cannot draw the letters in
"libVLC". Its Latin sibling is a separate download from the same family.
Satori is stricter still: it picks a face per glyph and does not fall back
when that face lacks one. An Arabic label against a Latin-only font set
throws, and the route returns a 500.
At build time, treat fonts as ordered stacks and pick per run. Ask each face
what it covers rather than trusting its name:
```js
export function loadFace(sfnt) {
const face = new Face(new Blob(sfnt), 0);
const font = new Font(face);
font.setScale(face.upem, face.upem);
return { font, upem: face.upem, covers: new Set(face.collectUnicodes()) };
}
const faceFor = (stack, codePoint) =>
stack.find((face) => face.covers.has(codePoint)) ?? stack[0];
```
`collectUnicodes` reads the cmap, so this is what the file can draw. Put the
Arabic face first and its Latin companion behind it, and a Latin word inside
an Arabic sentence keeps the same typeface instead of changing voice mid-line.
At the edge, fall back for the whole string rather than the missing letters.
Satori substitutes per glyph, and a name with three letters in another
typeface reads as a fault rather than a choice. That rule also decides the
Kurdish card: the Arabic face has no Ç, ç, ê, î, û or ş, which is most Kurdish
words, so it is set in the Latin face throughout.
### Joining and measurement
Arabic is cursive: a letter's shape depends on its neighbors, and the joined
forms are narrower than the isolated ones.
Satori picks the right forms. It gets the measurement wrong. A word's box is
sized from the isolated advances and drawn with the joined ones, so every box
carries the difference as dead space at its end.
Across the Unblock Syria catalog the median word loses 0.91em and the worst
loses 3.49em. On a 52px title that is a 47px gap and a 181px one. The second
is about a fifth of the text column, opening up in the middle of a name.
Seventeen words go the other way and are drawn *wider* than their box, because
a few letters have a final form broader than the isolated one. An error that
changes sign cannot be canceled with a constant. So compute the width per word
from the font's metrics and set it on the box. Generate the metrics table from
the embedded font, and have a test re-derive it from the same bytes, or a font
swap will leave a stale table behind.
One wrong fix deserves a name, because it looks right and then fails quietly.
Pre-shaping means replacing each letter with the presentation form its
position calls for, then handing the renderer the result in visual order. The
renderer orders it a second time, and the forms no longer match the positions.
التجاري came out التجاير.
Look at what happened. The last two letters swapped, and they are exactly the
two a non-joining letter had separated. Rāʾ does not join forward, so التجاري
draws as four pieces — ا, لتجا, ر, ي — the last two being single letters side
by side. Reorder the pieces and ي lands before ر.
Then the damage hides itself. Yāʾ *does* join forward, so the swapped pair
connects into ير and the word comes out as a well-formed Arabic shape. Nothing
throws. Every glyph is a real letter. The joins all look right. Only someone
who reads the script will notice the word is now a different one.
The neutrals are the same problem one level down. A digit, a colon or a
bracket attached to an Arabic word is not an Arabic character. A renderer with
no bidi draws it in logical order, on the wrong side of the word: the colon
belongs to the left of ليجندز, not the right. Brackets also have to be
mirrored in an RTL context. Unicode specifies that; satori does not do it, so
"جو (جولانج)" came out with its brackets pointing outward.
None of this arises at build time. HarfBuzz shapes each run, every glyph goes
out as a ``, and the rasterizer fills vectors without running its text
engine. That removes its font-fallback bug too.
```js
// A right-to-left line starts at the right edge, so the pen begins a full
// line-width left of it. Get this wrong and correct Arabic lands in the
// wrong half of the card.
let pen = dir === "rtl" ? x - measure(text, { stack, size }) : x;
for (const run of reorder(logicalRuns(text, stack, dir))) {
const scale = size / run.face.upem;
for (const glyph of shapeRun(run)) {
const d = run.face.font.glyphToPath(glyph.codepoint);
if (d) {
const gx = pen + glyph.xOffset * scale;
const gy = y - glyph.yOffset * scale;
// Flipped in y: font units go up, SVG goes down.
parts.push(
``,
);
}
pen += glyph.xAdvance * scale;
}
}
```
### Setting Arabic, once it draws correctly
The last part is not a bug, but the card is wrong without it. Tracking and
capitals are Latin devices. Arabic is joined, so letter-spacing severs the
joins, and there are no capitals to raise. The Arabic kicker is simply set, at
a size that balances the English one.
Arabic also sets smaller and looser: 58/52/46 against 64/57/50 for the title,
leading 1.52 against 1.22. Its ascenders and descenders reach further, and
lines set at Latin leading collide.
## Mistakes that are easy to make
The ordinary ones first, none of which are about text at all:
- **Meta tags injected on the client.** Crawlers do not run your JavaScript. If
a framework helper adds the tags after hydration, the crawler sees an empty
shell. They belong in the HTML the server sends.
- **A relative `og:image`.** The most common one. Some unfurlers resolve it,
some show no image.
- **WebP or AVIF.** Support across unfurlers is uneven in a way it is not in
browsers. Use PNG or JPEG.
- **Two sets of tags.** A CMS and a theme each emitting an `og:image` is a coin
flip over which wins.
- **Bot protection.** The crawler is a bot, and a default challenge rule blocks
it. If the page renders for you but the preview is empty, fetch the image URL
with the platform's user agent first.
- **A cache, not a bug.** A preview that was right and now is not is almost
always cached. Re-scrape from the platform's debugger instead of
redeploying.
- **A query string in the image path.** Derive the card URL from the canonical
path and clear the search first. Appending to `/articles?page=2` puts the
suffix inside the query *value*, and every crawler past page one gets the
HTML page where it expected a PNG.
- **`opengraph-image` as a usable slug.** Reserve it. A framework that resolves
a static segment before the dynamic one beside it lets a row slugged that
shadow its own collection's card.
- **Advertising a card you never drew.** A route rendered per request has no
built HTML for a build-time script to read. Check at the end of the run that
every advertised card exists on disk.
Then the Arabic ones. They share one property: if you do not read the script,
the output of every one of them looks fine.
- **Reversing the string.** Reversing code points is not right-to-left
rendering. It puts visual order in a field meant to hold logical order, so
search, copy-paste and screen readers break. And anything downstream that
orders text will reverse it back.
- **Writing presentation forms into your data.** The U+FE70–FEFF block is there
for round-trip compatibility with legacy encodings —
[Unicode says so on the chart](https://www.unicode.org/charts/PDF/UFE70.pdf).
Used as a shaping fix it is the pre-shaping trap above.
- **Treating `text-align: right` as RTL support.** Alignment is not ordering.
Ordering is not shaping. Fixing one does nothing for the other two.
- **Tracking, uppercase, small caps.** Latin devices, all three. Letter-spacing
severs the joins and turns a word into a row of letters.
- **Testing with Arabic alone.** The one that gets everybody. A line with no
Latin, no digits and no punctuation renders correctly under almost every
broken implementation, because the shaper infers direction from the script.
Put a product name and a version number in your test string.
The first four, as code:
```js
// Don't: none of these is right-to-left support.
const visual = [...name].reverse().join(""); // breaks search and copy
const shaped = toPresentationForms(name); // legacy compatibility block
element.style.textAlign = "right"; // alignment, not ordering
element.style.letterSpacing = "0.08em"; // severs the joins
// Do: keep the string in logical order and let the layer that draws it
// resolve direction, shaping and face — then check the result.
const runs = reorder(logicalRuns(name, stack, "rtl"));
```
And the test string, the cheapest fix here by far:
```js
// Renders correctly under almost every broken implementation.
const bad = "ربط المكتبة مباشرة";
// Exercises ordering, face selection and neutrals at once.
const good = "ربط libVLC مباشرةً من Swift 6 — إصدار 3.0.21";
```
## Checking it
Bidi cannot be checked by looking, unless you read the script. A reversed line
of Arabic still looks like Arabic.
So fingerprint it instead. Render a fixture, take the column-wise ink profile,
and segment it into words on a run of clear pixels. It never looks at the
text:
```js
async function fingerprint(png, gap) {
const { data, info } = await sharp(png).greyscale().raw()
.toBuffer({ resolveWithObject: true });
const widths = [];
let start = -1, blank = 0;
for (let x = 0; x < info.width; x++) {
let inked = false;
for (let y = 0; y < info.height; y++) {
if (data[y * info.width + x] < 128) { inked = true; break; }
}
if (inked) { if (start === -1) start = x; blank = 0; }
else if (start !== -1 && ++blank >= gap) {
widths.push(x - blank + 1 - start);
start = -1; blank = 0;
}
}
if (start !== -1) widths.push(info.width - 1 - start);
return widths;
}
```
Compare that sequence against a reference from a browser laying out the same
string, same size, same face. A run in the wrong order changes the sequence. A
glyph that fails to shape changes its length. Store the browser's numbers as
fixtures, allow a pixel or two, and fail the build on a mismatch. Nobody
running it has to read a word.
For the tags themselves, the platform validators are still the fastest check.
Run them once per card design, not once per post.
A card generator is a text layout engine with one customer. Ordering, shaping,
face selection, measurement — a browser does all of it for you, everywhere
except the one image you ship that no browser renders. Latin-only pages never
touch two thirds of this. The rest of us meet it in roughly the order the bugs
arrive.
Found a renderer or an Arabic text case that behaves differently? [Send me the
example](/en/contact); I'd like to compare approaches. Share the guide with
whoever maintains your site's previews, particularly if they only test in
English.
---
# معاينات الروابط بنص عربي سليم
- URL: https://omaralbeik.com/ar/blog/link-previews-that-work-in-arabic
- Markdown: https://omaralbeik.com/ar/blog/link-previews-that-work-in-arabic.md
- Translation: https://omaralbeik.com/en/blog/link-previews-that-work-in-arabic
- Author: Omar Albeik
- Language: ar
- Type: tutorial
- Date: 31 آب 2026
- Topics: typography, tooling, software, engineering
تعرض معاينة الرابط صورة يجلبها تطبيق المحادثة أو منصة التواصل من العنوان
المحدد في `og:image`. تحتفظ المنصة بنسخة منها لتعرضها مع الرابط لاحقًا. لذلك
ينبغي أن تكون الصورة جاهزة بما فيها النص والخطوط؛ عرض المعاينة لا يعتمد على
تنسيق الصفحة في متصفحك.
تستخدم مواقع كثيرة صورة واحدة لكل روابطها. تساعد هذه الصورة على التعرف إلى
الموقع، لكنها لا تقول الكثير عن الصفحة المقصودة. عندما تولّد بطاقة لكل صفحة،
تستطيع وضع عنوانها ووصفها في المعاينة، فيعرف القارئ ما الذي سيفتحه.
أستخدم طريقتين لتوليد البطاقات في موقعيّ. في omaralbeik.com، يولّدها سكربت
Node عند بناء الموقع. وفي unblocksyria.com، تُولّد عند الطلب على Cloudflare
Workers. الموقعان بالعربية والإنجليزية، ومعظم العمل الإضافي كان في عرض النص
العربي بصورة صحيحة.
## قبل أن تبدأ
- ولّد بطاقة لكل صفحة، وحدد في `og:image` عنوانًا مطلقًا للصورة، مع أبعادها
ونصها البديل ووسم `twitter:card`.
- ولّد الصور وقت البناء إذا كان محتواها لا يتغير بين عمليتي نشر.
- ضمّن ملفات الخطوط، وتحقق من الصيغ التي يدعمها محرّك الرسم.
- حدد أولوية العنوان والوصف وحجم الخط عندما لا تتسع المساحة للجميع.
- جهّز صورة بديلة يعيدها المسار إذا فشل توليد البطاقة.
- افحص ترتيب النص العربي، واختيار الخط، ووصل الحروف وقياسها كلًا على حدة.
استخدم عينة فيها أسماء لاتينية وأرقام، فقد تخفي العينة العربية وحدها بعض الأخطاء.
- قارن ترتيب النص بمرجع موثوق ضمن الاختبارات.
## الوسوم، باختصار
```html
```
استخدم عنوانًا مطلقًا للصورة، يتضمن البروتوكول والنطاق، حتى لا تعتمد على طريقة
تعامل كل منصة مع العناوين النسبية. واضبط `twitter:card` على
`summary_large_image` لطلب معاينة كبيرة. تحتاج الصفحة أيضًا إلى `og:title`
و`og:description` و`og:url` و`og:type`.
أستخدم صورًا بقياس 1200×630. قد تقص المنصات الصورة بنسب مختلفة؛ قصّتها X إلى
16:9 في اختباراتي. لذلك أترك هامشًا حول النص، بلغ 96 بكسلًا بعد تجربة عدة
معاينات. القياس وحده لا يخبرك بالمساحة التي ستظل ظاهرة بعد القص.
## أين تُرسم البطاقة
يتوقف الاختيار على سؤال: هل يمكن أن يتغير محتوى البطاقة دون إعادة نشر الموقع؟
إذا كان المحتوى ثابتًا بين عمليتي نشر، فالتوليد وقت البناء مناسب. لا تحتاج إلى
توليد الصورة أثناء طلب المستخدم، ويمكنك استخدام أي برنامج يلائم المهمة. في
omaralbeik.com، يعمل سكربت Node بعد البناء، ويقرأ العنوان والوصف من ``
في كل صفحة. بذلك تستخدم البطاقة البيانات نفسها التي تعلنها الصفحة.
```json
"build": "astro build && node scripts/og-render.mjs"
```
وضعت السكربت خارج إطار العمل عن قصد. مع محوّل Cloudflare، يولّد Astro الصفحات
مسبقًا داخل workerd. أما تحميل ملفات الخطوط وتشغيل مكتبة الرسم الأصلية في هذه
الطريقة، فيحتاجان إلى بيئة Node التي يعمل فيها السكربت.
إذا كان المحتوى يتغير دون نشر جديد، فالتوليد عند الطلب أنسب. تعرض بطاقة الخدمة
في unblocksyria.com حالة الحجب وآخر تقدم في المراسلات. قد تتغير المعلومتان في
أي وقت، بينما تحتفظ الصورة المولّدة وقت البناء بحالتهما يوم النشر.
أستخدم هنا `ImageResponse` من `next/og`، حيث يتولى satori ترتيب العناصر قبل
تحويلها إلى صورة. أضمّن ملفات الخطوط في حزمة التطبيق بترميز base64: وزنين من
الخط اللاتيني ووزنين من الخط العربي. حجم الملفات 129 كيلوبايت، ويصبح 172
كيلوبايت بعد الترميز. أحتاج العائلتين في كل بطاقة، لأن البطاقة العربية قد
تتضمن اسمًا لاتينيًا، والعكس صحيح.
استخدم WOFF في هذا المسار. لا يقرأ satori ملفات WOFF2، ومحاولة تحميلها ترمي
استثناءً بدل استخدام خط بديل.
## كلّ مسارٍ ينتهي بصورة
إذا أعاد عنوان `og:image` خطأ 500، فقد تظهر المعاينة بلا صورة. لا تعتمد على أن
المنصة ستبحث بنفسها عن صورة افتراضية للموقع.
جهّز صورة بديلة داخل مسار توليد البطاقة، وانتبه إلى موضع الخطأ: يعود `new
ImageResponse(...)` قبل اكتمال الرسم. يحدث الرسم الفعلي عند `arrayBuffer()`،
لذلك يجب أن يكون هذا الاستدعاء داخل `try`.
```ts
export function renderCard(element: ReactElement): Promise {
return new ImageResponse(element, { width: OG_WIDTH, height: OG_HEIGHT, fonts })
.arrayBuffer();
}
```
جرّب البطاقة كاملة أولًا. إذا فشلت، أعد المحاولة دون الشعار الذي يُجلب من مصدر
خارجي. وإذا فشلت أيضًا، اعرض بطاقة عامة لا تعتمد على بيانات الصفحة.
يمكن تخزين استجابة المعرّف غير الموجود مؤقتًا، لكن تجنب تخزين أخطاء 5xx. وإلا
فقد تبقى البطاقة العامة مرتبطة بصفحة سليمة طوال مدة `stale-while-revalidate`،
حتى بعد زوال الخطأ.
## ضبط النصّ في مساحته
بعد الحصول على قياس صحيح للنص، يمكن تقسيمه إلى أسطر، وتحديد عددها، وإضافة
علامة الحذف إذا بقي نص لا يتسع. تحتاج الكلمات التي تتجاوز عرض العمود إلى تقسيم
داخلي أيضًا. المشكلة الأصعب هي تقدير الحجم قبل القياس.
عندما ربطت حجم العنوان بعدد حروفه، اختلف التقدير كثيرًا بين العربية
والإنجليزية. ظهر «المرصد الأورومتوسطي لرصد الزلازل» بحجم 28 بكسلًا، بينما ظهر
«EMSC» بحجم 104، رغم أن كليهما اسم الجهة نفسها في بطاقات Unblock Syria.
وفي هذا التنفيذ، يحتاج satori إلى حساب صريح لعدد الأسطر وارتفاع كتلة النص، حتى
لا يمتد العنوان إلى العناصر التي تحته.
قد لا تتسع البطاقة لعنوان من ثلاثة أسطر ووصف من سطرين بالحجم المطلوب. حدد ما
تريد الحفاظ عليه أولًا. هنا أحاول إبقاء الوصف كاملًا، ثم الحفاظ على العنوان
دون اختصار، وأصغّر الخط عند الحاجة:
```js
for (const descLines of card.description ? [2, 1, 0] : [0]) {
for (const size of [64, 57, 50]) {
const block = layout(card, { size, descLines });
if (block.height <= BAND) return block; // يفوز أوّل ما يتّسع
}
}
```
ترتيب الحلقتين يحدد هذه الأولوية: نجرب أحجام الخط الثلاثة مع سطرين للوصف، ثم
نجربها مع سطر واحد، وأخيرًا دون وصف. أي أننا نصغّر الخط قبل حذف سطر من الوصف.
يحافظ ذلك على المعلومات التي يضيفها الوصف إلى العنوان.
## من اليمين إلى اليسار
عرض العربية من اليمين إلى اليسار يتطلب معالجة ثلاث مسائل منفصلة: ترتيب
المقاطع، واختيار الخط المناسب، ووصل الحروف وقياسها. نجاح واحدة لا يضمن نجاح
البقية.
### ترتيب الكلمات
في الاختبارات هنا، لم يؤثر تغيير `direction` و`unicode-bidi` في خرج resvg؛ بقي
مطابقًا بايتًا ببايت مع `embed` و`isolate` و`plaintext`. لم أستطع إذن إصلاح
ترتيب النص بهذه الخصائص. وفي مسار satori، ظهرت مشكلة ترتيب الكلمات من اليسار
إلى اليمين أيضًا.
يصعب ملاحظة المشكلة عند اختبار نص عربي فقط. يستنتج HarfBuzz الاتجاه من الحروف،
وقد يبدو السطر صحيحًا. يظهر الخلل عندما تضيف اسم منتج لاتينيًا أو رقم إصدار،
وهو أمر متكرر في موقع عن البرمجة.
في التوليد وقت البناء، استخدمت bidi-js لحساب مستويات الاتجاه. نقسّم النص إلى
أسطر وهو في ترتيبه المنطقي، ثم نعيد ترتيب مقاطع كل سطر للعرض. تطبق القاعدة L2
ذلك بدءًا من أعلى مستوى تضمين وصولًا إلى أدنى مستوى فردي، وتعكس المقاطع
المتجاورة التي تقع عند المستوى الحالي أو فوقه.
نبدأ بمقاطع يمكن إرسال كل منها إلى محرّك تشكيل الحروف (shaper) دفعة واحدة.
يجمع المقطع حروفًا تشترك في مستوى الاتجاه والخط:
```js
const bidi = bidiFactory();
function logicalRuns(text, stack, baseDir) {
const { levels } = bidi.getEmbeddingLevels(text, baseDir);
const runs = [];
for (let i = 0; i < text.length; ) {
const char = String.fromCodePoint(text.codePointAt(i));
const level = levels[i];
const face = faceFor(stack, text.codePointAt(i));
const last = runs[runs.length - 1];
if (last && last.level === level && last.face === face) last.text += char;
else runs.push({ level, face, text: char });
i += char.length;
}
return runs;
}
```
ثم نطبّق القاعدة L2 لإعادة ترتيب المقاطع:
```js
function reorder(runs) {
const levels = runs.map((r) => r.level);
const highest = Math.max(...levels);
const odd = levels.filter((l) => l % 2 === 1);
const lowestOdd = odd.length ? Math.min(...odd) : highest + 1;
const out = [...runs];
for (let level = highest; level >= lowestOdd; level--) {
for (let start = 0; start < out.length; start++) {
if (out[start].level < level) continue;
let end = start;
while (end + 1 < out.length && out[end + 1].level >= level) end++;
out.splice(start, end - start + 1, ...out.slice(start, end + 1).reverse());
start = end;
}
}
return out;
}
```
بعد ذلك نحدد أشكال الحروف داخل كل مقطع:
```js
function shapeRun(run) {
const buffer = new HbBuffer();
buffer.addText(run.text);
buffer.guessSegmentProperties();
buffer.setDirection(run.level % 2 === 1 ? Direction.RTL : Direction.LTR);
shape(run.face.font, buffer);
return buffer.getGlyphInfosAndPositions();
}
```
استدعِ `guessSegmentProperties()` أولًا لاختيار نظام الكتابة واللغة، ثم عيّن
الاتجاه صراحة. عكس هذا الترتيب قد يجعل المحرّك يستبدل اتجاهك باتجاه يستنتجه من
الحروف. وانتبه إلى نوع الوسيط: الاتجاه قيمة من تعداد رقمي. تمرير النص `"rtl"`
في هذا المسار يعطي `INVALID` دون تنبيه، وقد تصبح قياسات التقدم الأفقي صفرًا.
في مسار التوليد على Workers، أستخدم `row-reverse` لترتيب المقاطع الاتجاهية.
يجب أن يبقى ترتيب الكلمات داخل المقطع اللاتيني كما هو. عكس الكلمات المفصولة
بالمسافات واحدة واحدة قد يحوّل «Google Play» إلى «Play Google» داخل الجملة
العربية.
### اختيار الخط لكل مقطع
تظهر المربعات الفارغة عندما لا يحتوي الخط المختار على الحروف المطلوبة، ولا
ينتقل محرّك الرسم إلى خط آخر يوفرها.
يوفر Fontsource ملفات منفصلة بحسب مجموعة المحارف. تحميل ملف العربية من IBM
Plex Sans Arabic لا يعني أنك حمّلت الحروف اللازمة لكتابة «libVLC»؛ تحتاج إلى
الملف اللاتيني أيضًا. وفي مسار satori الذي أستخدمه، قد يؤدي غياب الحروف من
الخط المختار إلى استثناء واستجابة 500.
احتفظ بقائمة مرتبة من الخطوط، واختر لكل مقطع خطًا يحتوي على حروفه. افحص
المحارف التي يدعمها الملف بدل الاعتماد على اسم العائلة:
```js
export function loadFace(sfnt) {
const face = new Face(new Blob(sfnt), 0);
const font = new Font(face);
font.setScale(face.upem, face.upem);
return { font, upem: face.upem, covers: new Set(face.collectUnicodes()) };
}
const faceFor = (stack, codePoint) =>
stack.find((face) => face.covers.has(codePoint)) ?? stack[0];
```
تقرأ `collectUnicodes` جدول cmap لمعرفة المحارف الموجودة في ملف الخط. عندما
يكون الملف العربي أولًا والملف اللاتيني من العائلة نفسها ثانيًا، يبقى شكل النص
متناسقًا عند الانتقال بين اللغتين.
في مسار satori، أختار الخط البديل للنص كاملًا عندما يلزم، حتى لا تظهر بضعة
حروف بخط مختلف وسط الاسم. لهذا أستخدم الخط اللاتيني للبطاقات الكردية: حروف مثل
Ç وç وê وî وû وş غير موجودة في الملف العربي المستخدم هنا.
### الوصل والقياس
يتغير شكل الحرف العربي بحسب موضعه واتصاله بما حوله. وفي الخط المستخدم هنا،
تكون كثير من الكلمات بعد وصل حروفها أضيق من مجموع عروض الحروف المنفصلة.
يرسم satori الحروف متصلة، لكنه يحسب صندوق الكلمة من عروضها المنفصلة. يبقى
الفرق بين القياسين فراغًا زائدًا عند طرف الصندوق.
في أسماء الخدمات العربية في فهرس Unblock Syria، بلغ وسيط الفراغ الزائد 0.91em،
ووصل أكبر فرق إلى 3.49em. عند حجم خط 52 بكسلًا، يعادل ذلك نحو 47 و181 بكسلًا؛
أي أن الخطأ قد يترك فجوة كبيرة داخل الاسم.
لكن سبع عشرة كلمة كانت أعرض من صناديقها، لأن الشكل النهائي لبعض الحروف أعرض من
المنفصل. لذلك لا يصلح ضرب جميع القياسات في معامل تصحيح واحد. حسبت عرض كل كلمة
من مقاييس الخط، وولّدت جدول القياسات من ملف الخط المضمّن. ويعيد اختبار اشتقاق
الجدول من الملف نفسه، حتى لا نستبدل الخط ونترك قياسات النسخة القديمة.
جرّبت أيضًا التشكيل المسبق: استبدال الحروف بأشكالها المناسبة لمواضعها، ثم
إرسال النص بالترتيب البصري. لكن المحرّك أعاد ترتيبه مرة أخرى، فلم تعد الأشكال
المختارة تطابق المواضع الجديدة. هكذا ظهرت «التجاري» على هيئة «التجاير».
تبادل الحرفان الأخيران موضعيهما. الراء لا تتصل بما بعدها، ولذلك تتوزع
«التجاري» على أربعة مقاطع: ا، لتجا، ر، ي. عند إعادة ترتيب المقطعين الأخيرين،
سبقت الياء الراء.
المربك أن الياء تتصل بالراء بعدها، فتظهر «ير» متصلة. لا توجد حروف مفقودة أو
استثناءات، وقد يبدو الرسم سليمًا لمن لا يقرأ العربية. لكنه يعرض الكلمة بترتيب
خاطئ.
وتحتاج الأرقام وعلامات الترقيم إلى معالجة أيضًا. قد يضعها المحرّك في الجانب
الخطأ من الكلمة إذا لم يطبق قواعد الاتجاهين. مثلًا، يجب أن تأتي النقطتان إلى
يسار «ليجندز» في هذا السياق. والأقواس تتطلب عكس أشكالها عند العرض من اليمين
إلى اليسار؛ بدون ذلك ظهرت أقواس «جو (جولانج)» متجهة إلى الخارج.
في مسار البناء، يتولى HarfBuzz تشكيل المقاطع، ثم أحوّل كل شكل إلى ``.
يرسم resvg هذه المسارات دون استخدام محرّك النص الخاص به. وبذلك أتحكم في
الترتيب واختيار الخط قبل تحويل الرسم إلى صورة.
```js
// السطر اليمينيّ يبدأ من الحافّة اليمنى، فيبدأ القلم على بُعد عرض السطر كلّه
// إلى يسارها. أخطئ هذا تحطّ عربيّةٌ صحيحة في النصف الخطأ من البطاقة.
let pen = dir === "rtl" ? x - measure(text, { stack, size }) : x;
for (const run of reorder(logicalRuns(text, stack, dir))) {
const scale = size / run.face.upem;
for (const glyph of shapeRun(run)) {
const d = run.face.font.glyphToPath(glyph.codepoint);
if (d) {
const gx = pen + glyph.xOffset * scale;
const gy = y - glyph.yOffset * scale;
// مقلوبٌ في المحور الرأسيّ: وحدات الخطّ تصعد، وSVG ينزل.
parts.push(
``,
);
}
pen += glyph.xAdvance * scale;
}
}
```
### مراجعة التصميم بعد تصحيح النص
بعد تصحيح النص، راجع التصميم نفسه. العربية لا تحتوي على حروف كبيرة وصغيرة،
وزيادة المسافات بين الحروف قد تفصل ما يجب أن يتصل. لذلك أستخدم تنسيقًا أبسط
للعناوين الصغيرة في البطاقة العربية، بحجم يوازن النسخة الإنجليزية.
اخترت للعناوين العربية أحجامًا أصغر ومسافات أكبر بين الأسطر: 58 و52 و46
بكسلًا، مقابل 64 و57 و50 للإنجليزية، وتباعدًا قدره 1.52 مقابل 1.22. تحتاج
صواعد الحروف ونوازلها والتشكيل في هذا الخط إلى مساحة رأسية أكبر.
## أخطاء شائعة
تبدأ بعض المشكلات قبل أن يصل محرّك الرسم إلى النص:
- **إضافة الوسوم في المتصفح فقط.** لا تعتمد على أن برامج جلب المعاينات ستشغّل
JavaScript. أرسل الوسوم ضمن HTML الصفحة من الخادم.
- **عنوان صورة نسبي.** استخدم عنوانًا كاملًا، حتى لا تختلف النتيجة بحسب طريقة
معالجة المنصة للمسارات النسبية.
- **صيغ الصور.** اختر PNG أو JPEG لتوافق أوسع بين المنصات؛ دعم المتصفح لـ WebP
أو AVIF لا يضمن دعمها في معاينة الرابط.
- **تكرار `og:image`.** قد يضيف القالب ونظام المحتوى الوسم نفسه. افحص HTML
الناتج وتأكد من أنه يحدد الصورة المطلوبة.
- **حجب برنامج جلب المعاينات.** قد تمنعه قواعد مكافحة البوتات من الوصول إلى
الصورة. جرّب طلب عنوانها باستخدام ترويسة `User-Agent` الخاصة بالمنصة.
- **بقاء نسخة قديمة في الذاكرة المؤقتة.** اطلب تحديث المعاينة من أداة المنصة
قبل إعادة نشر الموقع بحثًا عن خطأ لم يعد موجودًا.
- **إلحاق مسار الصورة بعد معاملات الاستعلام.** اشتق العنوان من مسار الصفحة
دون الاستعلام. إذا أضفت اللاحقة إلى `/articles?page=2`، فستصبح جزءًا من قيمة
`page`، وقد يصل برنامج المعاينة إلى HTML بدل الصورة.
- **تعارض المعرّفات مع `opengraph-image`.** احجز هذا الاسم إذا كان إطار العمل
يستخدمه لمسار الصورة. وإلا فقد يحجب المسار الثابت صفحة سجل تحمل المعرّف نفسه.
- **الإعلان عن صورة لم تُولّد.** الصفحات التي تُعرض عند الطلب قد لا تترك ملفات
HTML يقرأها سكربت البناء. تحقق من وجود الصور التي يفترض توليدها وقت البناء،
واختبر مسارات الصور التي تُولّد عند الطلب منفصلة.
وفي العربية، قد يبدو السطر سليمًا مع أن ترتيب كلماته خاطئ. انتبه إلى الآتي:
- **عكس النص المخزّن.** احتفظ بالحروف في ترتيب القراءة المنطقي، ودع مرحلة العرض
تحدد مواضعها. عكس السلسلة نفسها يربك البحث والنسخ وقارئات الشاشة.
- **تخزين أشكال الحروف بدل الحروف الأصلية.** خُصصت كتلة U+FE70–FEFF للتوافق مع
الترميزات القديمة، كما يوضح
[جدول Unicode](https://www.unicode.org/charts/PDF/UFE70.pdf). استخدامها لتجاوز
محرّك التشكيل قد يؤدي إلى إعادة ترتيب النص بعد اختيار أشكال حروفه.
- **الاكتفاء بـ `text-align: right`.** تضبط هذه الخاصية المحاذاة، لكنها لا
تعالج ترتيب المقاطع أو وصل الحروف.
- **نقل تنسيق العناوين اللاتينية كما هو.** لا توجد حروف عربية كبيرة وصغيرة،
وزيادة المسافات بين الحروف قد تفصل حروف الكلمة.
- **اختبار نص عربي فقط.** أضف اسم منتج لاتينيًا ورقم إصدار وعلامات ترقيم،
لتختبر انتقال الاتجاه واختيار الخط أيضًا.
هذه أمثلة على الحلول التي يجب تجنبها، وعلى فصل ترتيب المقاطع عن البيانات
الأصلية:
```js
// لا تفعل: ليس شيءٌ من هذه دعمًا لليمين إلى اليسار.
const visual = [...name].reverse().join(""); // يكسر البحث والنسخ
const shaped = toPresentationForms(name); // كتلة توافقٍ قديمة
element.style.textAlign = "right"; // محاذاة، لا ترتيب
element.style.letterSpacing = "0.08em"; // يقطع الوصل
// افعل: أبقِ السلسلة بالترتيب المنطقيّ، ودع الطبقة التي ترسمها تحلّ
// الاتّجاه والتشكيل والوجه — ثمّ تحقّق من النتيجة.
const runs = reorder(logicalRuns(name, stack, "rtl"));
```
واختر عينة الاختبار بعناية:
```js
// تخرج صحيحةً مهما يكن الخلل تحتها.
const bad = "ربط المكتبة مباشرة";
// تمتحن الترتيب واختيار الوجه والمحايدات معًا.
const good = "ربط libVLC مباشرةً من Swift 6 — إصدار 3.0.21";
```
## كيف تتحقّق ممّا لا تراه
قد يبدو السطر العربي مقبولًا لمن لا يقرأه حتى عندما تكون كلماته معكوسة. لذلك
يحتاج فحص الترتيب إلى مرجع موثوق.
يمكن استخراج بصمة بسيطة من الصورة: نفحص أعمدة البكسلات، ونحدد المناطق التي
تحتوي على حروف، ونفصل بينها عند وجود فراغ كافٍ. نحصل بذلك على تسلسل من العروض
يمكن مقارنته بالمرجع:
```js
async function fingerprint(png, gap) {
const { data, info } = await sharp(png).greyscale().raw()
.toBuffer({ resolveWithObject: true });
const widths = [];
let start = -1, blank = 0;
for (let x = 0; x < info.width; x++) {
let inked = false;
for (let y = 0; y < info.height; y++) {
if (data[y * info.width + x] < 128) { inked = true; break; }
}
if (inked) { if (start === -1) start = x; blank = 0; }
else if (start !== -1 && ++blank >= gap) {
widths.push(x - blank + 1 - start);
start = -1; blank = 0;
}
}
if (start !== -1) widths.push(info.width - 1 - start);
return widths;
}
```
ولّد المرجع بمتصفح يعرض النص نفسه بالحجم والخط نفسيهما. تغيير ترتيب المقاطع
يغيّر تسلسل العروض، وقد يغيّره أيضًا خطأ في تشكيل الحروف. احفظ القياسات
المرجعية ضمن الاختبارات، واسمح بفارق بكسل أو اثنين. عند تجاوز الفارق، يفشل
الاختبار دون أن يحتاج من يشغّله إلى قراءة النص.
لفحص الوسوم، استخدم أدوات التحقق لدى المنصات. اختبر كل تصميم للبطاقة، لا كل
مقالة على حدة.
استغرق عرض العربية معظم العمل لأن مولّد البطاقات احتاج إلى تنفيذ أمور يتولاها
المتصفح عادة: ترتيب المقاطع، واختيار الخط، ووصل الحروف، وقياسها. فصل هذه
المهام جعل تشخيص الأخطاء أسهل. عندما تظهر بطاقة غير صحيحة الآن، أستطيع تحديد
المرحلة التي أراجعها بدل تعديل المحاذاة وانتظار نتيجة مختلفة.
هل وجدت محرّك رسم أو مثالًا عربيًا يتصرف بصورة مختلفة؟ [أرسل لي
المثال](/ar/contact)، لنتبادل طرق المعالجة. وشارك الدليل مع من يتولى معاينات
الروابط في موقعك، خصوصًا إذا كانت اختباراته تقتصر على الإنجليزية.
---
# Syria is off the list
- URL: https://omaralbeik.com/en/blog/syria-is-off-the-list
- Markdown: https://omaralbeik.com/en/blog/syria-is-off-the-list.md
- Translation: https://omaralbeik.com/ar/blog/syria-is-off-the-list
- Author: Omar Albeik
- Language: en
- Type: note
- Date: 26 August 2026
- Topics: syria, politics
I spent last week writing a few thousand careful words for Unblock Syria
about why this wouldn't change anything on its own. Then Monday came and I
sat there grinning at my laptop like an idiot.
Both are true. The careful version is
[over there](https://unblocksyria.com/en/articles/syria-sst-removal-what-it-changes)
and I stand behind it. This is the other one.
On Monday the State Department took Syria off the list of state sponsors of
terrorism.
Syria went on that list in 1979, which is the year the list started existing.
It wasn't added to something. It was one of the four names that made the
thing a thing, along with Libya, Iraq and South Yemen. Iraq came off in 2004.
Libya in 2006. South Yemen stopped being a country. Syria stayed, through
Hafez, through Bashar, through the war, and was still there on Sunday.
I have never been alive for a day when it wasn't.
I've spent two days trying to work out who to tell. My family knew before I
did. Nobody at work is going to understand why I've reread the same short
press release about nine times. It's good news that doesn't really convert.
And underneath the happy part there's something I wasn't expecting, which is
anger. Forty-six years. All of my life and most of my parents'. Then it ended
with a signature and a clock running out, the way a parking permit expires.
Hafez earned that designation and Bashar spent his entire rule re-earning
it, and the cost of it never landed on either of them for a single day. It
landed on everyone else. Two generations of people who had no say in any of
it paid for what those two men chose to do, and are still paying, and will go
on paying for years after this week.
Bashar is in Moscow. I don't imagine he has any trouble opening an account.
## The word
People assume it was the sanctions. Mostly it wasn't the sanctions. It was
the word.
The word is what a compliance officer sees when they type a country into a
screening tool, and that is the entire mechanism. It's why PayPal wrote back
to us in March, said no, and cited sanctions Congress had already repealed in
December. We pointed that out. They didn't engage with it.
It cost people money. That gets lost when this is argued as a policy
question. Somebody turns down a client because there is no way to be paid.
Somebody can't buy the course. Somebody runs a business for two years through
a friend's account in another country and loses all of it the week the friend
has had enough. Every Syrian I know has built some part of their working life
around this, and most of us stopped bringing it up, because what was anyone
going to do about it.
That part is finished. Not the blocking. The blocking is another year of
emails at least. But there is no longer a reason, and I have wanted to write
that sentence for a long time.
## What happens next
Most of it will be quiet. A company changes one line in a config file and
tells nobody, and someone in Damascus tries again out of habit and it works,
and they assume it always did.
What I want out of this is small and I've said it to about six people this
week. A kid in Aleppo opens a laptop, makes an account, and nothing happens.
No VPN. No cousin in Germany. No workaround to be proud of. A form that just
submits.
Forty-six years for that.
If this brings back an experience of your own, [write to me](/en/contact). And
if someone you know has never understood what these restrictions meant in
daily life, you can share this with them.
---
# سوريا خارج القائمة
- URL: https://omaralbeik.com/ar/blog/syria-is-off-the-list
- Markdown: https://omaralbeik.com/ar/blog/syria-is-off-the-list.md
- Translation: https://omaralbeik.com/en/blog/syria-is-off-the-list
- Author: Omar Albeik
- Language: ar
- Type: note
- Date: 26 آب 2026
- Topics: syria, politics
قضيتُ الأسبوع الماضي أكتب بضعة آلافٍ من الكلمات المتأنّية لـUnblock Syria في
أنّ هذا القرار وحده لن يغيّر شيئًا. ثمّ جاء الاثنين، فجلستُ أبتسم لشاشتي
كالأبله.
ما زلت مقتنعًا بكل ما كتبته في [التحليل
هناك](https://unblocksyria.com/ar/articles/syria-sst-removal-what-it-changes).
لكنني هنا أكتب عن شعوري بالخبر.
يوم الاثنين أخرجت وزارة الخارجيّة الأمريكيّة سوريا من قائمة الدول الراعية
للإرهاب.
دخلت سوريا القائمة سنة 1979، منذ إنشائها، مع ليبيا والعراق واليمن الجنوبي. خرج
العراق سنة 2004، وليبيا سنة 2006، ولم يعد اليمن الجنوبي دولة مستقلة. وبقيت
سوريا: في عهد حافظ، ثم بشار، وطوال الحرب. وحتى يوم الأحد، كان اسمها لا يزال
هناك.
ولم أعش يومًا واحدًا لم تكن فيه هناك.
أمضيت يومين أفكر بمن أخبر. أهلي عرفوا قبلي. وفي العمل، لن يفهم أحد لماذا قرأت
البيان القصير نفسه تسع مرات. يصعب أن أشرح لهم مقدار فرحتي به.
وتحت الفرح شيءٌ لم أتوقّعه، وهو الغضب. ستٌّ وأربعون سنة. عمري كلُّه وأكثر
عمر أهلي. ثمّ انتهى الأمر بتوقيعٍ ومهلةٍ تنقضي، كما تنتهي رخصةُ موقف سيّارة.
استحقّ حافظ اللعين ذلك التصنيف، وقضى بشّار حكمه كلَّه يستحقّه من جديد، ولم تقع
كلفتُه على أيٍّ منهما يومًا واحدًا. وقعت على الباقين. دفع جيلان لا ذنبَ
لهم ثمنَ ما فعله الأبلهان، وما زالوا يدفعون، وسيدفعون سنينَ بعد هذا الأسبوع.
بشّار في موسكو. ولا أظنّه يجد عناءً في فتح حساب.
## الكلمة
يظن الناس أن السبب كان العقوبات. في كثير من الحالات، كانت المشكلة في كلمة
«إرهاب» نفسها.
هذه الكلمة هي ما يظهر لموظف الامتثال حين يبحث عن البلد. ولهذا رفضت PayPal
طلبنا في آذار، مستندة إلى عقوبات كان الكونغرس قد ألغاها في كانون الأول.
نبّهناهم إلى ذلك، ولم يردوا على هذه النقطة.
كلّف هذا الناسَ أموالهم، وهذا أوّل ما يضيع حين يُناقَش الأمر بوصفه مسألةَ
سياسات. يعتذر أحدُهم عن عملٍ لأنّه لا سبيل إلى قبض أجره. ولا يقدر آخر على
شراء دورةٍ تعليميّة. ويبني ثالثٌ رزقه سنتين على حساب صديقٍ في بلدٍ آخر، فيضيع
كلُّه في الأسبوع الذي يملّ فيه الصديق. وما من سوريٍّ أعرفه إلّا وقد رتّب
جزءًا من حياته المهنيّة على هذا، وأكثرنا كفّ عن ذكره؛ فماذا كان بيد أحدٍ أن
يفعل.
زوال التصنيف لا ينهي الحجب؛ أمامنا سنة أخرى من المراسلات على الأقل. لكنه يزيل
الذريعة التي واجهتنا طوال هذا الوقت. انتظرت طويلًا لأكتب هذه الجملة.
## ما سيحدث
ستحدث معظم التغييرات دون إعلان. تعدّل شركة سطرًا في إعداداتها، ثم يحاول شخص في
دمشق فتح حساب كعادته، فينجح هذه المرة. وربما لا يعرف أن شيئًا تغير.
ما أريده بسيط، وقد قلته لستة أشخاص هذا الأسبوع: أن يفتح شاب في حلب حاسوبه
وينشئ حسابًا دون أي مشكلة. بلا VPN، ولا ابن عم في ألمانيا، ولا حيلة يفتخر
باكتشافها. يملأ النموذج ويرسله، وينتهي الأمر.
ستٌّ وأربعون سنةً من أجل هذا.
إذا ذكّرك هذا بتجربة عشتها، [اكتب لي عنها](/ar/contact). وإن كنت تعرف شخصًا لم
يفهم أثر هذه القيود في حياتنا اليومية، فربما تساعده مشاركة المقالة على فهمه.
---
# Why AI gets Arabic calligraphy wrong
- URL: https://omaralbeik.com/en/blog/why-ai-gets-arabic-calligraphy-wrong
- Markdown: https://omaralbeik.com/en/blog/why-ai-gets-arabic-calligraphy-wrong.md
- Translation: https://omaralbeik.com/ar/blog/why-ai-gets-arabic-calligraphy-wrong
- Author: Omar Albeik
- Language: en
- Type: article
- Date: 7 August 2026
- Topics: calligraphy, typography, ai, software, engineering
Type a line of Arabic into any of the calligraphy generators and you get back
something with the correct temperature and no content. The strokes have
weight. The composition stacks the way Thuluth stacks. Somebody who has never
read a word of Arabic would accept it without a second look, and that is
exactly the population it was built for.
Anyone who reads Arabic sees it in under a second. Letters that should have
joined are sitting apart. A ه has taken its initial form in the middle of a
word. The dots have drifted off the letters they belong to and settled
wherever the density looked right. It is not bad calligraphy. Bad calligraphy
is a thing a beginner produces, and it is legible. This is calligraphy-shaped
noise.
I wanted to know why. I build software for a living, and I have spent years
failing to write a decent *alif*, which is enough to know what the craft asks
of you. The explanation I assumed was true turned out to be wrong.
## Not for want of data
My first assumption was the obvious one: Arabic is under-resourced, and the
models will catch up. That was true for a long time. It has stopped being
true, and the numbers now say something stranger.
[Qalam](https://arxiv.org/abs/2407.13559), a vision encoder-decoder trained on
four and a half million manuscript images, reads Arabic handwriting at **0.80%
word error**. [QARI-OCR](https://arxiv.org/abs/2506.02295), a 2B-parameter
Qwen2-VL fine-tune, reads diacritically-rich Arabic print at **6.1% character
error** — with the tashkeel, which is the hard part. Both are open. Both run
on hardware you own.
Three numbers recur below, so it is worth fixing them now. Word error rate is
the share of words a system gets wrong; character error rate the share of
characters, which is the gentler measure since a word can be wrong by one
letter. Exact match is the strict one: the share of images transcribed with
nothing wrong at all.
Then somebody built a benchmark for calligraphy specifically.
[DuwatBench](https://arxiv.org/abs/2601.19898) landed in January, out of
MBZUAI: 1,272 samples across Thuluth, Diwani, Kufic, Naskh, Ruq'ah and
Nasta'liq, with transcriptions, style labels and bounding boxes. Thirteen
models were pointed at it, open and closed, general-purpose and
Arabic-specific.
The best result on the board is Gemini 2.5 Flash, at **45% word error and 42%
exact match**. Across the thirteen models tested, exact match runs from
**zero** to that 42%, and averages **17.9%**. One open model answers hard
images with the word *Allah*, over and over. It has learned that this is a
good bet on Arabic calligraphy, and nothing else about the image in front of
it.
So a system built for Arabic manuscripts reads them at under one per cent word
error, and the best system anyone has pointed at a calligraphic panel gets
45%. Nor is this general-purpose models being asked something outside their
brief. Two of the thirteen were Arabic-specific, and both sit low on the
board: Microsoft's Arabic handwriting TrOCR returns **99.98% word error and
not one exact match** across the entire benchmark. A model built for Arabic
handwriting, handed Arabic handwriting, reading essentially nothing.
I expected the per-style breakdown to be a clean ramp: plain scripts easy,
ornate scripts hard. It is not, and the way it fails to be is the most
interesting thing in the paper.
Kufic being the hardest is not obvious. It is the most geometric of the six,
the one closest to something you could describe with a grid, and it defeats
everything, presumably because that same geometry strips out the redundancy a
reader normally leans on.
The Thuluth result I do not think is a reading result at all. Thuluth is 55%
of this benchmark and the corpus is 44% Qur'anic, so a model with a strong
language prior has a great deal of it effectively memorized, and guessing the
basmala is not the same skill as reading it. This looks at first like a
contradiction with the paper's own summary, which says Naskh and Ruq'ah are
the most accurately recognized styles. It is not. That holds across all
thirteen models averaged together, and the same passage notes separately that
Thuluth and Diwani run substantially higher for the closed-source models in
particular. The Gemini column is the second half of that sentence.
## Not for want of scale
The comfortable next move is to say this is still a data problem, just a
bigger one. A paper from June puts that to rest.
Sana Al-azzawi, Elisa Barney and Marcus Liwicki ran [one model across nine
handwriting datasets](https://arxiv.org/abs/2606.18884) — Arabic, Urdu,
Persian, English, German — holding the architecture fixed and varying only the
script and the volume of training data. The Arabic-script penalty is largest
when data is scarce, narrows as data grows, and then **stops narrowing at a
consistent five to seven character-error points**. Cleaning the annotations
helps and does not close it.
Their diagnosis is the thing you notice within about ten minutes of picking up
a pen. **Around 30% of the substitution errors on Arabic-script data are
confusions between visually similar characters, against about 15% on Latin.**
One group of five letters in this alphabet is told apart by nothing but dots.
Standing alone they differ a little; inside a word they collapse onto the same
stroke and the dots are the whole of what is left. In a Latin alphabet the
letterform carries the identity and the diacritic modifies it. Here the
diacritic *is* the identity, riding on a stroke that means nothing by itself.
Now put that in a Thuluth composition, where the calligrapher moves dots off
their letters to balance the block — a licensed, traditional, expected move
that every trained reader parses without effort because they are reading the
*word*, not the glyph. The model is reading glyphs. It was always reading
glyphs.
If you want the number that makes this unarguable, look at Ajami, the
Arabic-script orthographies of West Africa. The [first HTR dataset for
Fulfulde and Hausa
manuscripts](https://link.springer.com/chapter/10.1007/978-3-032-04627-7_36)
was published in the ICDAR 2025 proceedings. Its authors ran a suite of
Arabic-script recognition models *built for historical manuscripts* over it,
and report **character error rates of 65 to 84%**. Not word error — character
error, the gentler of the two measures. Up to five letters in six wrong, one
letter at a time, by models built for exactly this kind of material. "Arabic
AI" turns out to mean a narrow slice of Arabic.
## What the script is doing
At this point I stopped reading benchmark papers and went back to the script
itself, because the errors had started to look structural rather than
statistical.
Arabic is not a set of glyphs you substitute one for one. A letter takes a
different form depending on whether it begins a word, sits inside it, ends it,
or stands alone. Six letters — ا د ذ ر ز و — refuse to join to whatever
follows them, so a single word breaks into several connected runs. Certain
pairs fuse into ligatures that are not either letter. In the classical styles
the line itself stops being horizontal: Diwani sweeps, Thuluth stacks words
vertically into a block, and where a word sits is a compositional decision
made by a person weighing the whole panel.
None of that is decoration on top of the letters. It *is* the letters. The
script has a grammar, and the grammar is the art.
And the line does not have to be a line. Diwani, the Ottoman chancery hand,
packs its words into a rising sweep and closes the gaps until the block reads
as one mass, a habit traditionally explained as a security measure, since a
text with no room between its words is a text nobody can insert a clause into.
Nasta'liq goes the other way. The name contracts *naskh* and *ta'liq*, and
ta'liq means suspension, which is what the script does: words hang off one
another and descend as the line runs, so a reader tracks a diagonal rather
than a baseline. A layout engine that assumes text sits on a horizontal has
already lost.
A model trained on images of finished calligraphy is being asked to recover
that grammar from its residue. It sees where the ink landed. It never sees the
rule that put it there, or the pen angle, or the order the strokes were made
in, or the fact that the calligrapher moved that dot deliberately. Given
enough examples it learns the texture of the residue, which is precisely what
it then produces.
## The rules were already written down
Here is where I expected to find the gap — some vagueness in the tradition, a
body of knowledge too intuitive to commit to paper — and found close to the
opposite.
The proportions are not taste passed down as vibes. They are a ratio system,
and it was formalized more than a thousand years ago as *al-khaṭṭ al-manṣūb*,
proportioned script, traditionally credited to the Abbasid vizier and
calligrapher Ibn Muqla, who died in 940. It has three units.
That system is why a trained reader can look at a letter and say it is
*incorrect* rather than just unfamiliar: there is a number it failed to meet.
Ibn Muqla is credited with canonizing the six classical pens on the same
basis, and Ibn al-Bawwab and Yaqut al-Musta'simi refined the system after him.
A thousand years before anyone wrote a font engine, this script had a written
specification.
And it did not stop at the letter. Whole page layouts were fixed forms too,
reproduced by generations of calligraphers to the same plan.
That is the tenth century. The modern version is the part that actually
reframed this for me.
[DecoType](https://decotype.com/) was incorporated in 1985 by Peter Somers,
Mirjam Somers and Thomas Milo — Designers of Computer-aided Typography. What
they built was not a glyph set but a font that knew the script's rules and
applied them: their Ruq'ah was the first dynamic Arabic typeface of its kind,
and by the early 1990s it was shipping inside Microsoft Office. The DecoType
Naskh and Thuluth families went out to a generation of Office users under an
"MS Office Edition" label, on licenses dated 1992 to 1998. Whether current
builds still carry them I could not establish.
Underneath sat ACE, the Arabic Calligraphic Engine, built first for Ruq'ah and
then extended across a broad analysis of Naskh, and later renamed the Advanced
Composition Engine as it grew to drive any Arabic typeface.
Milo's [own account of the
model](https://www.academia.edu/2448322/A_model_for_Handling_the_Arabic_Script_2005_)
is explicit about the stakes: ACE approaches Arabic typography in analogy with
*pre-typographic text manufacture*. It encodes the orthographic rules by which
letterform combinations weave into ligature forms. It is a considered
rejection of movable type as a model for this script, a rejection made by
people who went and studied the manuscript tradition first. He took the Peter
Karow Award for it in 2009.
It reached working designers as Tasmeem, the Arabic plug-in for InDesign ME
that DecoType built with WinSoft International, who published it. As far as I
can tell it remains the most structurally faithful Arabic composition system
anyone has shipped.
WinSoft [discontinued it in April
2021](https://winsoft-international.com/tasmeem/) — the product, not DecoType,
whose engine had always been the part underneath. Last release for InDesign CC
2021. Existing clients supported to the end of their subscriptions, no new
sales, no further upgrades. DecoType's own site now reads as an archive; the
most recent thing dated on it is a 2017 lecture.
One of the people who worked on that plug-in is still at it, and what he sells
now is the neatest summary of where this has ended up. Nihad Taisir Nadam —
Damascus-born, Dubai-based — co-developed the first online Arabic digital
calligraphy tool with WinSoft in 2011, alongside Tasmeem itself, and by his
own account has worked with Adobe, WinSoft and DecoType on Arabic font
technology. He now sells [ArabicDesign.ai](https://arabicdesign.ai/en), which
generates calligraphy from typed Arabic in about fifteen styles and exports
SVG.
Read its feature list closely. It offers to *preserve the requested text at up
to 95%*, and to *reduce* common letter and dot mistakes. That is a
purpose-built Arabic tool, from someone who has worked inside the most
structurally faithful Arabic engine anyone shipped, declining to promise that
the letters will come out right. His own essay on why the thing needs to exist
names the failure modes as incorrect letterforms, misplaced dots, broken words
— the three things the generators get wrong.
## What the field is working with
So the sequence runs: the grammar of the script was formally modeled four
decades ago, shipped commercially, won an award — and then in 2021 the one
product that exposed the engine's full range to a designer was withdrawn.
Meanwhile, when a recent paper sets out to *generate* Arabic calligraphy, the
default is to train a GAN on pictures of it: two networks, one producing
candidates and one judging them, converging on output that resembles the
training set. A [systematic review of the
literature](https://thesai.org/Publications/ViewPaper?Volume=16&Issue=3&Code=ijacsa&SerialNo=81)
covering 2009 to 2024 found nineteen studies and reported that GANs and their
variants dominate. Diffusion barely features.
Of the nineteen, the review's table of generation approaches lists **four**
studies — two on DCGAN, two on CycleGAN, one on vanilla GAN and VQ-GAN, one
paper counted twice because it tried both. The table of evaluation methods is
shorter still: four studies assessed by human judgment, and exactly one FID
score in the entire literature. This is not a field with a methodology problem
so much as a field that has barely been staffed.
The same review catalogs the datasets, and they explain a good deal.
So the generation literature is a methodological generation behind the rest of
image synthesis, working from a few thousand images, trying to rediscover from
pixels a structure that already exists in a specification.
It is not that nobody digitizes this material. IRCICA — the Istanbul institute
that has run the world's triennial calligraphy competition since 1986 — built
its own Ottoman OCR in 2011, because nothing off the shelf could parse the
script. Nearly two million scanned Ottoman pages sit in the Farabi digital
library. [Osmanlica.com](https://www.osmanlica.com/en/) reports average
accuracy above 95%, through a pipeline that reads the page, transliterates the
alphabet, then translates into modern Turkish.
IRCICA holds a calligraphy archive too, including four decades of
prize-winning work from its own competition. The OCR is pointed at the
paperwork. Reading the administration is a solved problem; reading the art is
not one anybody has taken on.
## Where the rules were written, someone encoded them
The tell is what happens next door.
Islamic geometric pattern is having an excellent decade computationally,
because its rules are written down and always were. Square Kufic — *bannā'ī*,
masonry script, the one that looks like pixel art because it was made of
bricks — gets [generated by cellular
automata](https://link.springer.com/article/10.1007/s00004-019-00454-3), which
is almost too neat a fit, since the script genuinely is a grid rule system.
Girih gets graph theory. In June, Ugail and Mehmood published a [completion
method with the patterns' own symmetries built in as a
constraint](https://arxiv.org/pdf/2607.02573), scoring edges over a candidate
lattice to reconstruct a full pattern from sparse control geometry — and it
does geometry only, not script. There is no equivalent for Thuluth.
Qur'anic page layout is the same story in a different register. The Madani
mushaf's 604 pages at fifteen lines each, with per-line word placement, exist
as [a hand-tuned table](https://qul.tarteel.ai/mushaf_layouts). Nobody trained
anything. Somebody sat down and encoded it, because the layout is a rule and
rules can be written.
And it is not only next door. There is a working market in Arabic calligraphy
software, decades old, and every tool in it that can promise you correct
letterforms gets them the same way: from fonts a type designer drew, assembled
by a program that knows the joining rules. Kelk has been the professional
standard for years. So have eMashq, Kaleam, CalliPro.
And that hedge is, oddly, the honest end of this market. I went through the
other generators — My Qalam AI, the free no-signup sites, the ones that
promise "authentic" Thuluth in seconds — and not one of them says anything
about correctness at all. No accuracy figure, no warning that the letters
might come out wrong, nothing telling you to check the text before you print
it. The only tool that admits it can miss is the one built by somebody who has
worked inside an engine that could not.
The pattern I keep landing on is this. Where the rules are already written
down, somebody encodes them and the results are good. Where they are not, the
default is to train on images and hope. That does not look like a difference
in how hard the art is.
## The part that stayed unwritten
Which leaves the obvious objection. If the proportions were written down in
the tenth century, why is there nothing to train on?
Because the specification and the judgment are two different things, and only
one of them got written. Ibn Muqla's system tells you how tall an alif is. It
does not tell you which of several licensed positions a dot should take in
*this* composition, how far a word may climb before the block goes wrong, or
why a stroke that measures correctly can still be dead on the page. That part
moves by *ijāza*, a license granted by a master to a student who has
demonstrated mastery, in an unbroken chain back through named teachers. What
travels along that chain is correction: the master watches the student's hand
and adjusts it. The judgment lives in the correction, and the correction was
never written down, because it never needed to be. There was always a person.
That is a strength of the tradition, and it is also why there is no corpus.
Centuries of accumulated judgment about pen angle, about where a dot may move
and how far, about which letters may be stacked and in what order — held in
hands, taught in rooms, and almost entirely absent from any machine-readable
form.
Whether you could grant a machine an ijāza is a fun question and not the
important one. The important one is that this half was never written down, so
there is nothing to train on but the finished work — and the finished work is
the one part that does not contain it.
## What might actually help
Not more images. Strokes.
[Calliar](https://arxiv.org/abs/2106.10745), from the ARBML community, is the
only dataset I know of that treats Arabic calligraphy as motion: 2,500
sentences traced with a digital pen by four annotators, recorded as ordered
point sequences and annotated at stroke, character, word and sentence level. A
stroke is one uninterrupted movement of the pen; a dot counts as one of its
own. Every other dataset in this field hands the model a picture of dried ink.
Calliar hands it the gesture.
There is a mature technique waiting for exactly this shape of data. Graves
showed in [2013](https://arxiv.org/abs/1308.0850) that an LSTM predicting pen
trajectories through a Gaussian mixture can generate convincing handwriting,
and can be primed with a real writer's pen movements to write in that person's
hand. The lineage runs through to transformer ink models today. Nobody, as far
as I can find, has run that playbook on Calliar. Thirty-six thousand training
strokes is probably too few. It is the right shape of too few.
The physical end is emptier still. Chinese calligraphy has parameterized brush
models — 3D hair geometry, ink deposition along the trajectory — and [robot
arms driven by optimal control](https://arxiv.org/abs/1911.08002) against
those models. The qalam is a reed cut at a fixed angle: a rigid nib with a
straight contact edge, which is what produces the entire thick-and-thin logic
of every classical style. It is a *simpler* object to model than a soft brush,
and its geometry is the whole grammar of the stroke. I could not find anyone
who has modeled it.
The closest thing is a project rather than a system. In a 2021–22 seminar at
the Berlin University of the Arts, Salam Shokor taught a UR5 industrial arm to
write Arabic, using a 3D-printed holder, a broad-nib parallel pen standing in
for the reed, and a custom stroke-based Arabic font built in Grasshopper. The
font was explicitly inspired by Hofstadter's *Letter Spirit*, the 1990s
project that tried to generate a whole alphabet in a consistent style from a
couple of seed letters. It worked on a grid of fifty-six segments rather than
a canvas of pixels, because its authors thought the hard part was holding two
kinds of sameness at once: what makes an *a* an *a*, and what makes it
Helvetica. Which is to say the robot drives from a font, along paths a person
defined. Even the robot is running on written-down rules. Nobody is simulating
the nib.
Visual text rendering *has* been largely solved:
[Glyph-ByT5-v2](https://arxiv.org/abs/2406.10208) renders accurate text in ten
languages and ships a benchmark to prove it. The ten are English, Chinese,
French, German, Spanish, Portuguese, Italian, Russian, Japanese and Korean.
Arabic is in neither the model nor the benchmark, so there is not even a
number to be bad at.
Meanwhile the region is building the infrastructure and hitting the same wall.
Qatar's [Fanar 2.0](https://huggingface.co/QCRI/Fanar-2-Oryx-IG) shipped in
March, a genuinely serious Arabic-first stack, with an image model built on
FLUX and trained on 480,000 culturally-curated images gathered across
twenty-two Arab countries. It scores 85.49 on the card's own
cultural-compliance measure. And the same card says, in plain words, that text
rendering in images — especially Arabic — remains challenging. A purpose-built
Arabic image model that cannot write Arabic. The companion vision model
*recognizes* calligraphy as a listed feature. Reading and writing have come
apart.
## What it is good for today
Vectorization, and not much else.
Turning a scanned piece into curves has always meant auto-tracing it and then
repairing the places where the tracer turned a confident sweep into a dozen
anchor points and a wobble. Learned vectorizers are better at the thing that
actually matters here, which is not coverage but curve continuity: the
smoothness of a single stroke, which is the first thing a trained eye checks
and close to the last thing a threshold-and-trace pipeline preserves. A [2025
method reports near-perfect overlap and smoother curvature than standard
auto-tracing across Naskh, Ruq'ah and
Diwani](https://www.academia.edu/145562424/A_Novel_Deep_Learning_Approach_for_High_Fidelity_Vectorization_of_Arabic_Calligraphy).
I would treat the exact figures with care given where it is published, but the
direction is unsurprising.
Note what that task requires: nothing. The model does not need to know Arabic,
or which style it is looking at, or that the marks are writing at all. It is
tracing curves. That is the honest shape of what machine learning currently
offers this craft — real, useful, and entirely outside the part that is hard.
One thing more. The marketplaces are now full of generated Qur'anic verses
sold as wall art, and a mangled verse is not a typographical infelicity. If
the text is sacred, take it from a verified mushaf and set it with a font that
knows the script. The generator does not know what it wrote.
## What I could not settle
None of this is an argument that the thing cannot be done. It is an argument,
from someone who is neither a researcher in this field nor a master of the
craft, that it is being approached from the wrong end — and I would rather be
shown wrong about that than right.
The structure of the script is known: DecoType demonstrated that decades ago,
and their model is documented in public even if the product is gone. The
calligraphic rules on top of it are known too; they are just held in people
rather than files. The datasets that would matter are the ones recording the
hand in motion, and one of them exists and is small and open and largely
unused.
What is missing is not compute, or model capacity, or volume — this was never
going to be fixed by more of what already exists. It is a different kind of
record altogether, one nobody has made, of a body of knowledge whose entire
transmission mechanism was designed around not needing one. Tarteel got 67
hours of Qur'anic recitation from twelve hundred volunteers in six months,
which suggests the community can build the corpus when someone frames the
task. For calligraphy, nobody has framed it.
Several things I could not settle, and would take a correction on. Whether
anyone has run the stroke-generation playbook on Calliar and simply not
published it. How much of DecoType's model is documented well enough to
rebuild from, now that the product is gone. Whether there is Arabic robotic
calligraphy work in a language I do not read: the literature on brush robots
is largely Chinese, and I searched in English and Arabic only. And how far the
disputed figures go: sources do not even agree on how many dots high a Thuluth
alif is, which is a strange place for a thousand-year-old specification to be
vague.
What I am fairly confident of is the shape of it. The window is not open
indefinitely: the chain that carries this knowledge runs through living
people, and what they hold is the correction — the adjustment made to a hand
in a room, which no photograph of a finished panel has ever contained. Every
archive being built right now is an archive of dried ink.
The thing worth recording is the stroke.
If you teach calligraphy, build these tools, or know of research I've missed,
[I'd like to hear from you](/en/contact). Share this with a calligrapher or
researcher who could add to the discussion, especially someone recording how
the work is made.
---
# لماذا يُخطئ الذكاء الاصطناعيّ في الخطّ العربيّ
- URL: https://omaralbeik.com/ar/blog/why-ai-gets-arabic-calligraphy-wrong
- Markdown: https://omaralbeik.com/ar/blog/why-ai-gets-arabic-calligraphy-wrong.md
- Translation: https://omaralbeik.com/en/blog/why-ai-gets-arabic-calligraphy-wrong
- Author: Omar Albeik
- Language: ar
- Type: article
- Date: 7 آب 2026
- Topics: calligraphy, typography, ai, software, engineering
قد تطلب من مولّد صور كتابة عبارة بالخط العربي، فتحصل على صورة تشبه الخط من
بعيد: سماكة القلم مقنعة، والكلمات متراكبة كما في الثلث. لكنك عندما تحاول
قراءتها، تجد أن بعض الحروف لا يؤدي إلى كلمة مفهومة.
يرى القارئ العربي الأخطاء بسرعة: حروف منفصلة في مواضع الوصل، وهاء بشكل ابتدائي
في وسط الكلمة، ونقاط لا يُعرف لأي حرف تنتمي. قد يخطئ المبتدئ في النسب وتبقى
عبارته مقروءة، بينما تفشل هذه الصور أحيانًا في الحفاظ على النص نفسه.
أردت أن أفهم السبب. أعمل في البرمجة، وأتدرّب على الخط منذ سنوات؛ وما زلت أقضي
وقتًا طويلًا في محاولة كتابة ألف أقبل شكلها. توقعت أن أجد نقصًا في بيانات
التدريب، لكن البحث قادني إلى مشكلة أدق.
## من قراءة النص إلى قراءة اللوحة الخطية
بدأت بافتراض أن النماذج تحتاج إلى مزيد من النصوص والصور العربية. لكن نتائج
التعرف على الكتابة اليومية والمخطوطات أظهرت تقدمًا كبيرًا، بينما بقيت قراءة
اللوحات الخطية أصعب بكثير.
يحوّل [Qalam](https://arxiv.org/abs/2407.13559) صور النصوص العربية إلى نص قابل
للمعالجة. دُرّب على أكثر من 4.5 مليون صورة من المخطوطات، وسجل في اختبار
الكتابة اليدوية **معدل خطأ كلمات قدره 0.80%**. أما
[QARI-OCR](https://arxiv.org/abs/2506.02295)، المبني على Qwen2-VL ذي الملياري
معامل، فسجل **معدل خطأ محارف قدره 6.1%** في نصوص عربية غنية بالتشكيل. هذه
نتائج على مجموعات الاختبار المذكورة في البحثين، وليست ضمانًا للأداء على أي
صورة عربية.
للمقارنة بين النتائج، نحتاج إلى التمييز بين ثلاثة مقاييس. معدل خطأ الكلمات
يقيس أخطاء التعرف على مستوى الكلمة، ومعدل خطأ المحارف يقيسها على مستوى الحرف.
قد تُحسب كلمة كاملة خاطئة بسبب حرف واحد. أما المطابقة التامة فهي نسبة الصور
التي تعرّف النظام على نصها كاملًا دون خطأ.
خصص باحثون من جامعة محمد بن زايد للذكاء الاصطناعي معيار
[DuwatBench](https://arxiv.org/abs/2601.19898) للخط العربي، ونشروه في كانون
الثاني. يضم 1272 عينة من الثلث والديواني والكوفي والنسخ والرقعة والتعليق، مع
النصوص والأنماط ومربعات التحديد. اختبروا عليه ثلاثة عشر نموذجًا، منها نماذج
عامة وأخرى متخصصة بالعربية، مفتوحة ومغلقة.
حقق Gemini 2.5 Flash أفضل نتيجة: **معدل خطأ كلمات 45%، ومطابقة تامة 42%**.
تراوحت المطابقة التامة في النماذج الثلاثة عشر من **صفر إلى 42%**، بمتوسط
**17.9%**. وتوضح الأمثلة نوعًا من الإخفاق لا يظهر في المتوسط وحده: أحد النماذج
يكرر لفظ الجلالة بدل قراءة النص الموجود في الصورة.
تختلف هذه النتيجة كثيرًا عن معدل الخطأ الذي يقل عن 1% في مهمة Qalam، مع اختلاف
مجموعات الاختبار وطبيعة النصوص. وحتى التخصص بالعربية لم يكفِ: النموذجان
المتخصصان بها جاءا قرب نهاية ترتيب DuwatBench. سجل نموذج TrOCR للكتابة اليدوية
العربية من Microsoft **معدل خطأ كلمات 99.98%، دون مطابقة تامة واحدة**.
توقعت أن ترتفع الأخطاء كلما زادت الزخرفة، لكن توزيع النتائج على الأنماط لم
يتبع هذا الترتيب.
كانت صعوبة الكوفي لافتة. أشكاله هندسية ويمكن وصف كثير منها على شبكة، ومع ذلك
كان الأصعب على النموذجين. قد تكون هذه الهندسة نفسها قد أزالت تفاصيل يستعين بها
القارئ على تمييز الحروف؛ هذا تفسير محتمل، وليس نتيجة أثبتها الاختبار.
أما تفوق النموذج المغلق في الثلث فيحتاج إلى حذر في التفسير. يمثل الثلث 55% من
العينات، وتشكل النصوص القرآنية 44% من المعيار كله. قد تساعد معرفة العبارات
الشائعة على تخمين النص، لكن هذه النسب وحدها لا تثبت أن النموذج اعتمد على
الحفظ.
وتقول خلاصة البحث إن النسخ والرقعة أسهل عند النظر إلى النماذج الثلاثة عشر
مجتمعة. وتذكر أيضًا أن النتائج تتحسن كثيرًا في الثلث والديواني لدى النماذج
المغلقة؛ وهو ما يظهر في عمود Gemini.
## هل يكفي نموذج أكبر؟
يبقى احتمال أن تحل زيادة بيانات التدريب المشكلة. بحث نُشر في حزيران اختبر أثر
الحجم مع تثبيت بنية النموذج.
استخدمت سناء العزّاوي وإليزا بارني وماركوس ليويتسكي [نموذجًا واحدًا لاختبار
تسع مجموعات من الكتابة اليدوية](https://arxiv.org/abs/2606.18884)، تشمل
العربية والأردية والفارسية والإنجليزية والألمانية. ثبّت الباحثون بنية النموذج،
وقارنوا النتائج عبر مجموعات البيانات وأحجام التدريب. كان الفارق بين الكتابة
بالحرف العربي واللاتيني أكبر عندما قلت البيانات. ضاق مع زيادتها، لكنه بقي عند
**خمس إلى سبع نقاط مئوية في معدل خطأ المحارف** حتى مع استخدام المجموعة كاملة.
وساعد تصحيح أخطاء التوصيف على تضييقه، دون إزالته.
وجد الباحثون أن **نحو 30% من أخطاء الاستبدال في بيانات الخط العربي تأتي من
الخلط بين حروف متشابهة بصريًا، مقابل نحو 15% في اللاتينية**. في بعض المواضع،
تتشارك عدة حروف الهيكل نفسه ولا يميزها إلا عدد النقاط ومكانها. يجب إذن أن يربط
القارئ النقطة بالحرف الصحيح، لا أن يتعرف على شكل الحرف وحده.
تزداد الصعوبة في تركيب الثلث، إذ قد يبعد الخطاط النقاط عن الحروف لتحقيق
التوازن. يستعين القارئ المتمرّس بالكلمة والسياق لفهم هذه العلاقات. أما ربط كل
علامة بأقرب شكل بصري فلا يكفي.
وتظهر حدود التعميم في مخطوطات العجمي بغرب أفريقيا، حيث تُكتب لغات أخرى بالحرف
العربي. قدمت وقائع ICDAR 2025 [مجموعة بيانات لمخطوطات الفلفلدية
والهوسا](https://link.springer.com/chapter/10.1007/978-3-032-04627-7_36). سجلت
نماذج التعرف على المخطوطات العربية التاريخية فيها **معدل خطأ محارف بين 65%
و84%**. هذه أخطاء على مستوى الحروف، وليست الكلمات، وتوضح أن النجاح في نوع من
المخطوطات لا ينتقل تلقائيًا إلى نوع آخر.
## ما الذي يفعله الخطّ
عدت بعد ذلك إلى قواعد الخط نفسه. أردت أن أفهم العلاقات التي يصعب على هذه
النماذج قراءتها.
يتغير شكل الحرف العربي بحسب موضعه: منفردًا أو في بداية الكلمة أو وسطها أو
نهايتها. وستة حروف، هي ا د ذ ر ز و، لا تتصل بما بعدها، فتتوزع الكلمة على مقاطع
منفصلة. وهناك تراكيب تجمع حرفين في شكل خاص. وفي الخطوط الكلاسيكية، قد تتراكب
الكلمات رأسيًا كما في الثلث، أو تصعد على السطر كما في الديواني. يحتاج القارئ
إلى فهم هذه العلاقات حتى يعرف ترتيب القراءة.
تؤثر هذه القواعد في تكوين الحروف وقراءة الكلمات، وليست مجرد زخرفة تضاف بعد
كتابة النص.
في الديواني، المستخدم في الدواوين العثمانية، تتقارب الكلمات وتصعد في تراكيب
كثيفة. ومن التفسيرات التقليدية لهذا التقارب أنه يصعّب إضافة كلمات أو بنود إلى
الوثيقة بعد كتابتها.
وفي النستعليق، الذي يجمع اسمه بين النسخ والتعليق، تنحدر الكلمات قطريًا وتختلف
مستوياتها. لذلك لا يكفي نموذج صفّ يفترض أن جميع الحروف والكلمات تستقر على خط
أفقي واحد.
تُظهر صورة العمل النهائي موضع الحبر، لكنها لا تسجل ترتيب حركات القلم وزاويته،
ولا سبب اختيار موضع نقطة أو كلمة. يستطيع النموذج تعلم كثير من العلاقات من
الصور، لكن الصورة وحدها لا تقدم هذه القرارات بصورة صريحة.
## القواعد كانت مكتوبةً سلفًا
توقعت أن تكون بعض هذه القواعد غير موثقة. وجدت، بدلًا من ذلك، تراثًا طويلًا
لقياس الحروف وتنظيمها.
يقوم *الخط المنسوب* على نظام للنسب يعود إلى أكثر من ألف سنة، ويُنسب في المشهور
إلى ابن مقلة (ت 328هـ/940م). يستخدم النقطة والألف والدائرة مراجع لقياس الحروف.
تساعد هذه المقاييس الخطاط على تحديد الخطأ في النسبة، بدل الاكتفاء بالشعور بأن
الحرف يبدو غريبًا. ويُنسب إلى ابن مقلة تقنين الأقلام الستة، ثم تطوير النظام
على يد ابن البواب (ت 413هـ) وياقوت المستعصمي. كانت هناك إذن قواعد قابلة للوصف
قبل ظهور برامج الخطوط بقرون.
وتوجد قواعد للتكوين على مستوى الصفحة أيضًا. من أمثلتها تخطيط الحلية الذي أعاد
الخطاطون استخدامه مع اختلاف التفاصيل.
ثم وجدت محاولة حديثة لتحويل معرفة الخط إلى برنامج، وهي التي غيّرت تصوري
للمشكلة.
تأسست [DecoType](https://decotype.com/) سنة 1985 على يد بيتر سومرز وميريام
سومرز وتوماس ميلو. طورت الشركة خطوطًا تطبق قواعد الكتابة عند تركيب الحروف،
ومنها خط رقعة رقمي ديناميكي وصل إلى Microsoft Office في أوائل التسعينيات. وعرف
مستخدمو Office أيضًا عائلتي DecoType Naskh وDecoType Thuluth، اللتين تحمل
نسخهما المخصصة له تواريخ ترخيص بين 1992 و1998. لم أستطع التحقق من وجودهما في
إصدارات Office الحالية.
بنت DecoType محرّك ACE للرقعة أولًا، ثم وسعته اعتمادًا على دراسة النسخ. حمل
الاسم في البداية معنى محرّك الخط العربي، ثم أصبح محرّك التركيب المتقدم مع
اتساع استخدامه.
يشرح ميلو في [عرض نموذج
ACE](https://www.academia.edu/2448322/A_model_for_Handling_the_Arabic_Script_2005_)
كيف يمكن بناء نظام صفّ ينطلق من قواعد الكتابة العربية وتراث المخطوطات. يحدد
المحرّك طريقة تركيب الحروف وفق هذه القواعد، بدل التعامل معها كقطع مطبعية
مستقلة. ونال ميلو جائزة بيتر كارو سنة 2009.
استخدم المصممون هذا المحرّك عبر «تصميم»، وهو ملحق لـ InDesign ME طورته
DecoType مع WinSoft International، التي تولت نشره. ما يهمني فيه هو مقدار
التحكم الذي يتيحه في تركيب الحروف، اعتمادًا على قواعد الكتابة نفسها.
[أوقفت WinSoft منتج «تصميم» في نيسان
2021](https://winsoft-international.com/tasmeem/). شمل القرار الملحق، لا شركة
DecoType أو محرّكها كله. كان آخر إصدار مخصصًا لـ InDesign CC 2021، مع استمرار
دعم العملاء إلى نهاية اشتراكاتهم، ودون مبيعات أو ترقيات جديدة. وفي مراجعتي
لموقع DecoType، كان أحدث محتوى مؤرخ وجدته محاضرة من 2017.
ومن الأسماء التي تكررت في هذا التاريخ نهاد تيسير ندم، المصمم الدمشقي المقيم في
دبي. يذكر في سيرته عمله مع Adobe وWinSoft وDecoType، ومشاركته سنة 2011 في
تطوير أدوات للخط العربي على الويب إلى جانب «تصميم». ويقدم اليوم
[ArabicDesign.ai](https://arabicdesign.ai/en)، التي تولّد صورًا خطية من نص
عربي بنحو خمسة عشر نمطًا، وتتيح تصديرها بصيغة متجهية.
تقول صفحة مزايا الأداة إنها تحافظ على النص المطلوب بنسبة تصل إلى 95% وتقلل
أخطاء الحروف والنقاط. هذه أرقام يعلنها المنتج، لا قياسات مستقلة أجريتها. لكنها
تكشف الحد الذي يقر به: حتى الأداة المتخصصة لا تضمن سلامة النص في كل نتيجة.
وتذكر مقالة صاحبها الأخطاء نفسها التي بدأت بها: حروف غير صحيحة، ونقاط في غير
مكانها، وكلمات متقطعة.
## الأدوات المتاحة اليوم
إذن لدينا تجربة تجارية قديمة في تمثيل قواعد الخط، لكن جزءًا من الأدوات التي
أتاحت هذه التجربة توقف. أما أبحاث التوليد التي راجعتها، فتنطلق غالبًا من صور
الخط. جمعت [مراجعة
منهجية](https://thesai.org/Publications/ViewPaper?Volume=16&Issue=3&Code=ijacsa&SerialNo=81)
تسعة عشر بحثًا بين 2009 و2024، ووجدت حضورًا بارزًا للشبكات التوليدية التنافسية
ومشتقاتها، مقابل حضور محدود لنماذج الانتشار. في الشبكة التنافسية، يولّد جزء
الصور ويتعلم جزء آخر تمييزها عن بيانات التدريب.
يعرض جدول مناهج التوليد في المراجعة **أربعة أبحاث**: يظهر DCGAN في بحثين،
وCycleGAN في بحثين، وGAN الأصلي وVQ-GAN في بحث. تتداخل الأعداد لأن أحد الأبحاث
جرّب أكثر من منهج. أما التقييم، فتذكر المراجعة أربعة أبحاث استخدمت الحكم
البشري، واستخدامًا واحدًا لمقياس FID. العينة البحثية صغيرة، فلا تكفي لتعميم
واسع على كل طرق التوليد.
وتعرض المراجعة مجموعات البيانات المستخدمة، مع اختلاف كبير في أحجامها:
تعمل الأبحاث التي تعرضها هذه المراجعة غالبًا على مجموعات صغيرة من الصور. وهذا
يفتح سؤالًا: كيف يمكن تزويد النموذج بقواعد الخط المعروفة، بدل مطالبته
باستنتاجها كلها من الصور؟
توجد جهود كبيرة لرقمنة هذه المواد. طوّر مركز IRCICA في إسطنبول نظامًا للتعرف
الضوئي على النصوص العثمانية سنة 2011، وتضم مكتبة الفارابي الرقمية نحو مليوني
صفحة عثمانية ممسوحة. ويعلن [Osmanlica.com](https://www.osmanlica.com/en/)
متوسط دقة يتجاوز 95% في نظام يجمع قراءة النص ونقله إلى الحروف اللاتينية
وترجمته إلى التركية الحديثة. هذا رقم يعلنه المشروع، ولم أختبره بنفسي.
ولدى IRCICA أيضًا أرشيف لأعمال فائزة في مسابقات الخط عبر أربعة عقود. لكن
التعرف على الوثائق الإدارية وقراءة اللوحات الفنية مهمتان مختلفتان؛ وجود أرشيف
رقمي لا يعني أنه أصبح مجموعة تدريب مناسبة للثانية.
## تجارب في تحويل القواعد إلى برامج
توجد أمثلة قريبة توضح فائدة تمثيل القواعد صراحة.
في الخط الكوفي المربع، أو البنائي، تتبع الحروف شبكة تشبه شبكة الآجر الذي تُبنى
به. يستفيد [بحث في توليده بالأوتوماتا
الخلوية](https://link.springer.com/article/10.1007/s00004-019-00454-3) من هذه
البنية: تُطبق قواعد على خلايا الشبكة لتكوين الأنماط. هنا تتوافق طريقة التمثيل
البرمجي مع طريقة بناء الشكل.
وفي زخارف الگِره الهندسية، قدم عجيل ومحمود [طريقة لإكمال الزخرفة باستخدام قيود
التناظر](https://arxiv.org/pdf/2607.02573). تبدأ من عناصر هندسية متفرقة،
وتقيّم الحواف المحتملة على شبكة لإكمال الشكل. المثال يتعلق بالزخرفة، لكنه يوضح
كيف توجه قاعدة معروفة عملية التوليد.
ومثال آخر هو تخطيط صفحات المصحف. تتيح [مكتبة QUL من
ترتيل](https://qul.tarteel.ai/mushaf_layouts) جداول تربط الكلمات بصفحاتها
وأسطرها في تخطيطات متعددة، منها مصحف المدينة ذي 604 صفحات. يستطيع البرنامج
استخدام هذه البيانات مباشرة للحفاظ على توزيع الكلمات، بدل محاولة استنتاج
التخطيط من صورة الصفحة.
وتستخدم برامج مثل Kelk وeMashq وKaleam وCalliPro حروفًا صممها خطاطون ومصممو
خطوط، مع أدوات لتركيبها. تختلف هذه الطريقة عن توليد صورة جديدة للنص؛ فهي تبدأ
بأشكال محددة وقواعد لوصلها وترتيبها.
راجعت أيضًا صفحات مولّدات أخرى، منها My Qalam AI وأدوات مجانية تعد بإنشاء
الثلث في ثوانٍ. لم أجد في الصفحات التي قرأتها قياسات واضحة لصحة النص أو شرحًا
كافيًا لأخطاء الحروف المحتملة. لذلك كان تصريح ArabicDesign.ai بحدود الدقة
مفيدًا، حتى مع حاجته إلى تحقق مستقل. قبل طباعة النتيجة، أريد أن أعرف كيف أراجع
نصها، لا كم يستغرق توليدها فقط.
تكرر أمامي فرق في طريقة تمثيل المعرفة: بعض الأدوات تستخدم قواعد وتراكيب محددة،
بينما تتعلم أدوات التوليد من صور النتائج. يبدو الجمع بين النوعين اتجاهًا يستحق
التجربة، بدل الاكتفاء بزيادة الصور.
## الجزء الذي بقي غير مكتوب
لكن إذا كانت نسب الحروف موثقة منذ قرون، فما الذي لا يزال ناقصًا؟
تحدد القواعد قامة الألف ونسب الحروف، لكنها لا تختصر كل ما يراجعه المعلم في عمل
الطالب: أين توضع النقطة في هذا التركيب، وكم ترتفع الكلمة، ولماذا يبدو حرف
مضبوط القياس ضعيفًا داخل اللوحة.
ينتقل جانب كبير من هذه المعرفة بالممارسة والتصحيح المباشر. وتمنح الإجازة
للطالب الذي أثبت تمكنه أمام معلمه، ضمن سلسلة من الخطاطين المعروفين. صورة العمل
النهائي لا تحتفظ عادة بالتعديلات التي اقترحها المعلم ولا بأسبابها.
تحفظ هذه الطريقة معرفة دقيقة في الممارسة: زاوية القلم، وحدود نقل النقاط، وطرق
تركيب الحروف. لكن تحويلها إلى بيانات يتطلب تسجيل عملية التصحيح نفسها، لا تصوير
الأعمال المكتملة فقط.
السؤال المفيد هنا هو كيف نسجل الفرق بين المحاولة الأولى وتصحيح المعلم، مع
تفسير السبب. هذا يوفر معلومات لا تظهر في صورة النتيجة وحدها.
## ما قد ينفع فعلًا
أرى فرصة في بيانات تسجّل حركة القلم إلى جانب صور العمل النهائي.
تقدم [Calliar](https://arxiv.org/abs/2106.10745)، من مجتمع ARBML، مثالًا على
ذلك: 2500 جملة كتبها أربعة أشخاص بقلم رقمي، مع تسجيل النقاط بالترتيب وتوصيف
الضربات والحروف والكلمات والجمل. تحتفظ المجموعة بمسار الكتابة، وهو ما لا يتوفر
في صورة العمل المكتمل وحدها.
بيّن غريفز في [2013](https://arxiv.org/abs/1308.0850) إمكان توليد كتابة يدوية
عبر التنبؤ بمسارات القلم باستخدام خليط غاوسي، وتكييفها انطلاقًا من كتابة شخص
معين. امتد هذا الاتجاه إلى نماذج حبر تعتمد على المحوّلات. لم أجد تجربة تطبقه
على Calliar. وقد لا تكفي ست وثلاثون ألف ضربة للتدريب، لكنها تمثل نوعًا من
البيانات يستحق البناء عليه.
هناك جانب آخر يتعلق بالأداة نفسها. في الخط الصيني، توجد نماذج رياضية تحاكي شكل
شعر الفرشاة وترسب الحبر، و[أبحاث في التحكم بذراع
آلية](https://arxiv.org/abs/1911.08002) تستخدم هذه النماذج. أما قلم القصب فله
سن صلبة مقطوعة بزاوية، ويؤثر اتجاه حركتها في سماكة الضربة. تبدو هندسته أبسط من
الفرشاة، لكن ذلك لا يثبت أن محاكاة الكتابة به سهلة. لم أعثر في بحثي على نموذج
مماثل يجمع هذه الخصائص.
أقرب الأمثلة التي وجدتها مشروع لسلام شكور في جامعة برلين للفنون بين 2021
و2022. استخدم ذراع UR5 وحامل قلم مطبوعًا ثلاثي الأبعاد وقلمًا عريض السن، مع خط
مبني على الضربات صُمم في Grasshopper.
استلهم الخط مشروع *Letter Spirit* لهوفشتاتر، الذي حاول توليد أبجدية متناسقة
انطلاقًا من بضعة حروف. مثّل المشروع الحروف على شبكة من 56 مقطعًا، ليجمع بين ما
يميز الحرف وما يمنحه طابع خط معين. في تجربة الذراع، كانت مسارات الكتابة محددة
بهذا الخط الرقمي؛ لم تكن التجربة محاكاة مستقلة لتفاعل سن القصبة مع الورق.
تقدم [Glyph-ByT5-v2](https://arxiv.org/abs/2406.10208) في عرض النص داخل الصور
بعشر لغات، مع معيار لتقييم النتائج. تشمل اللغات الإنجليزية والصينية والفرنسية
والألمانية والإسبانية والبرتغالية والإيطالية والروسية واليابانية والكورية.
العربية ليست بينها، لذلك لا نستطيع الاستدلال بهذه النتائج على أدائه في الخط
العربي.
وتوضح بطاقة [فنار 2.0](https://huggingface.co/QCRI/Fanar-2-Oryx-IG) أن المشكلة
قائمة أيضًا في مشروع يركز على المنطقة العربية. نموذج الصور مبني على FLUX،
ودُرّب على 480 ألف صورة مختارة من اثنتين وعشرين دولة عربية. تسجل البطاقة 85.49
في مقياس التوافق الثقافي، لكنها تذكر أن عرض النص في الصور، وخاصة العربي، ما
زال صعبًا. النجاح في تمثيل عناصر الثقافة لا يضمن كتابة الحروف بصورة صحيحة.
## استخدامات مفيدة الآن
أحد الاستخدامات الواعدة هو تحويل صورة خطية إلى رسم متجهي يمكن تكبيره وتحريره.
عند تحويل صورة ممسوحة إلى منحنيات، قد يضيف التتبع الآلي نقاط ارتكاز كثيرة
وتشوهات صغيرة تحتاج إلى تصحيح يدوي. في الخط، تهم نعومة المنحنى بقدر مطابقة
مساحة الحبر. تعرض [دراسة من
2025](https://www.academia.edu/145562424/A_Novel_Deep_Learning_Approach_for_High_Fidelity_Vectorization_of_Arabic_Calligraphy)
طريقة تعلم عميق، وتذكر أنها تحافظ على الشكل وتنتج منحنيات أنعم من التتبع
التقليدي في النسخ والرقعة والديواني. أتعامل مع أرقامها بحذر بسبب جهة نشرها،
لكن المهمة نفسها مناسبة للتجربة.
تختلف هذه المهمة عن توليد نص صحيح: يستطيع النموذج تحسين المنحنيات دون فهم
الكلمات أو معرفة قواعد الخط. هذا استخدام مفيد، لكنه لا يحل مشكلة الحروف
الخاطئة في الصور المولدة.
وتزداد أهمية المراجعة عندما يكون النص آية قرآنية. لا يكفي أن تبدو الصورة
جميلة؛ ينبغي مطابقة النص بمصحف موثوق، واستخدام أداة تحافظ على الحروف وترتيبها
قبل الطباعة أو النشر.
## ما لم أستطع الحسم فيه
لا أستنتج من ذلك أن توليد الخط الصحيح مستحيل. أرى أن تمثيل القواعد وحركات
القلم وتصحيحات المعلمين يستحق اهتمامًا أكبر. هذه قراءة من مطوّر يتعلم الخط،
وليست نتيجة تجربة تثبت تفوق هذا المنهج.
توضح تجربة DecoType إمكان تمثيل بعض قواعد الكتابة برمجيًا. وتضيف Calliar
بيانات مفتوحة عن حركة القلم، وإن كانت صغيرة. أما قرارات التصحيح والتكوين، فما
زال جانب كبير منها ينتقل بين المعلم والطالب دون سجل يصلح مباشرة للتدريب.
قد تفيد زيادة البيانات وحجم النماذج، لكنني أبحث هنا عن بيانات من نوع آخر:
محاولات قبل التصحيح وبعده، ومسارات القلم، وتفسير المعلم لما غيّره ولماذا.
تقدم تجربة «ترتيل» مثالًا مشجعًا على جمع البيانات بمشاركة المجتمع: 67 ساعة من
التلاوة القرآنية، من نحو 1200 متطوع خلال ستة أشهر. قد يساعد تحديد مهمة واضحة
وقابلة للمشاركة على جمع بيانات للخط أيضًا، مع اختلاف متطلبات التسجيل والتوصيف.
بقيت أسئلة لم أستطع حسمها. هل جُرّبت طرق توليد الضربات على Calliar دون نشر
النتائج؟ وهل توثيق DecoType كافٍ لإعادة بناء نموذجها؟ وهل توجد أبحاث عن الخط
العربي الآلي بلغات لم أبحث بها؟ اقتصرت مراجعتي على العربية والإنجليزية، بينما
كثير من أبحاث فرشاة الخط بالصينية. كذلك تختلف المصادر في عدد النقاط الذي تقاس
به الألف في الثلث؛ وهذا تفصيل يحتاج إلى ضبط قبل تحويله إلى قاعدة برمجية.
ما أود حفظه هو ما يحدث أثناء التعلم: حركة القلم، وتصحيح المعلم، وسبب اختيار
موضع دون آخر. أصحاب هذه المعرفة أحياء ويمكن العمل معهم لتسجيلها. أرشيف اللوحات
مهم، لكنه لا يوثق هذه العملية وحده.
نحتاج إلى حفظ طريقة كتابة اللوحة أيضًا.
إذا كنت تعلّم الخط، أو تطوّر أدواته، أو تعرف بحثًا فاتني، [يسعدني أن
نتحدث](/ar/contact). وشارك المقالة مع خطاط أو باحث لديه ما يضيفه، خصوصًا من
يعمل على توثيق خطوات الكتابة والتصحيح.
---
# Binding libVLC directly from Swift 6
- URL: https://omaralbeik.com/en/blog/binding-libvlc-directly-from-swift-6
- Markdown: https://omaralbeik.com/en/blog/binding-libvlc-directly-from-swift-6.md
- Translation: https://omaralbeik.com/ar/blog/binding-libvlc-directly-from-swift-6
- Author: Omar Albeik
- Language: en
- Type: article
- Date: 3 August 2026
- Topics: swift, open-source, software, engineering
[Tilfaz](https://tilfaz.app) is an IPTV client. It ships on the App Store, on
iPhone, iPad, Mac and Apple TV. IPTV means whatever the provider decided to
send: MPEG-TS over UDP, HLS manifests that go stale between segments, MKV
containers, SSA subtitles carrying their own styling, audio in codecs Apple
has never shipped a decoder for.
AVFoundation is very good at the formats Apple ships. "AVFoundation can't do
IPTV" is the sort of claim that gets you corrected within the hour by somebody
who has shipped a flawless HLS app and never had a reason to feed it anything
else.
So take the smallest case: one MP4 carrying H.264 video and AAC audio, remuxed
to Matroska with `-c copy`. The elementary streams come out bit-identical — I
checked the hashes. The MP4 decodes. The MKV returns `-11828`, *this media
format is not supported*. There is no Matroska demuxer, so the question of
what is inside is never asked.
The refusals are the cheap half: a loud failure is one you can handle. The
expensive rows are the last three. HEVC inside a transport stream opens on
macOS, reports `isPlayable == true`, raises nothing, and hands you an asset
with no video track — and HEVC in a transport stream is ordinary in IPTV. A
viewer does not see an unsupported-format error. They see a channel that plays
sound over a black rectangle, and they tell you your app is broken, and they
are right.
Much later, building demo apps for the library that came out of all this, I
needed one file that exercised everything a player ought to cope with. It
ended up as sixty seconds of Matroska carrying three video variants, three
Opus audio tracks, three subtitle tracks — one of them Arabic, right to left —
six named chapters and an attached cover image. Every one of those properties
is unreachable through AVFoundation. I built it as a demo. It is really the
gap, written down as a file.
## I was already using VLCKit
So the engine had to be [libVLC](https://www.videolan.org/vlc/libvlc.html) —
VideoLAN's playback core, the same C API that VLC itself runs on. The
established Apple wrapper for it is
[VLCKit](https://code.videolan.org/videolan/VLCKit), also VideoLAN's own,
written in Objective-C. I was already using it.
VLCKit is a faithful record of the decade it was written in. I mean that
straight: the delegate protocol, the notification names, the `id drawable` you
assign a view to — that was how you built a media framework in 2013, and a
great deal of software you rely on was built the same way and works.
I did not leave over the idiom. I left over Picture-in-Picture, and the reason
is duller than a design argument. VLCKit 3 does not have it. There is no PiP
type, no PiP protocol, no `VLCDrawable.h` in that line at all — the feature
arrives in VLCKit 4, and VLCKit 4 has been in alpha since September 2022 and
ships from a download path with the word `unstable` in it. So the actual
choice was not modern Swift against good-enough Objective-C. It was: take a
production dependency on a four-year-old alpha to get one feature, or bind the
C API underneath it myself. Everything downstream of that — the direct C
binding, the lifetime rules, most of the patches — follows from it.
VLCKit 4 is not standing still. It added visionOS and watchOS, rewrote its
event handling, gained subsecond seeking, and picked up Swift Package Manager
support two weeks before I wrote this. Comparing against the 3.x README, which
is what its own repository still shows you, would be a straw man.
And the unreleased engine is mine, not theirs. I am on libVLC 4, which has
never had a stable release; VLCKit maintains a line on released libVLC 3 and
is still fixing that line. If you need an engine that has shipped, there is
exactly one option in this comparison and it is not mine.
There is an [open
Blocker](https://code.videolan.org/videolan/VLCKit/-/issues/759) on VideoLAN's
tracker, filed in July by someone who is not me: a second input on a reused
player never re-attaches its video output. Audio playing behind a permanently
black picture, on tvOS, on live MPEG-TS from an IPTV panel. That is channel
switching. That is the workload.
## The attempt before the attempt
In December 2025 I published
[`harflabs/VLC`](https://github.com/harflabs/VLC). Four commits in one
evening, and then never again.
It wrapped VLCKit, not libVLC. It took the three Objective-C frameworks that
VLCKit 3.7.0 ships, one per platform, and republished them as SPM binary
targets behind a platform-conditional umbrella — VLCKit 3.x has no
`Package.swift` at all, and I wanted to type a URL into a manifest like a
normal person.
It is archived now. The reason is visible in its own manifest, which declares
`swift-tools-version: 6.0` and then wraps a framework whose public headers
contain not one concurrency annotation. Packaging turned out to be the easy
half. I had made VLCKit resolvable and changed nothing about the fact that a
Swift 6 SwiftUI app now owned an unannotated, single-delegate object model.
[SwiftVLC](https://github.com/harflabs/SwiftVLC) started in February and hit
1.0 in July. Four and a half months, and here is where they went.
## Bind C directly, and accept the cost
The first decision was to go from C to Swift with no Objective-C in between.
The table above already made that case. What it cannot show is that rendering
becomes one view:
```swift
struct PlayerView: View {
@State private var player = Player()
var body: some View {
VideoView(player)
.onAppear { try? player.play(url: streamURL) }
}
}
```
`VideoView` hands libVLC an `NSView`/`UIView` through `set_nsobject` and VLC
renders into it directly. No layer you construct, no `MTKView`, no
`AVPlayerLayer`.
The cost is that you now own every C lifetime rule yourself, with no ARC in
between. Every libVLC object follows the same pattern — `init` allocates,
`deinit` releases, Swift object lifetime owns C pointer lifetime — and that
part is mechanical. The interesting failures all happen at the seams.
## Two ways to move a pointer
`OpaquePointer` and `UnsafeMutableRawPointer` do not conform to `Sendable`.
Not as an oversight and not as a consequence of region-based isolation: the
standard library declares the conformance *unavailable*, on purpose, because
the compiler cannot reason about what a pointer points at. Regions are what
occasionally rescue you by letting a disconnected value transfer between
isolation domains. They do not help here, because capturing into an escaping
`@Sendable` closure is not a transfer, and releasing a C object off the main
thread is exactly that capture.
SwiftVLC allows two ways out. For a capture into a single closure, a local
binding that opts out:
```swift
nonisolated(unsafe) let p = pointer
DispatchQueue.global(qos: .utility).async {
libvlc_media_player_release(p)
}
```
The pointer is trivially transferable and stays valid for the enclosing scope,
which is the whole argument. For pointers read and written from several
threads over time, a `Mutex` around a state struct, with the struct marked
`@unchecked Sendable` and the mutex, not the compiler, doing the actual work.
There is a third way, and the architecture document bans it: laundering a
pointer through `Int(bitPattern:)` and back. It compiles, it silences the
diagnostic, and it destroys the two things that made the diagnostic worth
having — the type and the intent. Six months later nobody reading that
function can tell a live pointer from an integer, and the compiler has been
talked out of helping.
The codebase breaks that rule in exactly one place. A qualification path
stores a player address as a `UInt` and converts it straight back, and the
field's own doc comment offers the banned justification — *stored as bits
because `OpaquePointer` is not Sendable*. I have left it there, and named it
here. A rule with one exception you can point at and a rule nobody enforces
any more look identical from outside.
## Lifetimes nothing checks
Events cross three isolation domains: C callbacks firing on libVLC's own
threads, a multi-consumer broadcaster, then `@Observable` properties on the
main actor.
`Broadcaster.broadcast` snapshots the subscribers under the lock, then runs
their filters and yields *outside* it. One line.
Two separate things go wrong if you yield inside. A subscriber's filter is
user code. If that code touches the broadcaster again — subscribes, asks
whether it is empty, broadcasts — it deadlocks against a mutex that is not
recursive. And while it waits, it is still holding a lock libVLC's own event
thread is blocked on. Separately, `onTermination` runs synchronously on
whatever thread canceled the consuming task, and it calls `unsubscribe`, which
wants that same mutex. A cancellation landing mid-broadcast becomes one thread
taking a lock it is already holding.
There is a regression test for this now, and it exists because the fix is one
line and somebody could move it back. There was not one when the bug was
written. Deadlocks of this shape do not turn up in a suite that finishes while
you are still watching it; they turn up in the hands of someone scrubbing a
live stream on a train.
The same type carries two ways to close. `finishAll()` closes the current
subscribers and allows resubscribe; `terminate()` closes them and makes every
*future* `subscribe` return an immediately-finished stream. The second exists
because some broadcasters are reached through a computed property that builds
a fresh subscription on each access, so a subscriber arriving after the
producer is gone has to get a finished stream rather than a live one nobody
will ever feed. Without it, the failure is not a crash. It is an `await` that
never returns, which is much worse to find.
One callback also has to become two streams, because libVLC mixes two kinds of
event on it and only one of them can be dropped safely.
Teardown looks like four steps in a fixed order. It is not. The order falls
out of one question asked at each node: *what is still reading this?*
All three constraints live in one comment above one function, which is the
only thing enforcing them.
## A pointer is not an identity
This is the idea I would most want to have been told before starting, and it
is the one I arrived at last.
A `Player` can replace the libVLC player underneath it while the Swift object
and its event streams stay alive. When that happens, callbacks already in
flight are still going to arrive, and they are going to arrive describing
something that no longer exists. The instinct is to compare pointers. The
instinct is wrong, and the source says why in one line: *native pointer
addresses are not identities — an allocator may reuse a retired address for a
later handle.*
So every layer that can be replaced under a live consumer gets a monotonic
counter, and every event carries the values it was born with.
I did not design this up front. It accreted, one recurring bug class at a
time, and when I audited the library after 1.0 the single largest group of
findings was some version of *this callback is about the previous thing*. If I
were starting again I would reach for it on the first day, and I suspect that
is true of anyone binding a C library whose objects outlive the calls that
make them.
## Where the wrapper stops being a wrapper
The governing fact is that libVLC copies your video-memory callback pointers
and their opaque context when a video output *opens*. Clearing the callback
variables on the media player afterwards does not revoke a copy that output is
already holding. The obvious teardown — unset the callbacks, then free the
context — is a use-after-free waiting for a `vout` that has not finished with
you yet.
The fix ties every retained opaque to one exact `libvlc_media_player_t`, so
sequential controllers on the same native handle can hand over atomically
while an overlapping output can never touch another output's dimensions, pool,
or cleanup state. Retiring an opaque suppresses new display work immediately,
but it is released only after the final counted native release for that handle
returns and every callback already in flight has drained. No timeout, and no
transient `vout` observation, is treated as proof of safety. With C callbacks,
"it has probably finished by now" is not a lifetime.
Then there are four rendering paths, and they differ mainly in who owns the
object at the end.
That last row is the decision I am least comfortable with and most confident
about. On macOS, the public sample-buffer mirror crops at 1:1 layer size
instead of scaling into the PiP panel, on the macOS releases I support — the
video is simply wrong on screen. The path that works is a private framework:
load `PIPViewController` out of `PIP.framework` at runtime and reparent VLC's
real drawable view into it.
None of which means VideoLAN left PiP unsolved. libVLC ships a
Picture-in-Picture controller and both wrappers use it. But it is gated to iOS
and tvOS in VLC's own build files, the source file says as much in its header,
and the class is simply absent from the macOS slice of the binary I ship.
There is no native macOS path in the engine to use.
So the private-framework path ships behind an explicit opt-in, and every call
into a private *Apple* symbol in the library lives in exactly one file. Not
because that makes it App Store safe — it does not, and that is the point of
the opt-in — but because an auditor asking what private API this touches
should be able to read one file and be done.
The iOS backend does something similar in miniature: it reports PiP
unavailable in the Simulator, deliberately. Simulator AVKit will happily
report an active sample-buffer PiP controller while the system window stays
black. A test that passes against that is not a passing test, it is a lie with
a green tick.
And then the abstraction leaks the other way. Getting the geometry I needed
out of the vmem path meant adding entry points to libVLC that libVLC does not
have — which means shipping an engine whose public C surface I have extended,
and then negotiating with archives built before I invented it.
## When you stop reading the headers
At some point you stop reading a C engine's headers and start reading its
source, and shortly after that you start changing it.
Version 1.0 shipped with six patches. The other nineteen landed twelve days
later, in a single eight-day run. 1.0 was the point at which I stopped working
around the engine and started fixing it.
Some are backports of upstream fixes that landed after my pin. The
player-timer series is the clearest: on the pinned revision the timer
interpolates past the pause point, so a paused player keeps reporting a time
that advances. That surfaces directly as `Player.currentTime`, and PiP's
control timebase is placed from the same reading, so the visible symptom is a
paused video with a drifting scrubber. That patch carries three upstream
refactors it depends on, verbatim, rather than hand-adapting the two real
fixes onto the older shape — one of the three is what turns the interpolation
flag into the enum the real fix adds a case to. A rebase you can re-derive
beats a rewrite you have to re-verify.
Others are mine. One is a double free in VLC's adaptive demuxer.
`ISegment::toChunk()` releases the chunk source twice on the `prepareChunk()`
failure path: once explicitly through `recycleSource()`, and again when it
deletes the chunk, because `~AbstractChunk()` releases the source the chunk
owns. For segment chunks the recycle is not cacheable and goes straight to
`delete`, so the second release dispatches through a vtable on freed memory.
A one-line commit in 2022 copied a recycle call up from the branch immediately
below, where recycling is exactly right: `createChunk()` returned nothing
there, so no chunk exists to own the source. One branch up a chunk does exist,
and the copy became a second release. Somebody moved a correct line one branch
too far. It is still in VLC master today, and there is an [open
report](https://code.videolan.org/videolan/vlc/-/work_items/29845) on
VideoLAN's tracker describing an intermittent `EXC_BAD_ACCESS` on iOS arm64
after roughly ten minutes of HLS playback, with a stack that lands on the
destructor.
The ten minutes follow from the mechanism. `prepareChunk()` only does work for
encrypted segments, and only fails when the key cannot be resolved. Keys are
cached. So it bites at key rotation or after cache eviction rather than at
startup — which is exactly the *fine for ten minutes, then crash* profile in
the report.
Encrypted segments only, only when an AES-128 key fails to resolve, flaky
network, real device, ten minutes in. That bug is not going to fail your test
suite. It did not fail mine, either. Somebody else hit it first, on the same
engine commit I pin, and filed it upstream. I found the defect by reading the
ownership graph, then reproduced it deterministically. My patch adds a
regression test to VLC's own adaptive suite; it counts releases instead of
freeing, so the double release trips an assertion instead of undefined
behavior.
## I wrote the demos before I wrote the library
I built the demo apps first — one per shipping platform, driving every feature
I meant to ship, against that sixty-second Matroska — and the test suite
alongside them. Both were written as though the library underneath already
worked. It did not exist yet. What existed was an executable statement of what
working meant: a screen that plays a stream carrying three audio tracks and
lets you move between them, a Picture-in-Picture window that survives a seek,
a playlist that advances without losing an event on the way.
Then the agents closed the gap. They built and ran the apps and the suite,
hundreds of times over, on simulators where volume was the point and on real
hardware for the things that only fail there. They read the crash logs and
opened pull requests. Most of the code in this library came out of that loop,
written against a definition of done that already existed and could be checked
mechanically.
What changed is where my hours went. They stopped going into implementation
and started going into specification — into saying what correct meant
precisely enough that something other than me could decide whether it had been
reached. The issues in that repository are where the work went, and never in
the title. It is the acceptance criteria underneath that took the time: ten
thousand active media replacements under a sanitizer, with late metadata and
teardown callbacks. A seek soak on a physical device, with allocation
provenance retained. One combined row covering both PiP backends, so that a
passing backend cannot hide a failing one. Writing that well is harder than
writing the fix, and it is the part that does not delegate.
A loop that runs hundreds of times is worth exactly as much as its ability to
say no, and I learned that the expensive way. A batch of tests I had already
accepted turned out to contain sixteen that could never reach the condition
they were waiting on. They had been passing for months without testing
anything. A model will produce a plausible fix and a plausible test for it in
the same pass, and neither is worth anything until you break the fix and watch
the test fail.
So everything else I built exists to make that check cheap. Anything
load-bearing carries a red-green note in its commit body, recording that the
fix was reverted and the test watched failing. A coverage check reports which
patches the binary under test does *not* contain, because CI links a released
engine, and a patch in the tree is not a patch in the artifact. And the
release gate says what it is: *this does not run the tests — a person does, on
hardware. What it enforces is that the results exist, that every required row
was executed and passed, and that they describe this artifact rather than an
earlier one.*
The boundary sat in the same place every time. Volume and patience delegate
completely; ownership does not. Lock order, the moment a C object actually
dies, what AVKit expects of you that nobody ever wrote down — on those I would
get back something reasonable and wrong. The favorite wrong answer was a
timeout where the real answer was a rule about who owns what. A timeout
passes. It fails a month later, on someone else's network. Reading VLC's
source until the mechanism was understood is what I could not hand over. It is
also what produced the patches.
Both halves were necessary, and the double free is the proof — in the
direction I did not expect. The loop did not find it. Somebody else's crash
report did, against the commit I pin, and closing it meant sitting with VLC's
source until the vtable dispatch made sense. What the loop bought was
everything downstream: the deterministic reproduction, the sanitizer run, the
four hundred passes that showed the fix held. Diagnosis was mine. Proof was
not.
## What it cost
Four and a half months to 1.0, and it is still being paid.
The patch set costs the most. An ordered series against a pinned revision
means a rebase every time the pin moves — and pinning does not even buy a
stable world. One of those patches exists solely because a newer Autoconf
handed the C compiler a different standard flag from the one it handed the
Objective-C compiler. libtool could not infer a tag, and every Apple slice
died in `test/`, after libvlccore and libvlc had both linked. The same sources
built a fortnight earlier.
The engine ships as a static archive, which adds licensing obligations as
well as engineering work. libVLC uses LGPL 2.1. With static linking, providing
object files that let users relink against a modified library is one route to
compliance. [GNU's licensing FAQ](https://www.gnu.org/licenses/gpl-faq.en.html#LGPLStaticVsDynamic)
explains that requirement. Choosing a package format alone does not settle an
application's distribution obligations.
An open issue asks for a dynamic xcframework to make those requirements easier
to address. At the time of writing I had not resolved it: I expect a larger
binary, and am still weighing that against the distribution I want to support.
Static linking also creates an engineering problem: the process can contain
more than one copy of the engine.
The rest, briefly. The macOS PiP path that renders correctly cannot go in the
App Store, which means the best version of a feature I built is one I cannot
ship. The engine ships stripped of debug symbols and without a dSYM, so a
crash inside libVLC gives everyone shipping it a function name and no line
number. And physical-device qualification turned into a fifty-three-row matrix
and a harness whose own test file is longer than anything I wrote in the
library — because the things that break here break on hardware, and nothing
else is admissible as proof.
If you are considering wrapping a large C library, budget for its source
rather than its headers. The API surface looks like the work. It is bounded by
the header, and it is the same shape every time. What costs months is the part
where the engine's assumptions and your language's guarantees are both correct
and incompatible, and only one of them sits in a repository you can edit.
I stopped consuming the engine and started owning it, and an engine you own
hands you its licensing, its packaging and its bugs together, whether or not
you wrote any of them. That is the trade. I would make it again on Monday. But
it is a standing obligation, not a milestone you pass.
There is no total to give you. Picture-in-Picture on iOS still shuts itself
off on a plain seek — open on the tracker as I write this, with a fix merged
and not yet proven on hardware, reported by somebody I have never met. It is
the feature I left VLCKit to get. Two dozen patches into someone else's
engine, and the thing that started all of this is the thing still open.
If you've worked across a similar Swift and C boundary, [tell me which
assumption broke first](/en/contact). A small reproducer or a different
approach would be welcome. Share this with someone considering a direct
binding; I'd like to hear what their experience adds to mine.
---
# ربط libVLC بـSwift 6 مباشرةً
- URL: https://omaralbeik.com/ar/blog/binding-libvlc-directly-from-swift-6
- Markdown: https://omaralbeik.com/ar/blog/binding-libvlc-directly-from-swift-6.md
- Translation: https://omaralbeik.com/en/blog/binding-libvlc-directly-from-swift-6
- Author: Omar Albeik
- Language: ar
- Type: article
- Date: 3 آب 2026
- Topics: swift, open-source, software, engineering
[«تلفاز»](https://tilfaz.app) تطبيق IPTV متاح في متجر التطبيقات على iPhone
وiPad وMac وApple TV. في هذا النوع من التطبيقات، لا أختار صيغ الوسائط التي
تصلني. قد يرسل المزوّد MPEG-TS عبر UDP، أو قوائم HLS تتغير بين المقاطع، أو
ملفات MKV، أو ترجمات SSA بتنسيقها الخاص، أو صوتًا بترميز لا تدعمه آبل.
يعمل AVFoundation جيدًا مع الصيغ التي تدعمها آبل. لذلك لا يصح القول إنه لا
يصلح لتطبيقات IPTV عمومًا؛ قد تبني به تطبيق HLS يعمل دون مشاكل. تبدأ الصعوبة
عندما تحتاج إلى صيغ أخرى.
جرّبت حالة بسيطة: ملف MP4 يحتوي على فيديو H.264 وصوت AAC، أعدت تغليفه في
Matroska باستخدام `-c copy`. تحققت من البصمات للتأكد من أن بيانات الصوت
والفيديو لم تتغير. عمل ملف MP4، لكن ملف MKV أعاد الخطأ `-11828`، أي *صيغة
الوسيط هذه غير مدعومة*. لم تصل المحاولة إلى فك ترميز المحتوى، لأن AVFoundation
لا يقرأ حاوية Matroska.
يمكن التعامل مع الخطأ الصريح بإظهار رسالة مناسبة. الأصعب هو ما حدث في الصفوف
الثلاثة الأخيرة: يفتح macOS فيديو HEVC داخل تيار نقل، ويعيد `isPlayable ==
true` دون خطأ، لكن كائن الوسائط الناتج لا يحتوي على مسار فيديو. هذه صيغة
مألوفة في IPTV. يرى المستخدم شاشة سوداء ويسمع الصوت، ثم يبلغ عن عطل في
التطبيق، وهو محق.
لاحقًا، احتجت إلى ملف واحد لاختبار تطبيقات العرض الخاصة بالمكتبة. أنشأت ملف
Matroska مدته ستون ثانية، يحتوي على ثلاث نسخ للفيديو، وثلاثة مسارات صوت Opus،
وثلاثة مسارات ترجمة منها العربية، وستة فصول مسمّاة، وصورة غلاف مرفقة. جمع
الملف احتياجات التطبيق التي لم أستطع الوصول إليها عبر AVFoundation.
## كنتُ أستعمل VLCKit أصلًا
اخترت [libVLC](https://www.videolan.org/vlc/libvlc.html)، نواة تشغيل الوسائط
من VideoLAN وواجهة C التي يستخدمها VLC نفسه. كنت أستخدمها أصلًا من خلال
[VLCKit](https://code.videolan.org/videolan/VLCKit)، مكتبة VideoLAN لمنصات آبل
المكتوبة بـ Objective-C.
تعكس واجهة VLCKit أسلوب تطوير أطر الوسائط في 2013: بروتوكول delegate،
وإشعارات، وخاصية `id drawable` لإسناد واجهة العرض. هذا الأسلوب ما زال مستخدمًا
في برامج كثيرة، ولم يكن سبب انتقالي إلى حل آخر.
كنت أحتاج إلى ميزة «صورة داخل صورة». لا يوفرها VLCKit 3: لا توجد فيه الأنواع
والبروتوكولات الخاصة بها، ولا ملف `VLCDrawable.h`. تأتي الميزة في VLCKit 4،
الذي كان في طور ألفا منذ أيلول 2022 ويُوزّع من مسار يحمل اسم `unstable`.
كان أمامي خياران: الاعتماد على نسخة تجريبية للحصول على الميزة، أو ربط واجهة C
بنفسي. اخترت الثاني، ومنه جاءت بقية القرارات المتعلقة بالتزامن وإدارة الذاكرة
والتعديلات على المحرّك.
واصل VLCKit 4 التطور: أضاف visionOS وwatchOS، وأعاد كتابة إدارة الأحداث، وحسّن
دقة الانتقال داخل الوسائط، وأضاف دعم Swift Package Manager قبل أسبوعين من
كتابة المقالة. لذلك ستكون المقارنة غير عادلة إذا اعتمدت فقط على README الخاص
بالإصدار الثالث، الذي كان المستودع يعرضه آنذاك.
وفي اختياري مخاطرة مماثلة: أعتمد على libVLC 4 قبل صدور نسخة مستقرة منه. أما
VLCKit فما زال يحتفظ بإصدار يعمل مع libVLC 3 المستقر ويصلحه. إذا كانت أولوية
المشروع الاعتماد على محرّك مستقر، فذلك يرجّح VLCKit في هذه المقارنة.
وهناك [بلاغ مفتوح من فئة
Blocker](https://code.videolan.org/videolan/VLCKit/-/issues/759) على متتبّع
VideoLAN، سجله مطوّر آخر في تموز. يصف فشل إعادة توصيل خرج الفيديو عند إعادة
استخدام المشغّل: يستمر الصوت وتبقى الصورة سوداء على tvOS مع MPEG-TS مباشر. أي
أن المشكلة تظهر عند تبديل القنوات، وهي وظيفة أساسية في التطبيق.
## محاولة إصلاح VLCKit
في كانون الأول 2025 نشرت [`harflabs/VLC`](https://github.com/harflabs/VLC).
أجريت أربعة إيداعات في مساء واحد، ثم توقفت عن تطويرها.
كانت الحزمة تعيد توزيع أطر VLCKit 3.7.0 الثلاثة، بإطار لكل منصة، على هيئة
أهداف ثنائية في SPM. استخدمت شروط المنصة لاختيار الإطار المناسب. لم يكن VLCKit
3 يملك `Package.swift`، وأردت إضافته إلى المشروع من خلال رابط حزمة.
أرشفت الحزمة لاحقًا. كان ملفها يعلن `swift-tools-version: 6.0`، لكن ترويسات
الإطار لا تحتوي على توصيفات للتزامن. سهّلت إضافة VLCKit إلى المشروع، وبقي على
تطبيق SwiftUI التعامل مع نموذج كائنات يعتمد على delegate واحد ولا يوضح ضمانات
التزامن التي تحتاجها Swift 6.
بدأ [SwiftVLC](https://github.com/harflabs/SwiftVLC) في شباط، ووصل إلى الإصدار
1.0 في تموز. استغرق العمل أربعة أشهر ونصفًا.
## ما يتطلبه الربط المباشر مع C
كان القرار الأول أن أنتقل من C إلى Swift بلا Objective-C في المنتصف.
تظهر بساطة واجهة الاستخدام في هذا المثال، حيث يكفي View واحد لعرض الفيديو:
```swift
struct PlayerView: View {
@State private var player = Player()
var body: some View {
VideoView(player)
.onAppear { try? player.play(url: streamURL) }
}
}
```
يمرر `VideoView` كائنًا من نوع `NSView` أو `UIView` إلى libVLC عبر
`set_nsobject`، فيرسم VLC الفيديو فيه مباشرة. لا تحتاج إلى إنشاء طبقة عرض أو
استخدام `MTKView` أو `AVPlayerLayer`.
لكن الربط المباشر يجعل إدارة أعمار كائنات C مسؤوليتي. لكل كائن خطوة إنشاء
وخطوة تحرير، ويجب أن يبقى المؤشّر صالحًا طوال الفترة التي يستخدمه فيها كائن
Swift. يسهل وصف هذا في الحالة البسيطة؛ وتظهر الأخطاء عند انتقال الكائنات بين
الخيوط أو وصول أحداث أثناء تحريرها.
## طريقتان لنقل مؤشّر
لا يطابق `OpaquePointer` ولا `UnsafeMutableRawPointer` بروتوكول `Sendable`.
تمنع المكتبة القياسية هذه المطابقة عن قصد، لأن المترجم لا يعرف طبيعة الذاكرة
التي يشير إليها المؤشر أو من يستطيع الوصول إليها.
قد يسمح العزل القائم على المناطق بنقل قيمة منفصلة من نطاق عزل إلى آخر، لكنه لا
يحل الحالة هنا. فالمؤشر تلتقطه دالة مغلقة هاربة (escaping closure) موسومة بـ
`@Sendable`، كي تحرر كائن C خارج الخيط الرئيسي. هذا الالتقاط لا يعادل نقل قيمة
منفصلة.
أستخدم طريقتين في SwiftVLC. عند التقاط مؤشّر داخل `closure` واحدة، يمكن تعطيل
الفحص على الربط المحلي وحده:
```swift
nonisolated(unsafe) let p = pointer
DispatchQueue.global(qos: .utility).async {
libvlc_media_player_release(p)
}
```
يتحمل هذا المسار مسؤولية ضمان بقاء المؤشّر صالحًا حتى انتهاء العمل الذي
التقطه. أما الحالة التي تشاركها عدة خيوط، فأضعها داخل بنية موسومة بـ
`@unchecked Sendable` وأحمي الوصول إليها باستخدام `Mutex`. هنا يعتمد الأمان
على القفل وعلى طريقة استخدامه.
تمنع وثيقة البنية طريقة ثالثة: تحويل المؤشّر إلى عدد عبر `Int(bitPattern:)` ثم
تحويله إلى مؤشّر لاحقًا. قد تسكت هذه الطريقة تحذير المترجم، لكنها تخفي معنى
القيمة أيضًا. يصبح من الصعب تمييز عنوان ذاكرة يجب أن يبقى صالحًا عن عدد صحيح
عادي.
مع ذلك، يوجد استثناء واحد في الشيفرة: مسار لاختبارات التأهيل يحتفظ بعنوان
المشغّل في `UInt`، ثم يعيده مباشرة إلى مؤشّر. يذكر تعليق الحقل أن السبب هو عدم
مطابقة `OpaquePointer` لـ `Sendable`. تركت هذا الموضع كما هو، لكنه يظل
استثناءً من القاعدة يحتاج إلى مراجعة.
## إدارة عمر المؤشرات
تمر الأحداث بثلاث مراحل: callbacks من C على خيوط libVLC، ثم `Broadcaster` الذي
يوزعها على المشتركين، ثم خصائص `@Observable` على `@MainActor`.
تنسخ `Broadcaster.broadcast` قائمة المشتركين وهي تحمل القفل، ثم تحرره قبل
تشغيل المرشحات وتسليم القيم.
قد يحدث توقف متبادل إذا جرى التسليم أثناء الاحتفاظ بالقفل. مرشّح المشترك شيفرة
خارجية قد تستدعي `Broadcaster` من جديد للاشتراك أو البث أو الاستعلام. سيحاول
الاستدعاء الحصول على القفل نفسه، وهو لا يسمح بإعادة حيازته.
كذلك، تعمل `onTermination` فورًا على الخيط الذي ألغى المهمة المستهلكة. وهي
تستدعي `unsubscribe` التي تحتاج إلى القفل نفسه. إذا وقع الإلغاء أثناء البث،
فقد ينتظر الخيط قفلًا يحمله بالفعل.
أضفت اختبارًا يمنع عودة هذا الخطأ، لأن نقل سطر التسليم إلى داخل القفل قد يعيده
بسهولة. لم يكن الاختبار موجودًا عندما كُتبت الشيفرة الأولى. وقد يفوت هذا النوع
من المشاكل اختبارات سريعة، ثم يظهر أثناء استخدام التطبيق للبث المباشر.
يوفر النوع طريقتين للإغلاق. تنهي `finishAll()` تدفقات المشتركين الحاليين وتسمح
باشتراكات جديدة. أما `terminate()` فتنهي التدفقات الحالية وتجعل أي اشتراك لاحق
يعيد تدفقًا منتهيًا فورًا.
نحتاج إلى الثانية لأن بعض الخصائص المحسوبة تنشئ اشتراكًا مع كل قراءة. إذا
انتهى المنتج قبل الاشتراك، يجب أن يحصل المستهلك على تدفق منتهٍ. وإلا سيبقى
ينتظر في `await` دون أن تصل قيمة أو إشارة انتهاء.
قسّمت الأحداث أيضًا إلى تدفقين. يجمع callback في libVLC أحداث توقيت وأحداث
تحكم، لكن إسقاط أحداث التوقيت عند ازدحامها لا يبرر إسقاط حدث تحكم.
يعتمد ترتيب تحرير الموارد على ما لا يزال يستخدم كل مورد. قبل تحرير كائن، يجب
التأكد من انتهاء الجهات التي قد تقرأه:
وُثقت القيود الثلاثة في تعليق فوق دالة التحرير. لا يفرضها المترجم، ولذلك يجب
مراجعتها عند تغيير هذا المسار.
## المؤشّر ليس هويّة
وصلت إلى هذه المشكلة متأخرًا، وكان من المفيد تصميم الحل منذ البداية.
يمكن أن يستبدل `Player` مشغّل libVLC الداخلي مع بقاء كائن Swift وتدفقات
أحداثه. قد تصل بعد الاستبدال callbacks تخص المشغّل القديم. مقارنة المؤشّرات
وحدها لا تكفي لمعرفة مصدر الحدث، لأن مخصّص الذاكرة قد يعيد استخدام عنوان كائن
حُرر سابقًا.
لذلك أعطي كل طبقة قابلة للاستبدال رقم جيل يزداد مع كل استبدال. يحتفظ الحدث
بأرقام الأجيال وقت إنشائه، ويمكن رفضه إذا لم تعد تطابق الحالة الحالية.
أضفت هذه الأرقام تدريجيًا بعد ظهور عدة أخطاء. وعند مراجعة المكتبة بعد الإصدار
1.0، كانت مجموعة كبيرة من المشكلات تتعلق بأحداث متأخرة تخص حالة سابقة. لو بدأت
من جديد، لأضفت أرقام الأجيال منذ اليوم الأول، خصوصًا للكائنات التي تبقى بعد
انتهاء الاستدعاء الذي أنشأها.
## إصلاح مسارات عرض الفيديو
عند فتح خرج الفيديو، ينسخ libVLC مؤشّرات callbacks وسياقها. مسحها من مشغّل
الوسائط لاحقًا لا يمحو النسخة التي يحتفظ بها الخرج. لذلك فإن مسح callbacks ثم
تحرير السياق مباشرة قد يؤدي إلى استخدام ذاكرة محررة.
يربط الحل كل سياق بمؤشّر `libvlc_media_player_t` محدد. يتيح ذلك انتقال
المسؤولية بين المتحكمات التي تستخدم المشغّل نفسه دون أن يغيّر خرج فيديو حالة
خرج آخر.
عند إيقاف السياق، أمنع بدء عمل عرض جديد، لكنني لا أحرره قبل انتهاء آخر عملية
تحرير محسوبة للمشغّل واكتمال callbacks الجارية. الانتظار مدة ثابتة لا يثبت أن
هذه العمليات انتهت؛ يجب أن يعكس التحرير عمر الكائن الفعلي.
للعرض أربعة مسارات، تختلف في الجهة التي تملك الكائنات وتتحمل مسؤولية تحريرها:
كان القرار الأصعب متعلقًا بـ macOS. في الإصدارات التي أدعمها، يقص مسار عرض
sample buffers العام الصورة بنسبة 1:1 بدل تحجيمها داخل نافذة «صورة داخل صورة».
المسار الذي أعطى النتيجة الصحيحة يستخدم إطارًا خاصًا: تحميل
`PIPViewController` من `PIP.framework` وقت التشغيل، ونقل View الذي يرسم فيه
VLC إلى النافذة.
يوفر libVLC متحكمًا لميزة «صورة داخل صورة»، ويستخدمه كلا الغلافين. لكن ملفات
بناء VLC تقصره على iOS وtvOS. لا يوجد هذا الصنف في نسخة macOS من المحرّك الذي
أوزعه، ولذلك لا أستطيع استخدامه هناك.
جعلت استخدام الإطار الخاص خيارًا يحتاج إلى تفعيل صريح. وجمعت استدعاءات واجهات
آبل الخاصة في ملف واحد لتسهيل مراجعتها. هذا التنظيم لا يجعلها مقبولة في متجر
التطبيقات؛ ولهذا لا تعمل الميزة بهذا المسار افتراضيًا.
على iOS، تعلن المكتبة أن الميزة غير متاحة في المحاكي. قد يبلغ AVKit في المحاكي
أن المتحكم يعمل بينما تبقى نافذة النظام سوداء. لا أريد لاختبار يكتفي بهذه
الإشارة أن يسجل نجاحًا دون صورة فعلية.
واحتاج مسار vmem إلى معلومات عن أبعاد الفيديو لم تكن واجهة libVLC توفرها. أضفت
دوال إلى واجهة C، ثم احتجت إلى الحفاظ على التوافق مع الأرشيفات التي بُنيت قبل
هذه الإضافات.
## قراءة تنفيذ libVLC
بدأ العمل بقراءة ترويسات libVLC، ثم امتد إلى قراءة تنفيذه وتعديل بعض أجزائه.
احتوى الإصدار 1.0 على ست رقع. وأُضيفت التسع عشرة الباقية خلال ثمانية أيام بدأت
بعد الإصدار باثني عشر يومًا. عندها انتقلت من معالجة سلوك المحرّك في الغلاف إلى
إصلاحه داخل VLC.
بعض الرقع إصلاحات أُضيفت إلى VLC بعد المراجعة التي ثبّتُّ عليها البناء. من
أمثلتها إصلاح مؤقّت المشغّل: كانت النسخة المثبتة تواصل حساب الزمن بعد الإيقاف،
فتتقدم قيمة `Player.currentTime` رغم توقف الفيديو. ومن هذه القيمة يُضبط مرجع
زمن «صورة داخل صورة»، لذلك كان شريط التقدم يتحرك فوق فيديو متوقف.
نقلت مع الإصلاحات ثلاث تغييرات تمهيدية من المشروع الأصلي تعتمد عليها. يحوّل
أحدها راية الاستقراء إلى تعداد يضيف إليه الإصلاح حالة جديدة. أبقيت هذه
التغييرات كما هي، حتى أستطيع إعادة تطبيقها عند تحديث VLC، بدل صيانة نسخة أعيدت
كتابتها خصيصًا للبنية القديمة.
وكتبت بعض الإصلاحات بنفسي، منها إصلاح تحرير مزدوج في قارئ البث التكيّفي في
VLC.
عند فشل `prepareChunk()`، تحرر `ISegment::toChunk()` مصدر البيانات مرتين:
تستدعي `recycleSource()` صراحة، ثم تحذف القطعة، فيحرره `~AbstractChunk()` مرة
أخرى لأنه يملكه. في هذا المسار، لا يُحتفظ بالمصدر لإعادة استخدامه؛ يصل
الاستدعاء الأول إلى `delete` مباشرة. وعند محاولة التحرير الثانية، يُستخدم جدول
الدوال الافتراضية لكائن حُررت ذاكرته بالفعل.
بدأ الخطأ بتغيير من سطر واحد في 2022: نُسخ استدعاء إعادة التدوير من الفرع
التالي إلى هذا الفرع. كان الاستدعاء صحيحًا في موضعه الأصلي، لأن
`createChunk()` لم تُرجع قطعة تملك المصدر. أما في الفرع الآخر، فالقطعة موجودة
ومسؤولة عن تحريره. السطر نفسه صار هنا تحريرًا مزدوجًا.
عند كتابة المقالة، كان الخطأ ما يزال في فرع VLC الرئيسي. ويصف [بلاغ في متتبّع
VideoLAN](https://code.videolan.org/videolan/vlc/-/work_items/29845) انهيارًا
متقطعًا من نوع `EXC_BAD_ACCESS` على iOS arm64 بعد نحو عشر دقائق من تشغيل HLS،
مع مكدس استدعاءات ينتهي عند دالة الهدم.
يفسر مسار التنفيذ ظهور المشكلة بعد نحو عشر دقائق. لا تعمل `prepareChunk()` إلا
للمقاطع المشفرة، ولا تفشل في هذا المسار إلا عند تعذر الحصول على المفتاح. ولأن
المفاتيح تُخزن مؤقتًا، قد يظهر الخطأ عند تبديلها أو بعد إخلاء الذاكرة المؤقتة،
بدل ظهوره عند بدء التشغيل.
احتاج ظهور المشكلة إلى مقاطع مشفرة، وتعذر الحصول على مفتاح AES-128، وشبكة
متذبذبة، وجهاز فعلي، ومرور نحو عشر دقائق. لم تكتشفها اختباراتي. واجهها مطوّر
آخر على نسخة المحرّك نفسها وسجلها في المشروع الأصلي. وجدت سببها بقراءة علاقات
ملكية الكائنات، ثم أعدت إنتاجها بصورة حتمية. أضفت اختبارًا إلى اختبارات VLC
للبث التكيّفي يعدّ مرات التحرير دون تحرير الذاكرة فعلًا، حتى يكشف التحرير
المزدوج بفشل واضح بدل السلوك غير المعرّف.
## كتبتُ العروض قبل أن أكتب المكتبة
بدأت بتطبيق عرض لكل منصة وبمجموعة اختبارات، اعتمادًا على ملف Matroska ذي
الستين ثانية. كتبتها وفق الواجهة التي أردت للمكتبة أن توفرها قبل اكتمال
تنفيذها: تبديل المسارات الصوتية، والانتقال داخل الفيديو أثناء «صورة داخل
صورة»، وتشغيل العنصر التالي دون فقدان أحداث التحكم.
استخدمت وكلاء برمجيين لتنفيذ المكتبة وتشغيل التطبيقات والاختبارات مئات المرات.
شغّلت الاختبارات المتكررة على المحاكيات، واستخدمت الأجهزة الفعلية لما لا يظهر
إلا عليها. قرأ الوكلاء سجلات الانهيار وفتحوا طلبات دمج، وكان أمامهم وصف قابل
للاختبار للسلوك المطلوب.
أصبحت أقضي وقتًا أطول في تحديد السلوك الصحيح ومعايير قبوله. مثلًا: عشرة آلاف
استبدال للوسائط أثناء التشغيل تحت أدوات فحص الذاكرة والخيوط، مع وصول بيانات
متأخرة وcallbacks أثناء التحرير. واختبار طويل للانتقال داخل الفيديو على جهاز
فعلي، مع تسجيل مصدر تخصيص الذاكرة. ومقارنة مساري «صورة داخل صورة» في صف واحد،
حتى لا يخفي نجاح أحدهما فشل الآخر. كتابة هذه الشروط بدقة كانت من أصعب أجزاء
العمل.
وتعلمت أن كثرة مرات التشغيل لا تعني أن الاختبارات مفيدة. راجعت مجموعة كنت قد
قبلتها، فوجدت ستة عشر اختبارًا لا تصل أصلًا إلى الحالة التي يفترض أن تفحصها.
كانت تنجح منذ أشهر. لذلك صرت أعطّل الإصلاح عمدًا وأتأكد من فشل الاختبار قبل
الاعتماد عليه.
صممت الأدوات التالية لتسهيل هذا التحقق. توثق الإيداعات المهمة تجربة تعطيل
الإصلاح وفشل الاختبار. ويفحص تقرير التغطية الرقع الموجودة فعلًا في النسخة
الثنائية التي تختبرها CI، فقد توجد الرقعة في المستودع ولا تكون ضمن المحرّك
المرتبط بالاختبارات.
أما فحص الإصدار فلا يشغّل اختبارات الأجهزة بنفسه. يتحقق من وجود نتائج لكل حالة
مطلوبة، ونجاحها، وانتمائها إلى النسخة المراد إصدارها. تشغيلها على الأجهزة يظل
خطوة مستقلة.
أفادني الوكلاء في التنفيذ المتكرر وتشغيل الاختبارات، لكنني بقيت مسؤولًا عن
مراجعة ملكية الذاكرة وترتيب الأقفال ومتطلبات AVKit غير الموثقة. كثيرًا ما بدا
اقتراح مهلة زمنية معقولًا، بينما كان الحل الصحيح تحديد متى ينتهي استخدام
الكائن. قد تعمل المهلة في الاختبار ثم تفشل لاحقًا على شبكة مختلفة. احتجت إلى
قراءة شيفرة VLC لفهم هذه الحالات.
يوضح التحرير المزدوج حدود هذه الطريقة وفائدتها معًا. لم تكتشفه دورة الاختبارات
الآلية؛ كشفه بلاغ من مطوّر آخر، وحددت السبب بقراءة الشيفرة. ثم ساعدتني الأتمتة
على إعادة إنتاجه، وتشغيل أدوات فحص الذاكرة، والتحقق من الإصلاح عبر أربع مئة
محاولة.
## ما كلّفه ذلك
استغرق الوصول إلى 1.0 أربعة أشهر ونصفًا، وما زالت هناك أعمال صيانة ومشكلات
مفتوحة.
أكبر التزامات الصيانة هو الحفاظ على الرقع عند تحديث نسخة VLC. وحتى تثبيت
النسخة لا يثبت بيئة البناء كلها. احتجت إلى رقعة لأن إصدارًا أحدث من Autoconf
مرر إعدادًا لمعيار اللغة إلى مترجم C يختلف عن إعداد Objective-C. عجز libtool
عن تحديد الوسم المناسب، وفشلت أهداف آبل في `test/` بعد نجاح ربط libvlccore
وlibvlc. كانت المصادر نفسها قد بُنيت بنجاح قبل أسبوعين.
أوزّع المحرّك في أرشيف ساكن، وهذا يضيف التزامات تتعلق بالترخيص. تستخدم libVLC
رخصة LGPL 2.1؛ ومن خيارات الامتثال عند الربط الساكن توفير ملفات الكائنات التي
تتيح للمستخدم إعادة الربط بنسخة معدّلة من المكتبة. تشرح
[أسئلة GNU عن الربط الساكن والديناميكي](https://www.gnu.org/licenses/gpl-faq.en.html#LGPLStaticVsDynamic)
هذا الجانب. لا يحسم اختيار صيغة الحزمة وحده متطلبات توزيع التطبيق.
هناك طلب مفتوح لإصدار xcframework ديناميكي لتسهيل التعامل مع هذه المتطلبات. لم
أحسمه عند كتابة المقالة: أتوقع أن يزيد حجم الملفات الثنائية، وما زلت أوازن ذلك
مع طريقة التوزيع التي أريد دعمها.
ويضيف الربط الساكن مشكلة هندسية أيضًا: قد تضمّن أكثر من نسخة من المحرّك داخل
العملية نفسها.
وتبقى قيود أخرى. المسار الذي يعرض «صورة داخل صورة» بصورة صحيحة على macOS
يستخدم واجهات خاصة، فلا أستطيع إصداره في متجر التطبيقات. وأوزع المحرّك دون
رموز تنقيح أو ملفات dSYM، فتظهر الانهيارات داخله بأسماء الدوال دون أرقام
الأسطر. كذلك أصبحت اختبارات التأهيل على الأجهزة الفعلية تتضمن ثلاثة وخمسين
صفًا، مع أدوات اختبار كبيرة لأن المحاكيات لا تكفي لإثبات صحة هذه الحالات.
إذا أردت ربط مكتبة C كبيرة، فخصص وقتًا لقراءة تنفيذها وصيانته. الترويسات تحدد
الدوال التي ستستدعيها، لكنها لا تشرح كل الافتراضات المتعلقة بالخيوط والذاكرة.
وقد يتطلب التوفيق بينها وبين ضمانات Swift تعديل المحرّك نفسه.
الربط المباشر حمّلني مسؤولية الترخيص والتوزيع ومشكلات المحرّك، إلى جانب واجهة
Swift. ما زلت أختار هذا الطريق، لكن صيانته تستمر بعد إصدار المكتبة.
وعند كتابة المقالة، كانت «صورة داخل صورة» على iOS ما زالت تتوقف أحيانًا عند
الانتقال داخل الفيديو. سجل المشكلة مستخدم لم ألتقه، ودُمج إصلاح لم يكتمل
التحقق منه على الأجهزة بعد. هذه هي الميزة التي تركت VLCKit للحصول عليها، وما
زالت تحتاج إلى عمل بعد كل تلك الرقع.
إذا عملت على ربط Swift بمكتبة C، [أخبرني عن أكثر ما فاجأك](/ar/contact). أرحب
بمثال صغير يعيد إنتاج المشكلة، أو بطريقة مختلفة لحلها. وشارك المقالة مع مطوّر
يفكر في الربط المباشر؛ ربما تكمل تجربته ما تعلمته هنا.
---
# Namespace your Swift extensions
- URL: https://omaralbeik.com/en/blog/namespace-your-swift-extensions
- Markdown: https://omaralbeik.com/en/blog/namespace-your-swift-extensions.md
- Translation: https://omaralbeik.com/ar/blog/namespace-your-swift-extensions
- Author: Omar Albeik
- Language: en
- Type: article
- Date: 19 February 2022
- Topics: swift, api-design, open-source, software, engineering
Extensions are the feature that made me like Swift. You can add behavior to a
class, a struct, an enum, even a protocol, without subclassing it and without
owning its source. When I started writing Swift I liked it enough to build
[SwifterSwift](https://github.com/SwifterSwift/SwifterSwift) out of it, which
now carries more than five hundred extensions on the standard library and on
UIKit.
Somewhere past the first hundred, the pull requests started arriving with the
same problem. A useful extension is useful to more than one person, so the
better an idea is, the likelier it already ships in a library the same app
depends on.
## The collision
Two modules, both extending `Date`. One is yours; the other is something the
app already depends on and is not going to drop.
```swift
// Module A
extension Date {
public var isToday: Bool { ... }
}
// Module B — yours
extension Date {
public var isToday: Bool { ... }
}
```
At the call site:
```swift
Date().isToday // Ambiguous use of 'isToday'
```
The instinct is to qualify it, the way you would with two types of the same
name: `A.Date` and `B.Date` are both perfectly sayable. But a module name
qualifies a type. It does not qualify a member added to somebody else's type,
and there is no spelling of `B.isToday`, because `isToday` was never in module
B's namespace. It went into `Date`'s, next to `timeIntervalSinceNow`, and so
did the other one.
The consequence is easy to miss: a member you add to a type you do not own is
not scoped to your library at all. It is global, and it shares a namespace with
every other module in the build.
Ambiguity errors are the visible symptom. The other one appeared in SwifterSwift
years before anyone filed a bug: type a dot after a `String` in a project that
imports it, and autocomplete offers a hundred members, most of them mine, none
of them marked as such. Nothing is broken. It is just no longer possible to
tell at a glance which of these came with the language.
## A namespace of your own
If you have used RxSwift, Kingfisher or SnapKit you have already typed the
answer: `view.rx`, `imageView.kf`, `view.snp`. Each of them keeps its additions
behind a short property instead of putting them on the type.
It takes two pieces. A generic wrapper holding the value being extended:
```swift
public struct Extension {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
```
And a protocol whose only job is to hand out that wrapper:
```swift
public protocol ExtensionCompatible {}
extension ExtensionCompatible {
public var ext: Extension { Extension(self) }
public static var ext: Extension.Type { Extension.self }
}
```
`Self` rather than an `associatedtype`: the wrapped type is always the
conforming type, and an associated type that is only ever `Self` adds a line to
explain and nothing else.
The static overload is there so `UIColor.random` has somewhere to go. Without
it the namespace covers instance members only, the static ones stay on the bare
type, and half the library is back in the collision you just left.
Now conform the type once, and extend the wrapper instead of the type:
```swift
extension UILabel: ExtensionCompatible {}
extension Extension where Base: UILabel {
public var trimmedText: String? {
let text = base.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return text.isEmpty ? nil : text
}
}
```
```swift
let label = UILabel()
label.text = " hello world! \n\n"
label.text // " hello world! \n\n"
label.ext.trimmedText // "hello world!"
```
One conformance per type, and everything you add for that type afterwards goes
on the wrapper. Module A keeps its `isToday` and you keep yours, because yours
is on `Extension` and its is on `Date`. Two libraries that both do this
do not collide with each other either, as long as they chose different property
names — and `rx`, `kf` and `snp` suggest the convention holds in practice.
## What it does not cover
Mutation through the wrapper is the first trap. You will find a version of this
pattern with an empty setter on `ext`:
```swift
public var ext: Extension {
get { Extension(self) }
set { } // makes `foo.ext.thing = x` compile
}
```
It does make the assignment compile. For a class that is harmless: the wrapper
holds a reference, so writing through it reaches the same object. For a struct
it is worse than a compile error — the write lands on a temporary copy, the
empty setter throws it away, and the call site looks exactly like code that
works. Keep `base` a `let`, keep the wrapper read-through, and write mutations
as methods that take the value `inout` or return a new one.
Protocol conformances cannot be namespaced at all. `extension Date: Identifiable`
is a fact about `Date` for the whole program, and a second module declaring the
same conformance is a conflict no wrapper resolves. Operators are the same:
they are matched on the types of their operands and never see your namespace.
For both, the old advice stands — do not put them on types you do not own, in
code other people depend on.
And it costs four characters at every call site, forever.
`label.ext.trimmedText` is not as nice to write as `label.trimmedText`, and no
argument about namespaces makes it nicer. What you get back is that a reader
can see where the member came from, and that your additions sit together rather
than scattered through a type that already has two hundred members.
For a type you own, none of this applies; extend it directly. The pattern pays
for itself when you are adding to somebody else's type, in code somebody else
will depend on — a narrower case than it sounds, and nearly the whole of what a
library does.
SwifterSwift is the case in point, and it is too late for it. Five hundred
extensions on types nobody in that repository owns is exactly what the wrapper
is for, and adding one now would rename every member in the library at once. A
namespace cannot be introduced quietly later, so it has to be chosen before the
first release — when the library still looks too small to need one.
Have you introduced a namespace after a library was already in use? I'd be
interested in [how you handled the migration](/en/contact). If your team is
debating extension names, share this article as a starting point for that
discussion.
---
# تنظيم إضافات Swift في فضاء أسماء مستقل
- URL: https://omaralbeik.com/ar/blog/namespace-your-swift-extensions
- Markdown: https://omaralbeik.com/ar/blog/namespace-your-swift-extensions.md
- Translation: https://omaralbeik.com/en/blog/namespace-your-swift-extensions
- Author: Omar Albeik
- Language: ar
- Type: article
- Date: 19 شباط 2022
- Topics: swift, api-design, open-source, software, engineering
كانت الإضافات من أول ما أحببته في Swift. تستطيع إضافة سلوك إلى `class` أو
`struct` أو `enum` أو `protocol` دون وراثة أو تعديل الشيفرة الأصلية. أعجبتني
الفكرة حتى بنيت عليها
[SwifterSwift](https://github.com/SwifterSwift/SwifterSwift)، التي تضم أكثر من
خمسمئة إضافة للمكتبة القياسية وUIKit.
بعد أول مئة إضافة تقريبًا، بدأت مشكلة تتكرر في طلبات الدمج: قد تكون الإضافة
المفيدة موجودة أصلًا في مكتبة أخرى يستخدمها التطبيق. عندها يتعارض الاسمان.
## عندما تتعارض أسماء الإضافات
لنفترض أن وحدتين تضيفان `isToday` إلى `Date`. إحداهما مكتبتك، والثانية مكتبة
أخرى يحتاج إليها التطبيق:
```swift
// الوحدة A
extension Date {
public var isToday: Bool { ... }
}
// الوحدة B — وحدتك
extension Date {
public var isToday: Bool { ... }
}
```
وعند الاستدعاء:
```swift
Date().isToday // Ambiguous use of 'isToday'
```
قد تحاول تحديد العضو المقصود باسم الوحدة، كما تفعل عند تشابه أسماء الأنواع.
لكن اسم الوحدة يميز النوع، ولا يميز عضوًا أضافته إلى نوع خارجي. لا يمكنك كتابة
`B.isToday` لحل المشكلة؛ كلتا الإضافتين موجودتان في فضاء أسماء `Date` نفسه.
أي أن الإضافات على الأنواع الخارجية لا تبقى محصورة في مكتبتك. إنها تشارك بقية
الوحدات فضاء أسماء النوع الذي أضفتها إليه.
حتى دون تعارض يمنع البناء، توجد مشكلة أخرى. عند كتابة نقطة بعد قيمة `String`
في مشروع يستخدم SwifterSwift، تظهر اقتراحات كثيرة من إضافاتي، دون علامة واضحة
تميزها عن أعضاء Swift الأصلية. يصبح العثور على الدالة المناسبة ومعرفة مصدرها
أصعب.
## فضاء أسماءٍ خاصٌّ بك
تستخدم RxSwift وKingfisher وSnapKit حلًا مألوفًا: `view.rx` و`imageView.kf`
و`view.snp`. تجمع كل مكتبة إضافاتها تحت خاصية قصيرة تميزها.
نحتاج أولًا إلى غلاف يأخذ نوعًا عامًا (generic) ويحتفظ بالقيمة الأصلية:
```swift
public struct Extension {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
```
ثم نعرّف بروتوكولًا يتيح الوصول إلى الغلاف:
```swift
public protocol ExtensionCompatible {}
extension ExtensionCompatible {
public var ext: Extension { Extension(self) }
public static var ext: Extension.Type { Extension.self }
}
```
استخدمت `Self` لأن النوع داخل الغلاف هو دائمًا النوع المطابق للبروتوكول. لا
نحتاج إلى `associatedtype` مستقل للتعبير عن العلاقة نفسها.
تتيح نسخة `static` إضافة أعضاء على مستوى النوع، مثل بديل لـ `UIColor.random`.
بدونها، سيقتصر الغلاف على أعضاء القيم والمثيلات.
بعد ذلك نضيف مطابقة البروتوكول إلى النوع، ونكتب الإضافات على الغلاف:
```swift
extension UILabel: ExtensionCompatible {}
extension Extension where Base: UILabel {
public var trimmedText: String? {
let text = base.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return text.isEmpty ? nil : text
}
}
```
```swift
let label = UILabel()
label.text = " hello world! \n\n"
label.text // " hello world! \n\n"
label.ext.trimmedText // "hello world!"
```
نضيف المطابقة مرة واحدة لكل نوع. بعد ذلك تصبح إضافاتنا على `Extension`
مثلًا، بينما تبقى إضافات المكتبة الأخرى على `Date`. ويمكن لمكتبتين استخدام هذا
الأسلوب دون تعارض إذا اختارتا اسمين مختلفين لخاصية الوصول إلى الغلاف، كما في
`rx` و`kf` و`snp`.
## ما لا يشمله هذا
انتبه إلى تعديل القيم من خلال الغلاف. بعض تطبيقات هذا الأسلوب تضيف `setter`
فارغًا إلى `ext`:
```swift
public var ext: Extension {
get { Extension(self) }
set { } // makes `foo.ext.thing = x` compile
}
```
يسمح ذلك بترجمة الإسناد، لكنه قد يخفي خطأ. مع `class`، يحتفظ الغلاف بمرجع إلى
الكائن، فيصل التعديل إليه. أما مع `struct`، فقد يعدّل نسخة مؤقتة ثم يتجاهلها
`setter` الفارغ. تبدو الشيفرة صحيحة دون أن تحتفظ بالتغيير.
لذلك أبقي `base` ثابتًا باستخدام `let` وأستخدم الغلاف للقراءة. أما التعديل
فأجعله في دوال تستقبل القيمة بـ `inout` أو تعيد قيمة جديدة.
هذا الحل لا يعزل مطابقة البروتوكولات. كتابة `extension Date: Identifiable`
تنطبق على النوع في البرنامج كله، وقد تتعارض مع مطابقة تعلنها وحدة أخرى. وكذلك
تعتمد المعاملات على أنواع القيم التي تستقبلها. تجنب إضافة هذه المطابقات
والمعاملات إلى أنواع خارجية في مكتبة يستخدمها الآخرون.
في المقابل، يضيف الغلاف أربعة أحرف إلى كل استدعاء: `label.ext.trimmedText`
أطول من `label.trimmedText`. لكن القارئ يستطيع معرفة مصدر الإضافة، وتبقى أعضاء
المكتبة مجتمعة بدل اختلاطها بأعضاء النوع الأصلي.
إذا كان النوع ملكك، فأضف إليه مباشرة. يفيد الغلاف خصوصًا عند توسيع نوع خارجي
في مكتبة ستدخل مشاريع لا تتحكم في بقية تبعياتها.
أحتاج إلى هذا التنظيم في SwifterSwift، لكن إدخاله الآن سيغيّر طريقة استدعاء
أكثر من خمسمئة إضافة. لن يكون تحديثًا بسيطًا لمستخدمي المكتبة. لهذا ينبغي
اختيار فضاء الأسماء قبل الإصدار الأول، حين قد تبدو المكتبة أصغر من أن تحتاج
إليه.
هل أضفت فضاء أسماء إلى مكتبة يستخدمها الآخرون بالفعل؟ يهمني أن أعرف [كيف
تعاملت مع الانتقال](/ar/contact). وإذا كان فريقك يناقش تنظيم الإضافات، فشارك
المقالة لتبدأوا النقاش من مثال عملي.
---
# Enforce SSH instead of HTTPS for Git operations
- URL: https://omaralbeik.com/en/blog/enforce-ssh-instead-of-https-for-git-operations
- Markdown: https://omaralbeik.com/en/blog/enforce-ssh-instead-of-https-for-git-operations.md
- Translation: https://omaralbeik.com/ar/blog/enforce-ssh-instead-of-https-for-git-operations
- Author: Omar Albeik
- Language: en
- Type: tutorial
- Date: 23 August 2021
- Topics: tooling, software, engineering
Ten days ago GitHub stopped accepting account passwords for Git operations over
HTTPS. If you push over HTTPS you now paste a personal access token instead: a
longer secret, kept wherever the password was, expiring on a schedule you have
to remember.
A credential helper takes the typing out of that — `osxkeychain`, Git
Credential Manager, `gh auth login` — and if tokens suit you, that is a fine
answer. What it cannot take out is the expiry. Every few months the token
lapses and you are back on the settings page, generating another one and
trying to remember which scopes it had.
An SSH key has no expiry date. You generate a pair once, keep the private half
on your machine, hand the public half to the host, and the arrangement holds
until you revoke it. It also reaches somewhere a credential helper cannot: the
HTTPS URLs you did not write, in repositories and lockfiles belonging to other
people.
The first two steps below are in every guide. The two after them are the ones
that make this stick.
## Generate a key
```bash
ssh-keygen -t ed25519 -C "personal github" -f ~/.ssh/personal-github
```
Ed25519 rather than RSA: shorter keys, faster handshakes, and no key-size
argument to get wrong. For anything older than OpenSSH 6.5, `-t rsa -b 4096`
is the fallback.
Name the key after what it unlocks — `personal-github`, `work-gitlab` — and run
`ssh-keygen` once per account. GitHub refuses a public key already registered
to another account, so two accounts force two keys whether you planned for them
or not. Generate separately on each machine as well, and keep every private
half where it was made: a key that exists in one place is a key you can revoke
in one place. `id_ed25519_2` tells you nothing on the day you need to revoke it.
Use a passphrase. Loaded into `ssh-agent` it costs one prompt per session
rather than one per push.
## Add the public key to the host
Copy the public half, the file ending in `.pub`. The one without an extension
stays where it was generated:
```bash
# macOS
pbcopy < ~/.ssh/personal-github.pub
# Linux
xclip -selection clipboard < ~/.ssh/personal-github.pub
```
Then paste it into your account settings:
[GitHub](https://docs.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account),
[GitLab](https://docs.gitlab.com/ee/ssh/), or
[Bitbucket](https://support.atlassian.com/bitbucket-cloud/docs/set-up-an-ssh-key/).
## Tell SSH which key to use
Left to itself, SSH tries the default names — `id_ed25519`, `id_rsa` — so a key
called `personal-github` is never offered. In `~/.ssh/config`:
```ssh-config
Host github.com
User git
IdentityFile ~/.ssh/personal-github
IdentitiesOnly yes
AddKeysToAgent yes
Host gitlab.com
User git
IdentityFile ~/.ssh/work-gitlab
IdentitiesOnly yes
AddKeysToAgent yes
```
`IdentitiesOnly yes` earns its line. Without it SSH offers every key the agent
holds, and GitHub authenticates you as whichever account matches the first one
that fits — so a repository you have access to comes back as "not found". It
reads as a permissions bug and is not one.
On macOS, `UseKeychain yes` in each block keeps the passphrase in the login
keychain across restarts. It belongs to Apple's OpenSSH rather than upstream,
so if Homebrew's `openssh` is ahead on your `PATH` it will refuse to start.
Load the key into the keychain once with `ssh-add -K ~/.ssh/personal-github`.
Connect once, both to check the key and to answer the question SSH asks the
first time it meets a host:
```bash
ssh -T git@github.com
```
The prompt shows the server's host key fingerprint. Compare it against the
fingerprints GitHub publishes before answering `yes`: that prompt is the whole
of SSH's server authentication, and it is the easiest thing on this page to
answer by reflex. After it, a greeting with your username means the key works.
If the connection hangs instead, the network is probably blocking port 22.
GitHub answers SSH on 443 as well:
```ssh-config
Host github.com
Hostname ssh.github.com
Port 443
# ...the rest of the block as above
```
Worth setting before you need it. After the next step, HTTPS is no longer
available as a fallback.
## Rewrite HTTPS URLs to SSH
A key does nothing while your remotes still say `https://`. Rather than fixing
them one repository at a time, tell Git to substitute, in `~/.gitconfig`:
```ini
[url "ssh://git@github.com/"]
insteadOf = https://github.com/
[url "ssh://git@gitlab.com/"]
insteadOf = https://gitlab.com/
[url "ssh://git@bitbucket.org/"]
insteadOf = https://bitbucket.org/
```
Every HTTPS URL for those hosts is now rewritten before the request leaves your
machine, including the URLs you did not write yourself. Submodules are the case
that pays for the whole thing: a `.gitmodules` committed by someone else,
pointing at HTTPS, in a repository you have no say over. The same goes for any
dependency that names a Git repository by HTTPS URL — a pod with a `:git =>`
line, a `go get` under `GOPRIVATE`, an npm dependency spelled `git+https://`.
Two things it leaves alone, both correctly. Package managers that fetch an
archive rather than clone never hand Git a URL at all: CocoaPods moved to a CDN
in 1.8, the Go proxy serves public modules, and npm's `github:user/repo`
shorthand resolves to a codeload tarball. And this is `~/.gitconfig` on your
machine, so a CI runner with its own home directory will never see it. That is
the outcome you want. A build server should authenticate with a scoped token
over HTTPS, not with your personal key.
## Check the rewrite
Substitution happens inside Git, before the network, so you can watch it
without connecting to anything:
```bash
git ls-remote --get-url https://github.com/omaralbeik/SwifterSwift.git
```
If that prints `ssh://git@github.com/omaralbeik/SwifterSwift.git`, the rewrite
is live. Reach for this rather than cloning a public repository as a test:
public clones over HTTPS succeed without credentials either way, so a clean
clone proves nothing about whether the substitution fired.
That is the whole arrangement — Git rewrites the URL, SSH picks the key that
belongs to the host. Nothing expires, and nothing to paste.
If you try this with several Git accounts or a private dependency, I'd like to
[hear how it works in your setup](/en/contact). Share the guide with a
teammate who keeps having to fix repository URLs by hand.
---
# استخدام SSH تلقائيًا بدل HTTPS في Git
- URL: https://omaralbeik.com/ar/blog/enforce-ssh-instead-of-https-for-git-operations
- Markdown: https://omaralbeik.com/ar/blog/enforce-ssh-instead-of-https-for-git-operations.md
- Translation: https://omaralbeik.com/en/blog/enforce-ssh-instead-of-https-for-git-operations
- Author: Omar Albeik
- Language: ar
- Type: tutorial
- Date: 23 آب 2021
- Topics: tooling, software, engineering
قبل عشرة أيام من كتابة هذه المقالة، أوقفت GitHub قبول كلمات مرور الحسابات في
عمليات Git عبر HTTPS. أصبح أحد البدائل استخدام رمز وصول شخصي (personal access
token) بدل كلمة المرور.
يمكن لأداة حفظ بيانات الاعتماد (`credential helper`)، مثل `osxkeychain` أو Git
Credential Manager، أن تتولى حفظ الرمز. ويمكن إعداد المصادقة أيضًا عبر `gh
auth login`. هذا خيار مناسب إذا كنت تفضل HTTPS. أما الرموز ذات الصلاحية
المحددة فتحتاج إلى تجديد عند انتهائها، مع التأكد من الصلاحيات المطلوبة.
أستخدم SSH لتجنب تكرار هذا الإعداد. أنشئ زوجًا من المفاتيح، وأحتفظ بالمفتاح
الخاص على جهازي، ثم أضيف المفتاح العام إلى الحساب. وباستخدام قاعدة في Git،
أستطيع تحويل روابط HTTPS إلى SSH حتى عندما تأتي من ملفات تبعيات كتبها غيري.
سننشئ المفتاح ونسجله، ثم نحدد لـ SSH أي مفتاح يستخدم، ونضبط Git ليعيد كتابة
الروابط تلقائيًا.
## توليد المفتاح
```bash
ssh-keygen -t ed25519 -C "personal github" -f ~/.ssh/personal-github
```
يستخدم الأمر Ed25519، بمفاتيح قصيرة ودون الحاجة إلى اختيار حجم المفتاح. إذا
كان الخادم أقدم من OpenSSH 6.5، فاستخدم `-t rsa -b 4096` بدلًا منه.
اختر اسمًا يوضح الغرض من المفتاح، مثل `personal-github` أو `work-gitlab`. أنشئ
مفتاحًا لكل حساب؛ لا تقبل GitHub إضافة المفتاح العام نفسه إلى حساب آخر. وأنشئ
مفتاحًا مستقلًا لكل جهاز، حتى تستطيع إلغاء وصول جهاز واحد دون تغيير إعدادات
الأجهزة الأخرى. اسم مثل `id_ed25519_2` لن يساعدك كثيرًا عند مراجعة المفاتيح
لاحقًا.
احمِ المفتاح بعبارة مرور، واستخدم `ssh-agent` حتى لا تضطر إلى إدخالها مع كل
عملية دفع.
## إضافة المفتاح العام إلى الخادم
انسخ محتوى المفتاح العام، أي الملف الذي ينتهي بـ `.pub`. احتفظ بالمفتاح الخاص،
الذي لا يحمل هذا الامتداد، على جهازك:
```bash
# macOS
pbcopy < ~/.ssh/personal-github.pub
# Linux
xclip -selection clipboard < ~/.ssh/personal-github.pub
```
ثم ألصقه في إعدادات حسابك:
[GitHub](https://docs.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account)
أو [GitLab](https://docs.gitlab.com/ee/ssh/)
أو [Bitbucket](https://support.atlassian.com/bitbucket-cloud/docs/set-up-an-ssh-key/).
## تحديد المفتاح الذي يستخدمه SSH
يبحث SSH عن أسماء المفاتيح الافتراضية، مثل `id_ed25519` و`id_rsa`. إذا اخترت
اسمًا مختلفًا، فأضف مساره إلى `~/.ssh/config`:
```ssh-config
Host github.com
User git
IdentityFile ~/.ssh/personal-github
IdentitiesOnly yes
AddKeysToAgent yes
Host gitlab.com
User git
IdentityFile ~/.ssh/work-gitlab
IdentitiesOnly yes
AddKeysToAgent yes
```
يحدد `IdentitiesOnly yes` المفاتيح التي يسمح SSH باستخدامها لهذا الاتصال.
بدونه قد يعرض مفاتيح أخرى من `ssh-agent`، فتتعرف GitHub عليك بحساب مختلف. قد
تظهر عندها رسالة «المستودع غير موجود» رغم أن حسابك المقصود يملك صلاحية الوصول
إليه.
على macOS، يمكنك إضافة `UseKeychain yes` إلى كتلة الخادم لحفظ عبارة المرور في
Keychain. هذا خيار خاص بنسخة Apple من OpenSSH؛ قد ترفضه نسخة Homebrew إذا كانت
هي المستخدمة أولًا في `PATH`. في إعداد macOS المستخدم وقت كتابة المقالة، يُضاف
المفتاح بالأمر `ssh-add -K ~/.ssh/personal-github`.
اختبر الاتصال مرة واحدة:
```bash
ssh -T git@github.com
```
في أول اتصال، يعرض SSH بصمة مفتاح الخادم. قارنها بالبصمة التي تنشرها GitHub
قبل قبولها بـ `yes`. بعد نجاح المصادقة، ستظهر تحية تتضمن اسم حسابك؛ تحقق من
أنه الحساب المقصود.
إذا توقف الاتصال دون استجابة، فقد تكون الشبكة تحجب المنفذ 22. تتيح GitHub
اتصال SSH عبر المنفذ 443 أيضًا:
```ssh-config
Host github.com
Hostname ssh.github.com
Port 443
# ...بقيّة الكتلة كما سبق
```
تأكد من نجاح اتصال SSH قبل تفعيل إعادة كتابة الروابط في الخطوة التالية.
## إعادة كتابة روابط HTTPS إلى SSH
ما دامت روابط المستودعات تبدأ بـ `https://`، سيستخدم Git اتصال HTTPS. بدل
تعديل كل مستودع، أضف القواعد التالية إلى `~/.gitconfig`:
```ini
[url "ssh://git@github.com/"]
insteadOf = https://github.com/
[url "ssh://git@gitlab.com/"]
insteadOf = https://gitlab.com/
[url "ssh://git@bitbucket.org/"]
insteadOf = https://bitbucket.org/
```
يعيد Git كتابة روابط HTTPS المطابقة لهذه القواعد قبل الاتصال. يفيد ذلك خصوصًا
مع `submodules` عندما يحتوي `.gitmodules` على روابط HTTPS لا تتحكم فيها.
وينطبق أيضًا على الأدوات التي تمرر إلى Git روابط مستودعات، مثل تبعية CocoaPods
محددة بـ `:git =>` أو `go get` تحت `GOPRIVATE` أو تبعية npm بصيغة
`git+https://`.
لن تؤثر القواعد على مدير حزم ينزّل أرشيفًا مباشرة دون استخدام Git. من أمثلة
ذلك CDN في CocoaPods منذ الإصدار 1.8، وGo proxy للوحدات العامة، وأرشيفات
codeload المستخدمة مع اختصار npm بصيغة `github:user/repo`.
كذلك، تخص هذه الإعدادات مستخدمك على هذا الجهاز. لبيئة CI إعدادات وبيانات
اعتماد مستقلة؛ لا تنقل إليها مفتاحك الشخصي. استخدم وسيلة مصادقة مخصصة لها
بصلاحيات محدودة.
## التحقق من إعادة الكتابة
يمكنك التحقق من إعادة الكتابة دون أي اتصال بالشبكة:
```bash
git ls-remote --get-url https://github.com/omaralbeik/SwifterSwift.git
```
إذا ظهر `ssh://git@github.com/omaralbeik/SwifterSwift.git`، فالقاعدة تعمل. هذا
الاختبار أدق من استنساخ مستودع عام، لأن الاستنساخ عبر HTTPS ينجح أيضًا دون
بيانات اعتماد.
بعد ذلك، يتولى Git تحويل الرابط، ويختار SSH المفتاح المحدد للخادم. إذا حدثت
مشكلة، يمكنك فحص كل خطوة على حدة.
إذا جرّبت هذا الإعداد مع عدة حسابات Git أو تبعية خاصة، [أخبرني كيف عمل
لديك](/ar/contact). وشارك الدليل مع زميل يضطر إلى تعديل روابط المستودعات
يدويًا كل مرة.
---