@tekrom/tsoft-app-gate 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,13 +6,30 @@ T-Soft paneli içinde (iframe) açılan uygulamalar için **App Bridge** istemci
6
6
  npm install @tekrom/tsoft-app-gate
7
7
  ```
8
8
 
9
+ Paketleyici kullanmıyorsanız tarayıcı derlemesini `<script>` ile yükleyin; aynı API `TSoftAppGate` global'i altında gelir:
10
+
11
+ ```html
12
+ <script src="https://cdn.jsdelivr.net/npm/@tekrom/tsoft-app-gate@0.4/dist/tsoft-app-gate.min.js"></script>
13
+ <script>
14
+ const app = TSoftAppGate.createApp();
15
+ </script>
16
+ ```
17
+
18
+ Sürümü sabitleyin (`@0.4` ya da tam sürüm); üretimde dosyayı kendi sunucunuzdan sunmak da mümkündür.
19
+
9
20
  ## Hızlı başlangıç
10
21
 
11
22
  ```ts
12
- import { createApp, AppBridgeError } from '@tekrom/tsoft-app-gate';
23
+ import { createApp, isEmbedded, AppBridgeError } from '@tekrom/tsoft-app-gate';
24
+
25
+ if (!isEmbedded()) {
26
+ // Panel dışında açıldı: kendi giriş akışınızı gösterin.
27
+ }
13
28
 
14
29
  const app = createApp();
15
30
 
31
+ app.claims?.store_id; // hangi mağaza (doğrulamayı sunucuda yapın)
32
+
16
33
  // Arka uca giden her istekte taze token kullanın.
17
34
  const token = await app.getSessionToken();
18
35
  await fetch('/api/settings', { headers: { Authorization: `Bearer ${token}` } });
