@fluxwp/core 0.0.0-stage → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +4 -2
  2. package/package.json +39 -4
  3. package/src/accounts/session.ts +86 -0
  4. package/src/accounts/store.ts +67 -0
  5. package/src/accounts/tokens.ts +24 -0
  6. package/src/accounts/types.ts +77 -0
  7. package/src/api/client.ts +247 -0
  8. package/src/api/flxapp.ts +11 -0
  9. package/src/api/types.ts +105 -0
  10. package/src/auth/apppass.ts +52 -0
  11. package/src/auth/discovery.ts +84 -0
  12. package/src/auth/login.ts +73 -0
  13. package/src/auth/oauth.ts +89 -0
  14. package/src/auth/otp.ts +20 -0
  15. package/src/auth/pkce.ts +23 -0
  16. package/src/brand/current.json +56 -0
  17. package/src/brand/index.ts +44 -0
  18. package/src/demo/fetch.ts +138 -0
  19. package/src/demo/fixtures.ts +106 -0
  20. package/src/demo/flxc.ts +282 -0
  21. package/src/demo/flxg.ts +324 -0
  22. package/src/demo/locale.ts +63 -0
  23. package/src/demo/modules.ts +90 -0
  24. package/src/demo/origin.ts +1 -0
  25. package/src/i18n/index.ts +38 -0
  26. package/src/i18n/locales/ar.json +326 -0
  27. package/src/i18n/locales/de.json +326 -0
  28. package/src/i18n/locales/en.json +326 -0
  29. package/src/i18n/locales/es.json +326 -0
  30. package/src/i18n/locales/fr.json +326 -0
  31. package/src/i18n/locales/ja.json +326 -0
  32. package/src/i18n/locales/pt-br.json +326 -0
  33. package/src/i18n/locales/ru.json +326 -0
  34. package/src/i18n/locales/tr.json +326 -0
  35. package/src/i18n/locales/zh.json +326 -0
  36. package/src/index.ts +28 -0
  37. package/src/layout/merge.ts +123 -0
  38. package/src/layout/store.ts +36 -0
  39. package/src/modules/bagis.ts +27 -0
  40. package/src/modules/cagri.ts +47 -0
  41. package/src/modules/common.ts +6 -0
  42. package/src/modules/flxc.ts +260 -0
  43. package/src/modules/flxg.ts +191 -0
  44. package/src/modules/gorev.ts +44 -0
  45. package/src/platform.ts +116 -0
  46. package/src/text.ts +74 -0
  47. package/types/accounts/session.d.ts +12 -0
  48. package/types/accounts/store.d.ts +13 -0
  49. package/types/accounts/tokens.d.ts +6 -0
  50. package/types/accounts/types.d.ts +38 -0
  51. package/types/api/client.d.ts +79 -0
  52. package/types/api/flxapp.d.ts +15 -0
  53. package/types/api/types.d.ts +118 -0
  54. package/types/auth/apppass.d.ts +18 -0
  55. package/types/auth/discovery.d.ts +20 -0
  56. package/types/auth/login.d.ts +11 -0
  57. package/types/auth/oauth.d.ts +23 -0
  58. package/types/auth/otp.d.ts +10 -0
  59. package/types/auth/pkce.d.ts +7 -0
  60. package/types/brand/index.d.ts +38 -0
  61. package/types/demo/fetch.d.ts +2 -0
  62. package/types/demo/fixtures.d.ts +3 -0
  63. package/types/demo/flxc.d.ts +54 -0
  64. package/types/demo/flxg.d.ts +3 -0
  65. package/types/demo/locale.d.ts +4 -0
  66. package/types/demo/modules.d.ts +9 -0
  67. package/types/demo/origin.d.ts +1 -0
  68. package/types/i18n/index.d.ts +3288 -0
  69. package/types/index.d.ts +28 -0
  70. package/types/layout/merge.d.ts +55 -0
  71. package/types/layout/store.d.ts +8 -0
  72. package/types/modules/bagis.d.ts +47 -0
  73. package/types/modules/cagri.d.ts +72 -0
  74. package/types/modules/common.d.ts +6 -0
  75. package/types/modules/flxc.d.ts +324 -0
  76. package/types/modules/flxg.d.ts +511 -0
  77. package/types/modules/gorev.d.ts +92 -0
  78. package/types/platform.d.ts +85 -0
  79. package/types/text.d.ts +20 -0
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @fluxwp/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ @fluxwp/core (FluxWP)
4
+
5
+ Part of [FluxWP](https://fluxwp.com). Plugin screens: [@fluxwp/plugin-kit](https://www.npmjs.com/package/@fluxwp/plugin-kit).
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@fluxwp/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.5",
4
+ "description": "@fluxwp/core (FluxWP)",
5
+ "type": "module",
6
+ "license": "GPL-2.0-or-later",
7
+ "homepage": "https://fluxwp.com",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/FluxWP/FluxWP.git",
11
+ "directory": "packages/core"
12
+ },
13
+ "bugs": {
14
+ "email": "info@fluxwp.com"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./types/index.d.ts",
19
+ "default": "./src/index.ts"
20
+ }
21
+ },
22
+ "types": "./types/index.d.ts",
23
+ "files": [
24
+ "src",
25
+ "types",
26
+ "dist",
27
+ "schema",
28
+ "runtime-exports.json",
29
+ "README.md"
30
+ ],
31
+ "sideEffects": false,
32
+ "dependencies": {
33
+ "@fluxwp/tokens": "^0.4.0",
34
+ "i18next": "^26.6.0",
35
+ "zustand": "^5.0.16"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "provenance": true
40
+ }
41
+ }
@@ -0,0 +1,86 @@
1
+ // Hesap başına API istemcisi: süresi dolmak üzere olan belirteci yeniler, 401'de bir kez dener.
2
+ import { createClient, type ApiClient, type Credentials } from '../api/client';
3
+ import { refreshTokens } from '../auth/oauth';
4
+ import { demoFetch } from '../demo/fetch';
5
+ import type { Account } from './types';
6
+ import { fromTokenResponse, loadTokens, saveTokens } from './tokens';
7
+ import { accountsStore } from './store';
8
+
9
+ const SKEW = 60_000;
10
+ const clients = new Map<string, ApiClient>();
11
+ const inflight = new Map<string, Promise<Credentials | null>>();
12
+
13
+ async function markNeedsLogin(id: string): Promise<void> {
14
+ const cur = accountsStore.getState().accounts.find((x) => x.id === id);
15
+ if (cur && !cur.needsLogin) await accountsStore.getState().update(id, { needsLogin: true });
16
+ }
17
+
18
+ async function refresh(a: Account): Promise<Credentials | null> {
19
+ const running = inflight.get(a.id);
20
+ if (running) return running;
21
+ const p = (async () => {
22
+ const t = await loadTokens(a.id);
23
+ if (!t?.refresh || (a.authKind !== 'oauth' && a.authKind !== 'otp')) {
24
+ await markNeedsLogin(a.id);
25
+ return null;
26
+ }
27
+ try {
28
+ const next = fromTokenResponse(await refreshTokens(a.siteUrl, t.refresh));
29
+ await saveTokens(a.id, next);
30
+ return { token: next.access };
31
+ } catch {
32
+ await markNeedsLogin(a.id);
33
+ return null;
34
+ }
35
+ })().finally(() => inflight.delete(a.id));
36
+ inflight.set(a.id, p);
37
+ return p;
38
+ }
39
+
40
+ /**
41
+ * Lets a transport (Flux App over GraphQL, `@fluxwp/graphql/flx-app`) wrap every account client. Without one
42
+ * the client is plain REST. Demo accounts are never wrapped.
43
+ */
44
+ export type ClientEnhancer = (api: ApiClient, account: Account | null) => ApiClient;
45
+ let enhancer: ClientEnhancer | null = null;
46
+
47
+ export function setClientEnhancer(next: ClientEnhancer | null): void {
48
+ enhancer = next;
49
+ clients.clear();
50
+ }
51
+
52
+ /** Applies the installed enhancer (anonymous discovery passes `null` for the account). */
53
+ export const enhanceClient = (api: ApiClient, account: Account | null): ApiClient => (enhancer && account?.authKind !== 'demo' ? enhancer(api, account) : api);
54
+
55
+ export function clientFor(a: Account): ApiClient {
56
+ const hit = clients.get(a.id);
57
+ if (hit) return hit;
58
+ const c = createClient({
59
+ siteUrl: a.siteUrl,
60
+ fetchImpl: a.authKind === 'demo' ? demoFetch : undefined,
61
+ getCredentials: async () => {
62
+ if (a.authKind === 'demo') return { token: 'demo' };
63
+ const t = await loadTokens(a.id);
64
+ if (!t) {
65
+ await markNeedsLogin(a.id);
66
+ return null;
67
+ }
68
+ if (t.expiresAt && t.expiresAt - SKEW < Date.now()) return refresh(a);
69
+ return { token: t.access, scheme: a.authKind === 'apppass' ? 'basic' : 'bearer' };
70
+ },
71
+ onUnauthorized: async () => {
72
+ if (a.authKind === 'demo') return null;
73
+ if (a.authKind === 'oauth' || a.authKind === 'otp') {
74
+ const next = await refresh(a);
75
+ if (next) return next;
76
+ }
77
+ await markNeedsLogin(a.id);
78
+ return null;
79
+ },
80
+ });
81
+ const wrapped = enhanceClient(c, a);
82
+ clients.set(a.id, wrapped);
83
+ return wrapped;
84
+ }
85
+
86
+ export const dropClient = (id: string) => clients.delete(id);
@@ -0,0 +1,67 @@
1
+ import { createStore } from 'zustand/vanilla';
2
+ import { platform } from '../platform';
3
+ import type { Account, StoredTokens } from './types';
4
+ import { clearTokens, saveTokens } from './tokens';
5
+
6
+ const STORAGE_KEY = 'accounts';
7
+
8
+ export interface AccountsState {
9
+ ready: boolean;
10
+ accounts: Account[];
11
+ activeId: string | null;
12
+ load(): Promise<void>;
13
+ add(a: Account, tokens: StoredTokens | null): Promise<void>;
14
+ remove(id: string): Promise<void>;
15
+ setActive(id: string | null): Promise<void>;
16
+ update(id: string, patch: Partial<Account>): Promise<void>;
17
+ }
18
+
19
+ export const accountsStore = createStore<AccountsState>((set, get) => {
20
+ const persist = () => {
21
+ const { accounts, activeId } = get();
22
+ return platform().storage.set(STORAGE_KEY, JSON.stringify({ accounts, activeId }));
23
+ };
24
+ return {
25
+ ready: false,
26
+ accounts: [],
27
+ activeId: null,
28
+ async load() {
29
+ const raw = await platform().storage.get(STORAGE_KEY);
30
+ let data: { accounts?: Account[]; activeId?: string | null } = {};
31
+ try {
32
+ data = raw ? JSON.parse(raw) : {};
33
+ } catch {
34
+ /* bozuk kayıt: temiz başla */
35
+ }
36
+ const accounts = Array.isArray(data.accounts) ? data.accounts : [];
37
+ const activeId = accounts.some((a) => a.id === data.activeId) ? (data.activeId ?? null) : (accounts[0]?.id ?? null);
38
+ set({ ready: true, accounts, activeId });
39
+ },
40
+ async add(a, tokens) {
41
+ if (tokens) await saveTokens(a.id, tokens);
42
+ const rest = get().accounts.filter((x) => x.id !== a.id);
43
+ set({ accounts: [...rest, { ...a, needsLogin: false }], activeId: a.id });
44
+ await persist();
45
+ },
46
+ async remove(id) {
47
+ await clearTokens(id);
48
+ const accounts = get().accounts.filter((x) => x.id !== id);
49
+ const activeId = get().activeId === id ? (accounts[0]?.id ?? null) : get().activeId;
50
+ set({ accounts, activeId });
51
+ await persist();
52
+ },
53
+ async setActive(id) {
54
+ set({ activeId: id });
55
+ await persist();
56
+ },
57
+ async update(id, patch) {
58
+ set({ accounts: get().accounts.map((x) => (x.id === id ? { ...x, ...patch } : x)) });
59
+ await persist();
60
+ },
61
+ };
62
+ });
63
+
64
+ export const activeAccount = (): Account | null => {
65
+ const s = accountsStore.getState();
66
+ return s.accounts.find((a) => a.id === s.activeId) ?? null;
67
+ };
@@ -0,0 +1,24 @@
1
+ import { platform } from '../platform';
2
+ import type { TokenResponse } from '../api/types';
3
+ import type { StoredTokens } from './types';
4
+
5
+ const key = (id: string) => `tokens:${id}`;
6
+
7
+ export async function loadTokens(id: string): Promise<StoredTokens | null> {
8
+ const raw = await platform().secure.get(key(id));
9
+ if (!raw) return null;
10
+ try {
11
+ return JSON.parse(raw) as StoredTokens;
12
+ } catch {
13
+ return null;
14
+ }
15
+ }
16
+
17
+ export const saveTokens = (id: string, t: StoredTokens) => platform().secure.set(key(id), JSON.stringify(t));
18
+ export const clearTokens = (id: string) => platform().secure.remove(key(id));
19
+
20
+ export const fromTokenResponse = (r: TokenResponse, now = Date.now()): StoredTokens => ({
21
+ access: r.access_token,
22
+ refresh: r.refresh_token,
23
+ expiresAt: r.expires_in ? now + r.expires_in * 1000 : undefined,
24
+ });
@@ -0,0 +1,77 @@
1
+ import { siteBasePath } from '../text';
2
+
3
+ export type AuthKind = 'oauth' | 'otp' | 'apikey' | 'apppass' | 'demo';
4
+
5
+ export interface Account {
6
+ /** `host#userId` or `host/path#userId` (subdirectory). Two installs on one host stay separate. */
7
+ id: string;
8
+ siteUrl: string;
9
+ siteName: string;
10
+ siteIcon: string;
11
+ userId: number;
12
+ userName: string;
13
+ userAvatar: string;
14
+ authKind: AuthKind;
15
+ addedAt: number;
16
+ /** Yenileme başarısız: kullanıcı yeniden giriş yapmalı. */
17
+ needsLogin?: boolean;
18
+ }
19
+
20
+ export interface StoredTokens {
21
+ access: string;
22
+ refresh?: string | undefined;
23
+ /** ms epoch; API anahtarında yok. */
24
+ expiresAt?: number | undefined;
25
+ }
26
+
27
+ export interface ParsedAccountId {
28
+ host: string;
29
+ /** `""` at the root, otherwise `/blog`. */
30
+ basePath: string;
31
+ userId: number;
32
+ }
33
+
34
+ /** `host#userId` at the root, `host/path#userId` for a subdirectory install. */
35
+ export function accountId(siteUrl: string, userId: number): string {
36
+ const host = new URL(siteUrl).host;
37
+ const path = siteBasePath(siteUrl);
38
+ return `${host}${path}#${userId}`;
39
+ }
40
+
41
+ /**
42
+ * Reads an account id. Old root ids (`host#userId`) still parse.
43
+ * Anything else returns null; callers must not throw on a stored id.
44
+ */
45
+ export function parseAccountId(id: string): ParsedAccountId | null {
46
+ const hash = id.indexOf('#');
47
+ if (hash <= 0 || hash !== id.lastIndexOf('#')) return null;
48
+ const userRaw = id.slice(hash + 1);
49
+ if (!/^[0-9]+$/.test(userRaw)) return null;
50
+ const left = id.slice(0, hash);
51
+ const slash = left.indexOf('/');
52
+ const host = slash < 0 ? left : left.slice(0, slash);
53
+ const basePath = slash < 0 ? '' : left.slice(slash);
54
+ if (!host || /[\s#]/.test(host) || basePath === '/' || basePath.endsWith('/') || basePath.includes('//')) return null;
55
+ return { host, basePath, userId: Number(userRaw) };
56
+ }
57
+
58
+ /** One path segment. Root stays `host@userId`; a subdirectory encodes the slash. */
59
+ export function accountRouteKey(id: string): string {
60
+ const parsed = parseAccountId(id);
61
+ if (!parsed) return encodeURIComponent(id);
62
+ if (!parsed.basePath) return `${parsed.host}@${parsed.userId}`;
63
+ return `${encodeURIComponent(parsed.host + parsed.basePath)}@${parsed.userId}`;
64
+ }
65
+
66
+ /** Inverse of `accountRouteKey`. A bad key is returned unchanged. */
67
+ export function accountIdFromRouteKey(key: string): string {
68
+ try {
69
+ const at = key.lastIndexOf('@');
70
+ if (at <= 0) return decodeURIComponent(key);
71
+ const user = key.slice(at + 1);
72
+ if (!/^[0-9]+$/.test(user)) return decodeURIComponent(key);
73
+ return `${decodeURIComponent(key.slice(0, at))}#${user}`;
74
+ } catch {
75
+ return key;
76
+ }
77
+ }
@@ -0,0 +1,247 @@
1
+ import { platform } from '../platform';
2
+ import { siteBasePath, trimEnd } from '../text';
3
+
4
+ export class ApiError extends Error {
5
+ constructor(
6
+ public status: number,
7
+ public code: string,
8
+ message: string,
9
+ public data?: unknown,
10
+ ) {
11
+ super(message);
12
+ this.name = 'ApiError';
13
+ }
14
+ }
15
+
16
+ export interface Credentials {
17
+ /** Erişim belirteci (flxat_), API anahtarı (flxak_) ya da Basic için base64(kullanıcı:uygulama şifresi). */
18
+ token: string;
19
+ /** "basic": WordPress Application Passwords (Flux App olmayan site). */
20
+ scheme?: 'bearer' | 'basic';
21
+ }
22
+
23
+ const platformHeaders = (): Record<string, string> => {
24
+ try {
25
+ return platform().headers?.() ?? {};
26
+ } catch {
27
+ return {};
28
+ }
29
+ };
30
+
31
+ export interface ClientOptions {
32
+ siteUrl: string;
33
+ /** Güncel kimlik; yoksa anonim istek. */
34
+ getCredentials: () => Promise<Credentials | null>;
35
+ /** 401'de bir kez çağrılır; yeni kimlik dönerse istek tekrarlanır. */
36
+ onUnauthorized?: (() => Promise<Credentials | null>) | undefined;
37
+ /** Sunucu Authorization başlığını düşürüyorsa X-FluxWP-Token kullanılır. */
38
+ useHeaderFallback?: boolean | undefined;
39
+ fetchImpl?: typeof fetch | undefined;
40
+ /** Her isteğe eklenecek başlıklar (WP admin: X-WP-Nonce). */
41
+ extraHeaders?: (() => Record<string, string>) | undefined;
42
+ /** WP admin içinde çerezle kimlik: 'same-origin'. */
43
+ credentials?: RequestCredentials | undefined;
44
+ }
45
+
46
+ export interface RequestOptions {
47
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | undefined;
48
+ query?: Record<string, string | number | boolean | undefined | null> | undefined;
49
+ body?: unknown | undefined;
50
+ form?: Record<string, string> | undefined;
51
+ /** Dosya yükleme (multipart). Content-Type tarayıcıya bırakılır. */
52
+ formData?: FormData | undefined;
53
+ /** İsteğe ek başlıklar (ör. `If-None-Match`). Kimlik başlığının üstüne yazamaz. */
54
+ headers?: Record<string, string> | undefined;
55
+ /** Multipart yüklemede 0..1. Platform `XMLHttpRequest` verirse ara değerler gelir. */
56
+ onUploadProgress?: ((ratio: number) => void) | undefined;
57
+ /** 'blob': medya gibi ham cevap. 'stream': başarılı cevabın `Response`'u (satır satır okunan akış, ör. NDJSON). */
58
+ as?: 'json' | 'blob' | 'stream' | undefined;
59
+ /**
60
+ * true: gövdeyle birlikte durum ve yanıt başlıkları (`ETag`, `X-WP-TotalPages`).
61
+ * 304 gövdesiz başarıdır (`data: null`), hata değildir.
62
+ */
63
+ raw?: boolean | undefined;
64
+ signal?: AbortSignal | undefined;
65
+ /** Kimlik eklemeden gönder (OAuth token ucu gibi). */
66
+ anonymous?: boolean | undefined;
67
+ /**
68
+ * false: 4xx/5xx JSON cevabı da `raw` sonuç olarak döner (GraphQL hata gövdesi gibi); yalnız ağ
69
+ * hatası ve bozuk JSON fırlatır. Varsayılan true.
70
+ */
71
+ throwOnError?: boolean | undefined;
72
+ }
73
+
74
+ /** Case-insensitive response headers (Fetch `Headers#get`). */
75
+ export interface ResponseHeaders {
76
+ get(name: string): string | null;
77
+ }
78
+
79
+ /** `raw: true` cevabı. `etag` başlıktan okunmuş hâli (yoksa null). */
80
+ export interface ApiResult<T> {
81
+ data: T | null;
82
+ status: number;
83
+ etag: string | null;
84
+ headers: ResponseHeaders;
85
+ }
86
+
87
+ export function restBase(siteUrl: string): string {
88
+ return trimEnd(siteUrl) + '/wp-json/';
89
+ }
90
+
91
+ const CONTROLS = /[\u0000-\u001F\u007F-\u009F]/;
92
+
93
+ function pathUnder(pathname: string, basePath: string): boolean {
94
+ if (!basePath || basePath === '/') return true;
95
+ const base = basePath.endsWith('/') ? basePath.slice(0, -1) : basePath;
96
+ return pathname === base || pathname.startsWith(base + '/');
97
+ }
98
+
99
+ /**
100
+ * Resolve `path` against the account site. The result must stay on that origin and,
101
+ * for a subdirectory install, under that install's path. Backslash and protocol-relative
102
+ * paths (`\\host`, `//host`) are not rewritten into a relative path: the URL parser
103
+ * sees them, and a different origin is rejected before any request.
104
+ */
105
+ export function buildUrl(siteUrl: string, path: string, query?: RequestOptions['query']): string {
106
+ if (typeof path !== 'string' || CONTROLS.test(path) || CONTROLS.test(siteUrl)) throw new ApiError(0, 'bad_url', 'control');
107
+ let site: URL;
108
+ try {
109
+ site = new URL(siteUrl);
110
+ } catch {
111
+ throw new ApiError(0, 'bad_url', 'site');
112
+ }
113
+ if (site.username || site.password || (site.protocol !== 'http:' && site.protocol !== 'https:')) {
114
+ throw new ApiError(0, 'bad_url', site.username || site.password ? 'credentials' : site.protocol);
115
+ }
116
+ const normalised = path.replace(/\\/g, '/');
117
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(normalised) || normalised.startsWith('//');
118
+ let resolved: URL;
119
+ try {
120
+ resolved = absolute ? new URL(normalised, site) : new URL(normalised.replace(/^\/+/, ''), restBase(siteUrl));
121
+ } catch {
122
+ throw new ApiError(0, 'bad_url', 'path');
123
+ }
124
+ if (resolved.username || resolved.password) throw new ApiError(0, 'bad_url', 'credentials');
125
+ if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') throw new ApiError(0, 'foreign_url', resolved.protocol);
126
+ const basePath = siteBasePath(siteUrl);
127
+ if (resolved.origin !== site.origin || !pathUnder(resolved.pathname, basePath || '/')) {
128
+ throw new ApiError(0, 'foreign_url', resolved.origin);
129
+ }
130
+ if (!absolute) resolved.searchParams.set('_locale', 'user');
131
+ for (const [k, v] of Object.entries(query ?? {})) {
132
+ if (v !== undefined && v !== null && v !== '') resolved.searchParams.set(k, String(v));
133
+ }
134
+ return resolved.toString();
135
+ }
136
+
137
+ export interface ApiClient {
138
+ <T>(path: string, opts: RequestOptions & { raw: true }): Promise<ApiResult<T>>;
139
+ <T>(path: string, opts?: RequestOptions): Promise<T>;
140
+ }
141
+
142
+ function responseHeaders(res: Response): ResponseHeaders {
143
+ const map = new Map<string, string>();
144
+ res.headers.forEach((value, key) => map.set(key.toLowerCase(), value));
145
+ return { get: (name) => map.get(name.toLowerCase()) ?? null };
146
+ }
147
+
148
+ /** Upload progress needs XHR; fetch has none. Falls back to fetch when XHR is missing (tests, some hosts). */
149
+ function xhrSend(url: string, method: string, headers: Record<string, string>, body: BodyInit | undefined, signal: AbortSignal | undefined, onProgress: (ratio: number) => void): Promise<Response> {
150
+ const XHR = globalThis.XMLHttpRequest;
151
+ if (!XHR) return Promise.reject(new ApiError(0, 'no_xhr', 'upload progress unavailable'));
152
+ return new Promise((resolve, reject) => {
153
+ const xhr = new XHR();
154
+ xhr.open(method, url);
155
+ xhr.withCredentials = false;
156
+ for (const [key, value] of Object.entries(headers)) xhr.setRequestHeader(key, value);
157
+ xhr.upload.onprogress = (e) => {
158
+ if (e.lengthComputable && e.total > 0) onProgress(e.loaded / e.total);
159
+ };
160
+ const done = () => {
161
+ const h = new Headers();
162
+ for (const line of xhr.getAllResponseHeaders().trim().split(/[\r\n]+/)) {
163
+ const i = line.indexOf(':');
164
+ if (i > 0) h.append(line.slice(0, i).trim(), line.slice(i + 1).trim());
165
+ }
166
+ resolve(new Response(xhr.responseText, { status: xhr.status, statusText: xhr.statusText, headers: h }));
167
+ };
168
+ xhr.onload = done;
169
+ xhr.onerror = () => reject(new ApiError(0, 'network', 'network'));
170
+ xhr.onabort = () => reject(new ApiError(0, 'aborted', 'aborted'));
171
+ if (signal) {
172
+ if (signal.aborted) xhr.abort();
173
+ else signal.addEventListener('abort', () => xhr.abort(), { once: true });
174
+ }
175
+ xhr.send((body ?? null) as XMLHttpRequestBodyInit | null);
176
+ });
177
+ }
178
+
179
+ export function createClient(o: ClientOptions): ApiClient {
180
+ const doFetch = (...a: Parameters<typeof fetch>) => (o.fetchImpl ?? platform().fetch)(...a);
181
+
182
+ const send = async (url: string, opts: RequestOptions, cred: Credentials | null) => {
183
+ const headers: Record<string, string> = { Accept: 'application/json', ...platformHeaders(), ...o.extraHeaders?.(), ...opts.headers };
184
+ let body: BodyInit | undefined;
185
+ if (opts.formData) {
186
+ body = opts.formData;
187
+ } else if (opts.form) {
188
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
189
+ body = new URLSearchParams(opts.form).toString();
190
+ } else if (opts.body !== undefined) {
191
+ headers['Content-Type'] = 'application/json';
192
+ body = JSON.stringify(opts.body);
193
+ }
194
+ if (cred && !opts.anonymous) {
195
+ if (cred.scheme === 'basic') headers.Authorization = `Basic ${cred.token}`;
196
+ else if (o.useHeaderFallback) headers['X-FluxWP-Token'] = cred.token;
197
+ else headers.Authorization = `Bearer ${cred.token}`;
198
+ }
199
+ const method = opts.method ?? (body ? 'POST' : 'GET');
200
+ if (opts.onUploadProgress && typeof XMLHttpRequest !== 'undefined') return xhrSend(url, method, headers, body, opts.signal, opts.onUploadProgress);
201
+ // A token request never carries cookies. The app's web views sign in to wp-admin and share their
202
+ // cookies with native requests; with a login cookie present WordPress resolves the user from the
203
+ // cookie, ignores the token and FluxApp answers 401 "token is invalid or expired".
204
+ const credentials = o.credentials ?? (cred && !opts.anonymous ? 'omit' : undefined);
205
+ const init: RequestInit = { method, headers };
206
+ if (body !== undefined) init.body = body;
207
+ if (opts.signal) init.signal = opts.signal;
208
+ if (credentials) init.credentials = credentials;
209
+ return doFetch(url, init);
210
+ };
211
+
212
+ async function request<T>(path: string, opts: RequestOptions = {}): Promise<T | ApiResult<T>> {
213
+ const url = buildUrl(o.siteUrl, path, opts.query);
214
+ let cred = opts.anonymous ? null : await o.getCredentials();
215
+ let res = await send(url, opts, cred);
216
+ if (res.status === 401 && !opts.anonymous && o.onUnauthorized) {
217
+ cred = await o.onUnauthorized();
218
+ if (cred) res = await send(url, opts, cred);
219
+ }
220
+ const headers = responseHeaders(res);
221
+ const etag = headers.get('etag');
222
+ // 304 Not Modified: empty body, cache stays. Not an error.
223
+ if (res.status === 304) {
224
+ const result: ApiResult<T> = { data: null, status: 304, etag, headers };
225
+ return opts.raw ? result : (null as T);
226
+ }
227
+ if (opts.as === 'blob' && res.ok) return (await res.blob()) as T;
228
+ if (opts.as === 'stream' && res.ok) return res as T;
229
+ const text = await res.text();
230
+ let json: unknown = null;
231
+ if (text) {
232
+ try {
233
+ json = JSON.parse(text);
234
+ } catch {
235
+ throw new ApiError(res.status, 'invalid_json', text.slice(0, 200));
236
+ }
237
+ }
238
+ if (!res.ok && opts.throwOnError !== false) {
239
+ const j = (json ?? {}) as { code?: string; message?: string; error?: string; error_description?: string; data?: unknown };
240
+ throw new ApiError(res.status, j.code ?? j.error ?? 'http_' + res.status, j.message ?? j.error_description ?? res.statusText, j.data);
241
+ }
242
+ if (opts.raw) return { data: json as T, status: res.status, etag, headers };
243
+ return json as T;
244
+ }
245
+
246
+ return request as ApiClient;
247
+ }
@@ -0,0 +1,11 @@
1
+ import type { ApiClient } from './client';
2
+ import type { Dashboard, Me } from './types';
3
+
4
+ export const flxapp = (api: ApiClient) => ({
5
+ me: () => api<Me>('flxapp/v1/me'),
6
+ counts: () => api<Record<string, number>>('flxapp/v1/counts'),
7
+ dashboard: () => api<Dashboard>('flxapp/v1/dashboard'),
8
+ /** Yerel ekranı olmayan menü için tek seferlik panel girişi (60 sn). */
9
+ session: (path: string) => api<{ url: string; expires_in: number }>('flxapp/v1/session', { method: 'POST', body: { path } }),
10
+ logout: () => api<{ ok: boolean }>('flxapp/v1/logout', { method: 'POST' }),
11
+ });
@@ -0,0 +1,105 @@
1
+ // Flux App (flxapp/v1) cevap tipleri. Kaynak: docs/flx-app/API.md
2
+
3
+ export interface Role { id: string; name: string }
4
+
5
+ export interface MeUser {
6
+ id: number;
7
+ login: string;
8
+ name: string;
9
+ email: string;
10
+ avatar: string;
11
+ roles: Role[];
12
+ locale: string;
13
+ is_admin: boolean;
14
+ profile_url: string;
15
+ }
16
+
17
+ export interface MeSite {
18
+ name: string;
19
+ url: string;
20
+ admin_url: string;
21
+ rest_url: string;
22
+ icon: string;
23
+ locale: string;
24
+ timezone: string;
25
+ }
26
+
27
+ export interface MenuSubItem { slug: string; title: string; url: string; badge?: number | string }
28
+
29
+ export interface MenuItem {
30
+ id: string;
31
+ slug: string;
32
+ title: string;
33
+ url: string;
34
+ icon: string;
35
+ /** Paketin renkli logosu (Flux App gönderirse). */
36
+ icon_url?: string;
37
+ badge?: number | string;
38
+ items: MenuSubItem[];
39
+ }
40
+
41
+ /** WP'deki Flux Admin menü düzeni (kişinin sabitledikleri + gruplar). Flux Admin yoksa gelmez. */
42
+ export interface MenuLayout {
43
+ pins: string[];
44
+ groups: { id: string; label: string; collapsed?: boolean; items: string[] }[];
45
+ }
46
+
47
+ export interface ModuleInfo {
48
+ title: string;
49
+ cap?: string;
50
+ menu?: string;
51
+ api?: string;
52
+ icon?: string;
53
+ version?: string;
54
+ order?: number;
55
+ /** Modülün manifesti var (flxapp/v1/manifest). */
56
+ manifest?: boolean;
57
+ }
58
+
59
+ export interface Me {
60
+ user: MeUser;
61
+ site: MeSite;
62
+ auth: { kind: string; client?: string; scope?: string; expires?: number };
63
+ menu: MenuItem[];
64
+ modules: Record<string, ModuleInfo>;
65
+ counts: Record<string, number>;
66
+ bottom: string[];
67
+ layout?: MenuLayout;
68
+ web_session: boolean;
69
+ versions: Record<string, string>;
70
+ /** Çekirdek yetki özeti (edit_posts, upload_files, moderate_comments…). */
71
+ caps?: Record<string, boolean>;
72
+ /** me/config/manifest özetleri: değişince yeniden çekilir. */
73
+ hashes?: Record<string, string>;
74
+ }
75
+
76
+ export interface DashboardCard {
77
+ id: string;
78
+ title: string;
79
+ value: string;
80
+ sub?: string;
81
+ icon?: string;
82
+ tone?: '' | 'accent' | 'warn' | 'danger' | 'ok';
83
+ url?: string;
84
+ open?: string;
85
+ order?: number;
86
+ }
87
+
88
+ export interface DashboardList {
89
+ id: string;
90
+ title: string;
91
+ icon?: string;
92
+ url?: string;
93
+ order?: number;
94
+ items: { title: string; sub?: string; meta?: string; url?: string }[];
95
+ }
96
+
97
+ export interface Dashboard { cards: DashboardCard[]; lists: DashboardList[] }
98
+
99
+ export interface TokenResponse {
100
+ access_token: string;
101
+ token_type: string;
102
+ expires_in: number;
103
+ refresh_token?: string;
104
+ scope?: string;
105
+ }