@@ -33,6 +50,11 @@ try {
33
50
 
34
51
  await app.navigate.panel('order', 1042);
35
52
 
53
+ await app.nav.set([
54
+ { label: 'Gönderiler', path: '/shipments' },
55
+ { label: 'Ayarlar', path: '/settings' },
56
+ ]);
57
+
36
58
  const stop = app.autoResize();
37
59
  ```
38
60
 
@@ -42,27 +64,32 @@ const stop = app.autoResize();
42
64
 
43
65
  | Seçenek | Varsayılan | Açıklama |
44
66
  |---|---|---|
45
- | `panelOrigin` | otomatik | Panelin origin'i. Verilmezse `location.ancestorOrigins`, yoksa `document.referrer` kullanılır (panel iframe'i `referrerpolicy="strict-origin"` ile açar). |
67
+ | `panelOrigin` | otomatik | Panelin origin'i. Verilmezse `location.ancestorOrigins`, yoksa `document.referrer` kullanılır (panel iframe'i `referrerpolicy="strict-origin"` ile açar) ve T-Soft panel alan adlarından biri olmalıdır. Elle verilen değer denetlenmez; yalnız yerel geliştirmede kullanın. |
46
68
  | `timeout` | `10000` | Kullanıcı etkileşimi beklemeyen isteklerin zaman aşımı (ms). |
47
69
 
48
- Uygulama bir iframe içinde değilse ya da panel origin'i bulunamazsa `AppBridgeError('not_embedded')` fırlatır. Bu durumda uygulamanızı panel dışında (ör. doğrudan URL ile) açılmış sayıp ona göre davranın.
70
+ Panel alan adları `PANEL_ORIGIN_PATTERN` ile denetlenir: `tsoftpanel.com`, `tsoftpanel.net`, `paneltsoft.com` ve bunların alt alan adları, yalnız `https`. Böylece uygulamanızı başka bir siteye gömen biri panel gibi yanıt veremez.
71
+
72
+ Uygulama bir iframe içinde değilse ya da üst pencere bir T-Soft paneli değilse `AppBridgeError('not_embedded')` fırlatır. Önceden bakmak için `isEmbedded()` kullanın.
49
73
 
50
74
  Dönen nesnede ayrıca şunlar vardır:
51
75
 
52
76
  - `panelOrigin`: Mesajların gönderildiği ve yanıtların kabul edildiği origin.
77
+ - `claims`: Elimizdeki son oturum token'ının içeriği (`store_id`, `dest`, `sub`, `aud`, `exp`…); token yoksa `null`. Token yenilendikçe güncellenir.
53
78
  - `installCode`: Panelin kurulumdan hemen sonra eklediği `?code=` değeri; yoksa `null`.
54
79
 
55
80
  ### Oturum token'ı
56
81
 
57
82
  ```ts
58
83
  app.getSessionToken(options?): Promise<string>
59
- app.getSession(options?): Promise<{ token, expiresAt, scopes }>
84
+ app.getSession(options?): Promise<{ token, claims, expiresAt, scopes }>
85
+ decodeSessionToken(token): SessionClaims | null
60
86
  ```
61
87
 
62
88
  - Panel uygulamayı `?session=<jwt>` ile açar. Bu token süresi dolmamışsa ilk çağrıda panele gidilmeden kullanılır; bu durumda `scopes` `null` olur.
63
- - Token'ın bitmesine 30 saniyeden az kaldıysa panelden yenisi istenir. Aynı anda gelen yenileme çağrıları tek isteğe bağlanır.
89
+ - Token 60 saniye yaşar. Bitmesine 15 saniyeden az kaldıysa panelden yenisi istenir; aynı anda gelen yenileme çağrıları tek isteğe bağlanır. Her sunucu isteğinden önce `getSessionToken()` çağırmanız yeterlidir.
64
90
  - `forceRefresh: true` önbelleği atlar; `scopes` her zaman panelden gelen güncel listeyi içerir.
65
- - Token ES256 imzalı bir JWT'dir (`aud` = uygulama prefix'i, `store_id`, `dest` = mağaza alan adı, `sub` = panel kullanıcısı). İstemci yalnız `exp` alanını önbellek süresi için okur; **imzayı arka ucunuzda JWKS ile doğrulayın.**
91
+ - Token ES256 imzalı bir JWT'dir (`iss`, `aud` = uygulama prefix'i, `sub` = panel kullanıcısı, `store_id`, `dest` = mağaza alan adı, `iat`, `nbf`, `exp`, `jti`). İstemci içeriği imza doğrulamadan okur; **imzayı sunucunuzda JWKS ile doğrulayın** (`https://api.tsoftapps.com/api/integration/v3/apps/jwks.json`, ayrıntı: [Panele Gömülü Uygulamalar](https://developer.tsoft.com.tr/uygulama-gelistirme/embedded-uygulamalar)).
92
+ - Oturum token'ı Admin API için değildir; uygulamanın kendi sunucusuyla konuşması içindir.
66
93
 
67
94
  ### `toast(message, { variant? })`
68
95
 
@@ -96,6 +123,23 @@ Panelde başka bir sayfaya geçer (uygulama kapanır).
96
123
 
97
124
  Kimlik `^[A-Za-z0-9_-]{1,64}$` kalıbına uymalı; bilinmeyen kaynak ya da geçersiz kimlik `invalid_route` döner.
98
125
 
126
+ ### `nav.set(items)`
127
+
128
+ Panelin sol menüsünde (ve mobil menüde) uygulamanın adının altında alt menü gösterir; Shopify App Bridge'deki `ui-nav-menu` karşılığıdır. `items`: `{ label, path }` listesi.
129
+
130
+ - En fazla 8 öğe; `label` boş olamaz, en fazla 40 karakter.
131
+ - `path` uygulamanın kendi adresi altında, `/` ile başlayan yol olmalı (`/orders?status=1` gibi). Mutlak ya da başka origin'e giden adres, `//` ile başlayan yol ve `javascript:` reddedilir. `app_url` bir alt dizindeyse (`https://x.com/app/`) yol o dizinin altında kalmalı.
132
+ - Tek bir geçersiz öğe bütün listeyi `invalid_payload` ile reddeder; menü değişmez.
133
+ - Boş liste (`[]`) menüyü kaldırır.
134
+
135
+ Bağlantıya tıklanınca panel `?path=` değerini değiştirir ve iframe'i o yolla, yeni oturum token'ıyla yeniden yükler. Etkin bağlantı iframe'in o anki yoluna göre işaretlenir: önce bire bir eşleşme, sonra en uzun yol öneki (`/orders` bağlantısı `/orders/42` yolunda da etkin; `/` yalnız kendisiyle eşleşir). Uygulama kendi içinde gezindikçe `navigate.app` çağırırsa vurgu da güncel kalır.
136
+
137
+ Panel son gönderilen listeyi uygulama başına tarayıcıda saklar; menü bir sonraki açılışta uygulama yüklenmeden görünür. Alt menü uygulama panelde açıkken ya da menüye sabitlenmişken görünür. Listeyi her açılışta göndermeniz yeterlidir:
138
+
139
+ ```ts
140
+ await app.nav.set([{ label: 'Gönderiler', path: '/shipments' }, { label: 'Ayarlar', path: '/settings' }]);
141
+ ```
142
+
99
143
  ### `pickResource({ type, multiple? })`
100
144
 
101
145
  Panelin seçicisini açar, seçilen kayıtların kimliklerini döner: `{ ids, cancelled }`. Kullanıcı pencereyi kapatırsa `{ ids: [], cancelled: true }`. Varsayılan olarak zaman aşımı yoktur.
@@ -126,7 +170,7 @@ Tüm reddedilen promise'ler `AppBridgeError` taşır; `code` alanı aşağıdaki
126
170
 
127
171
  | Kod | Kaynak | Anlamı |
128
172
  |---|---|---|
129
- | `invalid_payload` | panel | Zorunlu alan boş ya da tipi yanlış. |
173
+ | `invalid_payload` | panel | Zorunlu alan boş ya da tipi yanlış; `nav.set` listesinde geçersiz öğe. |
130
174
  | `invalid_path` | panel | `navigate.app` yolu geçersiz ya da uygulama origin'i dışında. |
131
175
  | `invalid_route` | panel | `navigate.panel` kaynağı bilinmiyor ya da kimlik geçersiz. |
132
176
  | `missing_scope` | panel | Uygulamanın bu iş için gereken kapsamı yok. |
@@ -134,7 +178,7 @@ Tüm reddedilen promise'ler `AppBridgeError` taşır; `code` alanı aşağıdaki
134
178
  | `unsupported_type` | panel | Panel bu mesaj tipini tanımıyor (eski panel sürümü). |
135
179
  | `internal_error` | panel | Panel isteği işlerken hata aldı (ör. token alınamadı). |
136
180
  | `timeout` | istemci | Süre içinde yanıt gelmedi. |
137
- | `not_embedded` | istemci | Uygulama panel iframe'i içinde değil. |
181
+ | `not_embedded` | istemci | Uygulama panel iframe'i içinde değil ya da üst pencere bir T-Soft paneli değil. |
138
182
  | `destroyed` | istemci | `destroy()` çağrıldıktan sonra istek yapıldı. |
139
183
 
140
184
  ## Protokol
@@ -147,7 +191,7 @@ Panel uygulamanın `app_url` adresini (yalnız `https`, panel origin'inden farkl
147
191
 
148
192
  - `session`: Oturum JWT'si.
149
193
  - `code`: Yalnız kurulumdan hemen sonraki ilk açılışta, kurulum kodu.
150
- - Panel URL'inde `?path=/x` varsa uygulama `app_url` origin'i altındaki `/x` yolundan açılır.
194
+ - Panel URL'inde `?path=/x` varsa uygulama `app_url` origin'i altındaki `/x` yolundan açılır. `?path=` panel tarafında değişirse (alt menü bağlantısı) iframe o yolla yeniden yüklenir; `navigate.app`'in yazdığı yol yeniden yükleme yapmaz.
151
195
 
152
196
  iframe `sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads"`, `allow="clipboard-write"` ve `referrerpolicy="strict-origin"` ile açılır. Üst pencereye yönlendirme (`allow-top-navigation`) yoktur; panelde gezinmek için `navigate.panel` kullanılır.
153
197
 
@@ -171,7 +215,7 @@ Kurallar:
171
215
  - Panel yalnız `event.origin` uygulama origin'ine eşit ve `event.source` kendi iframe'i olan mesajları işler.
172
216
  - `source`, `version` (1), `type` (string) ve `id` (string) zorunludur; uymayan mesaj sessizce yok sayılır, yanıt dönmez.
173
217
  - `id` panel tarafında 64 karaktere kesilir; yanıt bu kesilmiş kimlikle döner. 64 karakteri aşmayın.
174
- - Uygulama da yanıtları yalnız `event.source === window.parent` ve `event.origin === panelOrigin` ise kabul etmelidir.
218
+ - Uygulama da mesajı `targetOrigin` olarak panel origin'iyle göndermeli, yanıtları yalnız `event.source === window.parent` ve `event.origin` panel alan adlarından biriyse kabul etmelidir.
175
219
 
176
220
  ### Mesaj tipleri
177
221
 
@@ -184,6 +228,7 @@ Kurallar:
184
228
  | `navigate.panel` | `{ resource, id? }` | `{}` | `invalid_route` |
185
229
  | `resource.pick` | `{ type, multiple? }` | `{ ids, cancelled? }` | `unsupported_resource`, `missing_scope` |
186
230
  | `size.set` | `{ height }` | `{}` | `invalid_payload` |
231
+ | `nav.set` | `{ items: [{ label, path }] }` | `{}` | `invalid_payload` |
187
232
  | diğer | — | — | `unsupported_type` |
188
233
 
189
234
  `confirm.open` ve `resource.pick` yanıtı kullanıcı işlem yapınca gelir.
@@ -198,15 +243,28 @@ window.parent.postMessage({ type: 'tsoft:session-token:request' }, panelOrigin);
198
243
  // hata: { type: 'tsoft:session-token:error' }
199
244
  ```
200
245
 
201
- ## 0.1.x'ten geçiş
246
+ ## Geçiş
202
247
 
203
- 0.1.x'teki `createApp({ apiKey, shopId, host })`, `setNavigationMenu` ve `showToast` panelin hiç tanımadığı bir mesaj biçimi (`T_SOFT_APP_BRIDGE`) gönderiyordu; bu yüzden kaldırıldı. Karşılıkları:
248
+ ### `developer.tsoft.com.tr/app-bridge/v1` script'inden
204
249
 
205
- | 0.1.x | 0.2 |
250
+ | `TSoftBridge` | `TSoftAppGate` / npm |
206
251
  |---|---|
207
- | `createApp({ apiKey, shopId, host })` | `createApp()` |
208
- | `showToast(app, { message, variant })` | `app.toast(message, { variant })` |
209
- | `setNavigationMenu(app, items)` | Karşılığı yok; panel uygulama menüsünü desteklemiyor. |
252
+ | `TSoftBridge.create()` | `createApp()` |
253
+ | `bridge.claims` | `app.claims` |
254
+ | `bridge.sessionToken()` | `app.getSessionToken()` |
255
+ | `bridge.toast(message, 'error')` | `app.toast(message, { variant: 'error' })` |
256
+ | `bridge.confirm(opts)` | `app.confirm(opts)` |
257
+ | `bridge.pickProducts({ multiple })` | `app.pickResource({ type: 'product', multiple })` |
258
+ | `bridge.navigate(path)` | `app.navigate.app(path)` |
259
+ | `bridge.openPanel(resource, id)` | `app.navigate.panel(resource, id)` |
260
+ | `bridge.setHeight(h)` / `bridge.autoResize()` | `app.setHeight(h)` / `app.autoResize()` |
261
+ | `Error.message` | `AppBridgeError.code` |
262
+
263
+ Script panel dışında açılınca ilk istekte hata veriyordu; `createApp()` ise hemen `not_embedded` fırlatır.
264
+
265
+ ### 0.1.x'ten
266
+
267
+ 0.1.x'teki `createApp({ apiKey, shopId, host })`, `setNavigationMenu` ve `showToast` panelin tanımadığı bir mesaj biçimi (`T_SOFT_APP_BRIDGE`) gönderiyordu; kaldırıldı. `showToast(app, opts)` yerine `app.toast(message, opts)` kullanın; `setNavigationMenu` yerine 0.4.0'dan beri `app.nav.set(items)` var.
210
268
 
211
269
  ## Geliştirme
212
270
 
@@ -216,4 +274,4 @@ npm test # derler ve node --test ile testleri koşar (Node 23.6+)
216
274
  npm run build
217
275
  ```
218
276
 
219
- `dist/` yalnız npm paketine girer, repoya eklenmez. `prepublishOnly` yayın öncesi derlemeyi çalıştırır.
277
+ Derleme iki çıktı üretir: `tsc` ile ESM + tipler (`dist/index.js`) ve `esbuild` ile tarayıcı derlemesi (`dist/tsoft-app-gate.min.js`). `dist/` yalnız npm paketine girer, repoya eklenmez. `prepublishOnly` yayın öncesi derlemeyi çalıştırır.
package/dist/client.d.ts CHANGED
@@ -1,12 +1,13 @@
1
- import { type BridgeErrorCode, type PanelDetailResource, type PanelListResource, type PickableResource, type RequestPayloads, type RequestType, type ResponsePayloads, type ToastVariant } from './protocol.js';
1
+ import { type BridgeErrorCode, type NavItem, type PanelDetailResource, type PanelListResource, type PickableResource, type RequestPayloads, type RequestType, type ResponsePayloads, type ToastVariant } from './protocol.js';
2
2
  export declare class AppBridgeError extends Error {
3
3
  readonly code: BridgeErrorCode;
4
4
  constructor(code: BridgeErrorCode, message?: string);
5
5
  }
6
6
  export interface AppOptions {
7
7
  /**
8
- * Panelin origin'i (ör. `https://magaza.tsoft360.com`). Verilmezse
9
- * `location.ancestorOrigins` ya da `document.referrer` üzerinden bulunur.
8
+ * Panelin origin'i. Verilmezse `location.ancestorOrigins` ya da `document.referrer`
9
+ * üzerinden bulunur ve T-Soft panel alan adlarından biri olmalıdır. Elle verilen
10
+ * değer bu listeyle denetlenmez; yerel geliştirme içindir.
10
11
  */
11
12
  panelOrigin?: string;
12
13
  /** Kullanıcı etkileşimi beklemeyen isteklerin zaman aşımı (ms). Varsayılan 10000. */
@@ -16,8 +17,25 @@ export interface RequestOptions {
16
17
  /** Bu isteğin zaman aşımı (ms). `0` zaman aşımını kapatır. */
17
18
  timeout?: number;
18
19
  }
20
+ /** Oturum token'ının içeriği. İmza doğrulanmadan okunur; güvenmeden önce sunucuda doğrulayın. */
21
+ export interface SessionClaims {
22
+ iss: string;
23
+ /** Uygulamanın prefix'i. */
24
+ aud: string;
25
+ /** Uygulamayı açan panel kullanıcısı. */
26
+ sub: string;
27
+ store_id: string;
28
+ /** Mağaza alan adı. */
29
+ dest: string;
30
+ iat: number;
31
+ nbf: number;
32
+ exp: number;
33
+ jti: string;
34
+ [claim: string]: unknown;
35
+ }
19
36
  export interface SessionToken {
20
37
  token: string;
38
+ claims: SessionClaims | null;
21
39
  /** Token'ın geçerliliğini yitirdiği an (epoch ms). */
22
40
  expiresAt: number;
23
41
  /** Panelden alınmışsa uygulamanın kapsamları; URL'deki token için `null`. */
@@ -45,6 +63,8 @@ export interface AutoResizeOptions {
45
63
  }
46
64
  export interface App {
47
65
  readonly panelOrigin: string;
66
+ /** Elimizdeki son oturum token'ının içeriği; token yoksa `null`. */
67
+ readonly claims: SessionClaims | null;
48
68
  /** Panelin kurulumdan hemen sonra URL'e eklediği `?code=` değeri. */
49
69
  readonly installCode: string | null;
50
70
  getSessionToken(options?: {
@@ -62,6 +82,13 @@ export interface App {
62
82
  panel(resource: PanelListResource, options?: RequestOptions): Promise<void>;
63
83
  panel(resource: PanelDetailResource, id: string | number, options?: RequestOptions): Promise<void>;
64
84
  };
85
+ nav: {
86
+ /**
87
+ * Panelin sol menüsünde uygulamanın altındaki bağlantıları ayarlar (en fazla 8).
88
+ * Tıklanan bağlantı iframe'i o yolla yeniden yükler; panel listeyi tarayıcıda saklar.
89
+ */
90
+ set(items: NavItem[], options?: RequestOptions): Promise<void>;
91
+ };
65
92
  /** Panelin seçicisini açar. Varsayılan olarak zaman aşımı yoktur. */
66
93
  pickResource(options: PickOptions): Promise<PickResult>;
67
94
  /** iframe yüksekliğini ayarlar; panel 300–5000 px aralığına sıkıştırır. */
@@ -73,4 +100,10 @@ export interface App {
73
100
  /** Dinleyicileri kaldırır, bekleyen istekleri `destroyed` ile reddeder. */
74
101
  destroy(): void;
75
102
  }
103
+ /** Panelin yayınlandığı alan adları (t-panel `PANEL_DOMAINS`). */
104
+ export declare const PANEL_ORIGIN_PATTERN: RegExp;
105
+ /** Sayfa bir iframe içinde mi açılmış. */
106
+ export declare function isEmbedded(): boolean;
107
+ /** JWT gövdesini imza doğrulamadan okur. */
108
+ export declare function decodeSessionToken(token: string): SessionClaims | null;
76
109
  export declare function createApp(options?: AppOptions): App;
package/dist/client.js CHANGED
@@ -7,7 +7,14 @@ export class AppBridgeError extends Error {
7
7
  }
8
8
  }
9
9
  const DEFAULT_TIMEOUT = 10000;
10
- const REFRESH_MARGIN = 30000;
10
+ // Token 60 sn yaşar; sunucuya giderken süresi dolmasın diye 15 sn kala yenilenir.
11
+ const REFRESH_MARGIN = 15000;
12
+ /** Panelin yayınlandığı alan adları (t-panel `PANEL_DOMAINS`). */
13
+ export const PANEL_ORIGIN_PATTERN = /^https:\/\/([a-z0-9-]+\.)*(tsoftpanel\.com|tsoftpanel\.net|paneltsoft\.com)$/;
14
+ /** Sayfa bir iframe içinde mi açılmış. */
15
+ export function isEmbedded() {
16
+ return typeof window !== 'undefined' && window.parent !== window;
17
+ }
11
18
  function detectPanelOrigin() {
12
19
  const ancestors = window.location.ancestorOrigins;
13
20
  if (ancestors && ancestors.length > 0) {
@@ -20,13 +27,12 @@ function detectPanelOrigin() {
20
27
  return null;
21
28
  }
22
29
  }
23
- /** JWT `exp` alanını imza doğrulamadan okur; yalnız önbellek süresi için. */
24
- function tokenExpiry(token) {
30
+ /** JWT gövdesini imza doğrulamadan okur. */
31
+ export function decodeSessionToken(token) {
25
32
  try {
26
- const part = token.split('.')[1];
27
- const json = atob(part.replace(/-/g, '+').replace(/_/g, '/'));
28
- const exp = JSON.parse(json).exp;
29
- return typeof exp === 'number' ? exp * 1000 : null;
33
+ const binary = atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'));
34
+ const claims = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0))));
35
+ return claims && typeof claims.exp === 'number' ? claims : null;
30
36
  }
31
37
  catch (_a) {
32
38
  return null;
@@ -37,13 +43,14 @@ function isFresh(session) {
37
43
  }
38
44
  export function createApp(options = {}) {
39
45
  var _a, _b;
40
- if (typeof window === 'undefined' || window.parent === window) {
46
+ if (!isEmbedded()) {
41
47
  throw new AppBridgeError('not_embedded', 'T-Soft App Bridge: uygulama panel iframe\'i içinde açılmamış');
42
48
  }
43
- const panelOrigin = (_a = options.panelOrigin) !== null && _a !== void 0 ? _a : detectPanelOrigin();
44
- if (!panelOrigin) {
45
- throw new AppBridgeError('not_embedded', 'T-Soft App Bridge: panel origin\'i bulunamadı; panelOrigin seçeneğini verin');
49
+ const detected = options.panelOrigin ? null : detectPanelOrigin();
50
+ if (!options.panelOrigin && !(detected && PANEL_ORIGIN_PATTERN.test(detected))) {
51
+ throw new AppBridgeError('not_embedded', `T-Soft App Bridge: üst pencere bir T-Soft paneli değil (${detected !== null && detected !== void 0 ? detected : 'bilinmiyor'})`);
46
52
  }
53
+ const panelOrigin = ((_a = options.panelOrigin) !== null && _a !== void 0 ? _a : detected);
47
54
  const defaultTimeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT;
48
55
  const pending = new Map();
49
56
  const params = new URLSearchParams(window.location.search);
@@ -53,9 +60,9 @@ export function createApp(options = {}) {
53
60
  let session = null;
54
61
  let refreshing = null;
55
62
  if (urlToken) {
56
- const expiresAt = tokenExpiry(urlToken);
57
- if (expiresAt !== null) {
58
- session = { token: urlToken, expiresAt, scopes: null };
63
+ const claims = decodeSessionToken(urlToken);
64
+ if (claims) {
65
+ session = { token: urlToken, claims, expiresAt: claims.exp * 1000, scopes: null };
59
66
  }
60
67
  }
61
68
  function onMessage(event) {
@@ -106,8 +113,10 @@ export function createApp(options = {}) {
106
113
  }
107
114
  refreshing !== null && refreshing !== void 0 ? refreshing : (refreshing = request('session-token.get', {}, sessionOptions)
108
115
  .then((response) => {
116
+ // expires_in görece olduğu için istemci saatindeki kaymadan etkilenmez.
109
117
  session = {
110
118
  token: response.token,
119
+ claims: decodeSessionToken(response.token),
111
120
  expiresAt: Date.now() + response.expires_in * 1000,
112
121
  scopes: Array.isArray(response.scopes) ? response.scopes : [],
113
122
  };
@@ -123,6 +132,10 @@ export function createApp(options = {}) {
123
132
  }
124
133
  return {
125
134
  panelOrigin,
135
+ get claims() {
136
+ var _a;
137
+ return (_a = session === null || session === void 0 ? void 0 : session.claims) !== null && _a !== void 0 ? _a : null;
138
+ },
126
139
  installCode: params.get('code'),
127
140
  getSession,
128
141
  async getSessionToken(sessionOptions) {
@@ -147,6 +160,11 @@ export function createApp(options = {}) {
147
160
  return empty('navigate.panel', { resource }, idOrOptions);
148
161
  },
149
162
  },
163
+ nav: {
164
+ set(items, requestOptions) {
165
+ return empty('nav.set', { items: items.map(({ label, path }) => ({ label, path })) }, requestOptions);
166
+ },
167
+ },
150
168
  async pickResource({ type, multiple, ...rest }) {
151
169
  const response = await request('resource.pick', { type, multiple: multiple === true }, rest, 0);
152
170
  return { ids: Array.isArray(response.ids) ? response.ids : [], cancelled: response.cancelled === true };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { createApp, AppBridgeError } from './client.js';
2
- export type { App, AppOptions, AutoResizeOptions, ConfirmOptions, PickOptions, PickResult, RequestOptions, SessionToken, ToastOptions, } from './client.js';
1
+ export { createApp, isEmbedded, decodeSessionToken, AppBridgeError, PANEL_ORIGIN_PATTERN } from './client.js';
2
+ export type { App, AppOptions, AutoResizeOptions, ConfirmOptions, PickOptions, PickResult, RequestOptions, SessionClaims, SessionToken, ToastOptions, } from './client.js';
3
3
  export { BRIDGE_VERSION, APP_SOURCE, PANEL_SOURCE } from './protocol.js';
4
- export type { BridgeErrorCode, BridgeRequest, BridgeResponse, PanelDetailResource, PanelListResource, PanelResource, PickableResource, RequestPayloads, RequestType, ResponsePayloads, ToastVariant, } from './protocol.js';
4
+ export type { BridgeErrorCode, BridgeRequest, BridgeResponse, NavItem, PanelDetailResource, PanelListResource, PanelResource, PickableResource, RequestPayloads, RequestType, ResponsePayloads, ToastVariant, } from './protocol.js';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { createApp, AppBridgeError } from './client.js';
1
+ export { createApp, isEmbedded, decodeSessionToken, AppBridgeError, PANEL_ORIGIN_PATTERN } from './client.js';
2
2
  export { BRIDGE_VERSION, APP_SOURCE, PANEL_SOURCE } from './protocol.js';
@@ -32,6 +32,15 @@ export type PanelDetailResource = 'order' | 'product';
32
32
  export type PanelResource = PanelListResource | PanelDetailResource;
33
33
  /** Seçici türü ve istediği kapsam: `product` → `read_products`. */
34
34
  export type PickableResource = 'product';
35
+ /**
36
+ * Panelin sol menüsünde uygulamanın adı altında görünen bağlantı. `path` uygulamanın
37
+ * kendi adresi altında `/` ile başlayan yol olmalı (`/orders?status=1` gibi); etiket
38
+ * en fazla 40 karakter. Liste en fazla 8 öğe; boş liste menüyü kaldırır.
39
+ */
40
+ export interface NavItem {
41
+ label: string;
42
+ path: string;
43
+ }
35
44
  export interface RequestPayloads {
36
45
  'session-token.get': Record<string, never>;
37
46
  'toast.show': {
@@ -57,6 +66,9 @@ export interface RequestPayloads {
57
66
  'size.set': {
58
67
  height: number;
59
68
  };
69
+ 'nav.set': {
70
+ items: NavItem[];
71
+ };
60
72
  }
61
73
  export interface ResponsePayloads {
62
74
  'session-token.get': {
@@ -75,6 +87,7 @@ export interface ResponsePayloads {
75
87
  cancelled?: boolean;
76
88
  };
77
89
  'size.set': Record<string, never>;
90
+ 'nav.set': Record<string, never>;
78
91
  }
79
92
  export type RequestType = keyof RequestPayloads;
80
93
  /**
@@ -0,0 +1 @@
1
+ "use strict";var TSoftAppGate=(()=>{var E=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var z=(o,n)=>{for(var i in n)E(o,i,{get:n[i],enumerable:!0})},V=(o,n,i,u)=>{if(n&&typeof n=="object"||typeof n=="function")for(let a of D(n))!U.call(o,a)&&a!==i&&E(o,a,{get:()=>n[a],enumerable:!(u=L(n,a))||u.enumerable});return o};var G=o=>V(E({},"__esModule",{value:!0}),o);var H={};z(H,{APP_SOURCE:()=>T,AppBridgeError:()=>p,BRIDGE_VERSION:()=>P,PANEL_ORIGIN_PATTERN:()=>S,PANEL_SOURCE:()=>O,createApp:()=>B,decodeSessionToken:()=>x,isEmbedded:()=>b});var P=1,T="tsoft-app",O="tsoft-panel";var p=class extends Error{constructor(n,i){super(i!=null?i:`T-Soft App Bridge: ${n}`),this.name="AppBridgeError",this.code=n}},M=1e4,F=15e3,S=/^https:\/\/([a-z0-9-]+\.)*(tsoftpanel\.com|tsoftpanel\.net|paneltsoft\.com)$/;function b(){return typeof window!="undefined"&&window.parent!==window}function j(){let o=window.location.ancestorOrigins;if(o&&o.length>0)return o[0];try{return document.referrer?new URL(document.referrer).origin:null}catch(n){return null}}function x(o){try{let n=atob(o.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")),i=JSON.parse(new TextDecoder().decode(Uint8Array.from(n,u=>u.charCodeAt(0))));return i&&typeof i.exp=="number"?i:null}catch(n){return null}}function $(o){return o!==null&&o.expiresAt-F>Date.now()}function B(o={}){var h,_;if(!b())throw new p("not_embedded","T-Soft App Bridge: uygulama panel iframe'i i\xE7inde a\xE7\u0131lmam\u0131\u015F");let n=o.panelOrigin?null:j();if(!o.panelOrigin&&!(n&&S.test(n)))throw new p("not_embedded",`T-Soft App Bridge: \xFCst pencere bir T-Soft paneli de\u011Fil (${n!=null?n:"bilinmiyor"})`);let i=(h=o.panelOrigin)!=null?h:n,u=(_=o.timeout)!=null?_:M,a=new Map,k=new URLSearchParams(window.location.search),v=k.get("session"),I=0,A=!1,l=null,R=null;if(v){let t=x(v);t&&(l={token:v,claims:t,expiresAt:t.exp*1e3,scopes:null})}function w(t){var r;if(t.source!==window.parent||t.origin!==i)return;let e=t.data;if((e==null?void 0:e.source)!==O||(e==null?void 0:e.version)!==1||typeof(e==null?void 0:e.id)!="string")return;let s=a.get(e.id);s&&(a.delete(e.id),clearTimeout(s.timer),e.ok===!0?s.resolve((r=e.payload)!=null?r:{}):s.reject(new p(typeof e.error=="string"?e.error:"internal_error")))}window.addEventListener("message",w);function d(t,e,s={},r=u){var y;if(A)return Promise.reject(new p("destroyed"));let c=`app-${Date.now().toString(36)}-${(I++).toString(36)}`,g=(y=s.timeout)!=null?y:r;return new Promise((f,C)=>{let N={resolve:f,reject:C};g>0&&(N.timer=setTimeout(()=>{a.delete(c),C(new p("timeout"))},g)),a.set(c,N),window.parent.postMessage({source:T,version:1,id:c,type:t,payload:e},i)})}async function q(t={}){return!t.forceRefresh&&$(l)?l:(R!=null||(R=d("session-token.get",{},t).then(e=>(l={token:e.token,claims:x(e.token),expiresAt:Date.now()+e.expires_in*1e3,scopes:Array.isArray(e.scopes)?e.scopes:[]},l)).finally(()=>{R=null})),R)}async function m(t,e,s){await d(t,e,s)}return{panelOrigin:i,get claims(){var t;return(t=l==null?void 0:l.claims)!=null?t:null},installCode:k.get("code"),getSession:q,async getSessionToken(t){return(await q(t)).token},toast(t,{variant:e,...s}={}){return m("toast.show",e?{message:t,variant:e}:{message:t},s)},async confirm(t){let{message:e,title:s,confirmText:r,...c}=typeof t=="string"?{message:t}:t;return(await d("confirm.open",{message:e,title:s,confirmText:r},c,0)).confirmed===!0},navigate:{app(t,e){return m("navigate.app",{path:t},e)},panel(t,e,s){return typeof e=="string"||typeof e=="number"?m("navigate.panel",{resource:t,id:String(e)},s):m("navigate.panel",{resource:t},e)}},nav:{set(t,e){return m("nav.set",{items:t.map(({label:s,path:r})=>({label:s,path:r}))},e)}},async pickResource({type:t,multiple:e,...s}){let r=await d("resource.pick",{type:t,multiple:e===!0},s,0);return{ids:Array.isArray(r.ids)?r.ids:[],cancelled:r.cancelled===!0}},setHeight(t,e){return m("size.set",{height:Math.ceil(t)},e)},autoResize({target:t}={}){let e=t!=null?t:document.body,s=0,r=0,c=()=>{r=0;let y=getComputedStyle(e),f=Math.ceil(e.getBoundingClientRect().height+parseFloat(y.marginTop)+parseFloat(y.marginBottom));f!==s&&(s=f,d("size.set",{height:f}).catch(()=>{}))},g=new ResizeObserver(()=>{r||(r=requestAnimationFrame(c))});return g.observe(e),()=>{g.disconnect(),r&&cancelAnimationFrame(r)}},request:d,destroy(){A=!0,window.removeEventListener("message",w);for(let t of a.values())clearTimeout(t.timer),t.reject(new p("destroyed"));a.clear()}}}return G(H);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tekrom/tsoft-app-gate",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "T-Soft paneli içinde açılan uygulamalar için App Bridge istemcisi",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -9,14 +9,17 @@
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
- }
12
+ },
13
+ "./browser": "./dist/tsoft-app-gate.min.js"
13
14
  },
15
+ "unpkg": "./dist/tsoft-app-gate.min.js",
16
+ "jsdelivr": "./dist/tsoft-app-gate.min.js",
14
17
  "files": [
15
18
  "dist"
16
19
  ],
17
20
  "sideEffects": false,
18
21
  "scripts": {
19
- "build": "tsc",
22
+ "build": "tsc && esbuild src/index.ts --bundle --format=iife --global-name=TSoftAppGate --target=es2018 --minify --outfile=dist/tsoft-app-gate.min.js",
20
23
  "test": "npm run build && node --test test/",
21
24
  "prepublishOnly": "npm run build"
22
25
  },
@@ -33,6 +36,7 @@
33
36
  "author": "T-Soft",
34
37
  "license": "MIT",
35
38
  "devDependencies": {
39
+ "esbuild": "^0.25.10",
36
40
  "typescript": "^5.9.3"
37
41
  }
38
42
  }