glitch-javascript-sdk 4.1.0 → 4.2.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.
@@ -1,6 +1,33 @@
1
1
  import Hosting from './api/Hosting';
2
2
  import Config from './config/Config';
3
3
 
4
+ type HostedPreorderOffer = {
5
+ id?: string;
6
+ sku?: string;
7
+ platform_code?: string;
8
+ fulfillment_type?: string;
9
+ state?: string;
10
+ remaining?: number | null;
11
+ };
12
+
13
+ type HostedPreorderCatalog = {
14
+ hosted_checkout_enabled?: boolean;
15
+ offers?: HostedPreorderOffer[];
16
+ };
17
+
18
+ type HostedPreorderClient = {
19
+ open: (options: {
20
+ offerId: string;
21
+ onComplete?: (order: Record<string, any>) => void;
22
+ onClose?: (reason?: string) => void;
23
+ onError?: (error: any) => void;
24
+ }) => Promise<any>;
25
+ restore?: (options?: {
26
+ onClose?: (reason?: string) => void;
27
+ onError?: (error: any) => void;
28
+ }) => Promise<any>;
29
+ };
30
+
4
31
  declare global {
5
32
  interface Window {
6
33
  GlitchHosting?: {
@@ -8,6 +35,7 @@ declare global {
8
35
  session?: Record<string, any>;
9
36
  getContext: () => Record<string, any> | null;
10
37
  };
38
+ GlitchPreorders?: HostedPreorderClient;
11
39
  }
12
40
  }
13
41
 
@@ -15,8 +43,248 @@ const script = document.currentScript as HTMLScriptElement | null;
15
43
  const siteId = script?.dataset.glitchHostingSite || '';
16
44
  const releaseId = script?.dataset.glitchHostingRelease || '';
17
45
  const apiBase = script?.dataset.glitchApiBase || 'https://api.glitch.fun/api';
46
+ const preorderScriptUrl =
47
+ script?.dataset.glitchPreorderScript || 'https://www.glitch.fun/hosting/glitch-preorders.js';
18
48
  Config.setConfig(apiBase, '');
19
49
 
50
+ const preorderSelector =
51
+ '[data-glitch-preorder],[data-glitch-preorder-manage],[data-steam-cta],[data-glitch-cta]';
52
+ let hostedPreorderCatalogPromise: Promise<HostedPreorderCatalog> | null = null;
53
+ let preorderClientPromise: Promise<HostedPreorderClient> | null = null;
54
+ let checkoutOpen = false;
55
+
56
+ const emit = (name: string, detail: Record<string, any>) => {
57
+ window.dispatchEvent(new CustomEvent(name, { detail }));
58
+ };
59
+
60
+ const fetchHostedPreorderCatalog = (): Promise<HostedPreorderCatalog> => {
61
+ if (hostedPreorderCatalogPromise) return hostedPreorderCatalogPromise;
62
+ hostedPreorderCatalogPromise = fetch(`${apiBase.replace(/\/$/, '')}/hosting/preorders/catalog`, {
63
+ method: 'GET',
64
+ mode: 'cors',
65
+ credentials: 'omit',
66
+ cache: 'no-store',
67
+ headers: { Accept: 'application/json' },
68
+ })
69
+ .then(async (response) => {
70
+ if (!response.ok) throw new Error(`Hosted preorder catalog returned HTTP ${response.status}.`);
71
+ const json = await response.json();
72
+ const data = (json?.data || json || {}) as HostedPreorderCatalog;
73
+ if (!data.hosted_checkout_enabled) throw new Error('Hosted preorder checkout is disabled.');
74
+ if (!Array.isArray(data.offers)) data.offers = [];
75
+ return data;
76
+ })
77
+ .catch((error) => {
78
+ hostedPreorderCatalogPromise = null;
79
+ throw error;
80
+ });
81
+ return hostedPreorderCatalogPromise;
82
+ };
83
+
84
+ const loadPreorderClient = (): Promise<HostedPreorderClient> => {
85
+ if (window.GlitchPreorders?.open) return Promise.resolve(window.GlitchPreorders);
86
+ if (preorderClientPromise) return preorderClientPromise;
87
+
88
+ preorderClientPromise = new Promise<HostedPreorderClient>((resolve, reject) => {
89
+ const existing = document.querySelector<HTMLScriptElement>(
90
+ 'script[data-glitch-hosted-preorders-runtime="1"]'
91
+ );
92
+ const runtimeScript = existing || document.createElement('script');
93
+ const finish = () => {
94
+ if (window.GlitchPreorders?.open) resolve(window.GlitchPreorders);
95
+ else reject(new Error('Glitch hosted preorder runtime loaded without a checkout client.'));
96
+ };
97
+
98
+ runtimeScript.addEventListener('load', finish, { once: true });
99
+ runtimeScript.addEventListener(
100
+ 'error',
101
+ () => reject(new Error('Glitch hosted preorder runtime could not be loaded.')),
102
+ { once: true }
103
+ );
104
+
105
+ if (!existing) {
106
+ runtimeScript.src = preorderScriptUrl;
107
+ runtimeScript.async = true;
108
+ runtimeScript.dataset.glitchHostedPreordersRuntime = '1';
109
+ runtimeScript.referrerPolicy = 'no-referrer';
110
+ document.head.appendChild(runtimeScript);
111
+ } else if (window.GlitchPreorders?.open) {
112
+ finish();
113
+ }
114
+ }).catch((error) => {
115
+ preorderClientPromise = null;
116
+ throw error;
117
+ });
118
+
119
+ return preorderClientPromise;
120
+ };
121
+
122
+ const isAvailable = (offer?: HostedPreorderOffer) =>
123
+ Boolean(
124
+ offer &&
125
+ offer.state === 'available' &&
126
+ (offer.remaining === null || offer.remaining === undefined || Number(offer.remaining) > 0)
127
+ );
128
+
129
+ const offerForElement = (
130
+ element: HTMLElement,
131
+ offers: HostedPreorderOffer[]
132
+ ): HostedPreorderOffer | undefined => {
133
+ const explicitId =
134
+ element.dataset.glitchPreorderOfferId ||
135
+ element.dataset.offerId;
136
+ if (explicitId) {
137
+ const byId = offers.find((offer) => offer.id === explicitId);
138
+ if (byId) return byId;
139
+ }
140
+
141
+ const explicitSku =
142
+ element.dataset.glitchPreorderSku ||
143
+ element.dataset.preorderSku ||
144
+ (element.dataset.glitchPreorder && element.dataset.glitchPreorder !== 'true'
145
+ ? element.dataset.glitchPreorder
146
+ : undefined);
147
+ if (explicitSku) {
148
+ const bySku = offers.find((offer) => offer.sku === explicitSku);
149
+ if (bySku) return bySku;
150
+ }
151
+
152
+ if (element.hasAttribute('data-steam-cta')) {
153
+ return offers.find((offer) => offer.platform_code === 'steam');
154
+ }
155
+ if (element.hasAttribute('data-glitch-cta')) {
156
+ return offers.find(
157
+ (offer) => offer.fulfillment_type === 'glitch_license' || offer.platform_code === 'glitch'
158
+ );
159
+ }
160
+
161
+ return offers.find(isAvailable);
162
+ };
163
+
164
+ const fallbackNavigate = (element: HTMLElement) => {
165
+ if (element instanceof HTMLAnchorElement && element.href) {
166
+ window.location.assign(element.href);
167
+ }
168
+ };
169
+
170
+ const focusAvailableAlternative = (
171
+ selected: HostedPreorderOffer | undefined,
172
+ offers: HostedPreorderOffer[]
173
+ ) => {
174
+ if (selected?.platform_code !== 'steam') return;
175
+ const alternative = offers.find(
176
+ (offer) =>
177
+ isAvailable(offer) &&
178
+ (offer.fulfillment_type === 'glitch_license' || offer.platform_code === 'glitch')
179
+ );
180
+ if (!alternative) return;
181
+ const element = document.querySelector<HTMLElement>('[data-glitch-cta]');
182
+ element?.focus({ preventScroll: false });
183
+ };
184
+
185
+ const initializeHostedPreorderBridge = () => {
186
+ if (!document.querySelector(preorderSelector)) return;
187
+
188
+ document.addEventListener(
189
+ 'click',
190
+ (event) => {
191
+ const target = event.target;
192
+ if (!(target instanceof Element)) return;
193
+ const element = target.closest<HTMLElement>(preorderSelector);
194
+ if (!element) return;
195
+
196
+ event.preventDefault();
197
+
198
+ if (checkoutOpen) return;
199
+
200
+ void (async () => {
201
+ try {
202
+ const catalog = await fetchHostedPreorderCatalog();
203
+ const offers = catalog.offers || [];
204
+
205
+ if (element.hasAttribute('data-glitch-preorder-manage')) {
206
+ const client = await loadPreorderClient();
207
+ if (!client.restore) throw new Error('Hosted preorder management is unavailable.');
208
+ checkoutOpen = true;
209
+ emit('glitch:preorder-open', { mode: 'manage', hosting_site_id: siteId });
210
+ await client.restore({
211
+ onClose: (reason) => {
212
+ checkoutOpen = false;
213
+ emit('glitch:preorder-close', { mode: 'manage', reason });
214
+ },
215
+ onError: (error) => {
216
+ checkoutOpen = false;
217
+ emit('glitch:preorder-error', {
218
+ mode: 'manage',
219
+ message: error?.message || 'Preorder management could not be opened.',
220
+ });
221
+ },
222
+ });
223
+ return;
224
+ }
225
+
226
+ const offer = offerForElement(element, offers);
227
+ if (!isAvailable(offer) || !offer?.id) {
228
+ emit('glitch:preorder-unavailable', {
229
+ offer_id: offer?.id,
230
+ sku: offer?.sku,
231
+ state: offer?.state || 'unavailable',
232
+ });
233
+ element.setAttribute('aria-disabled', 'true');
234
+ focusAvailableAlternative(offer, offers);
235
+ return;
236
+ }
237
+
238
+ const client = await loadPreorderClient();
239
+ checkoutOpen = true;
240
+ emit('glitch:preorder-open', {
241
+ mode: 'purchase',
242
+ offer_id: offer.id,
243
+ sku: offer.sku,
244
+ hosting_site_id: siteId,
245
+ });
246
+
247
+ await client.open({
248
+ offerId: offer.id,
249
+ onComplete: (order) => {
250
+ hostedPreorderCatalogPromise = null;
251
+ emit('glitch:preorder-complete', {
252
+ order,
253
+ offer_id: offer.id,
254
+ sku: offer.sku,
255
+ });
256
+ },
257
+ onClose: (reason) => {
258
+ checkoutOpen = false;
259
+ emit('glitch:preorder-close', {
260
+ mode: 'purchase',
261
+ offer_id: offer.id,
262
+ sku: offer.sku,
263
+ reason,
264
+ });
265
+ },
266
+ onError: (error) => {
267
+ checkoutOpen = false;
268
+ emit('glitch:preorder-error', {
269
+ mode: 'purchase',
270
+ offer_id: offer.id,
271
+ sku: offer.sku,
272
+ message: error?.message || 'Preorder checkout could not be opened.',
273
+ });
274
+ },
275
+ });
276
+ } catch (error: any) {
277
+ emit('glitch:preorder-error', {
278
+ message: error?.message || 'Hosted preorder checkout is unavailable.',
279
+ });
280
+ fallbackNavigate(element);
281
+ }
282
+ })();
283
+ },
284
+ true
285
+ );
286
+ };
287
+
20
288
  const ready = Hosting.startPlaySession<Record<string, any>>({
21
289
  hostname: window.location.hostname,
22
290
  hosting_site_id: siteId || undefined,
@@ -26,13 +294,18 @@ const ready = Hosting.startPlaySession<Record<string, any>>({
26
294
  const session = (response as any)?.data?.data || (response as any)?.data || response;
27
295
  if (window.GlitchHosting) window.GlitchHosting.session = session;
28
296
  window.dispatchEvent(new CustomEvent('glitch:hosting-ready', { detail: session }));
29
- const heartbeat = () => Hosting.heartbeatPlaySession(session.session_id, session.session_token).catch(() => undefined);
297
+ const heartbeat = () =>
298
+ Hosting.heartbeatPlaySession(session.session_id, session.session_token).catch(() => undefined);
30
299
  const interval = window.setInterval(heartbeat, 60_000);
31
300
  window.addEventListener('pagehide', () => window.clearInterval(interval), { once: true });
32
301
 
33
302
  return session;
34
303
  }).catch((error) => {
35
- window.dispatchEvent(new CustomEvent('glitch:hosting-error', { detail: { message: error?.message || 'Hosting analytics could not start.' } }));
304
+ window.dispatchEvent(
305
+ new CustomEvent('glitch:hosting-error', {
306
+ detail: { message: error?.message || 'Hosting analytics could not start.' },
307
+ })
308
+ );
36
309
  // Analytics must never prevent the uploaded game itself from loading.
37
310
  return null as any;
38
311
  });
@@ -42,4 +315,6 @@ window.GlitchHosting = {
42
315
  getContext: () => window.GlitchHosting?.session || null,
43
316
  };
44
317
 
318
+ initializeHostedPreorderBridge();
319
+
45
320
  export {};
package/src/index.ts CHANGED
@@ -31,6 +31,7 @@ import {Publications} from "./api";
31
31
  import {GameShows} from "./api";
32
32
  import FestivalNetworking from './api/FestivalNetworking';
33
33
  export * from './api/FestivalNetworking';
34
+ export type { AegisLicenseType, AegisLicenseDetail, AegisInstallValidation, GameMonetizationSettings } from './api/Titles';
34
35
  import {Newsletters} from "./api";
35
36
  import {PlayTests} from "./api";
36
37
  import {Media} from "./api";
@@ -71,6 +71,7 @@ class CampaignsRoute {
71
71
  sendCampaignContractWithDocusign: { url: '/campaigns/{campaign_id}/influencers/{user_id}/docusign', method: HTTP_METHODS.POST },
72
72
  sourcingSearchIgdbForCampaignGame: { url: '/campaigns/{campaign_id}/sourcing/search-game', method: HTTP_METHODS.GET },
73
73
  sourcingGetSimilarIgdbGames: { url: '/campaigns/{campaign_id}/sourcing/similar-games', method: HTTP_METHODS.GET },
74
+ sourcingGetActiveStreamLookalikes: { url: '/campaigns/{campaign_id}/sourcing/active-stream-lookalikes', method: HTTP_METHODS.POST },
74
75
  sourcingFindCreators: { url: '/campaigns/{campaign_id}/sourcing/find-creators', method: HTTP_METHODS.POST },
75
76
  updateSourcingSettings: { url: '/campaigns/{campaign_id}/sourcing/settings', method: HTTP_METHODS.PUT },
76
77
  sourcingFindAndSaveCreators: { url: '/campaigns/{campaign_id}/sourcing/find-save-creators', method: HTTP_METHODS.POST },
@@ -15,6 +15,11 @@ class McpRoute {
15
15
  listTitles: { url: "/mcp/v1/titles", method: HTTP_METHODS.GET },
16
16
  titleContext: { url: "/mcp/v1/titles/{title_id}/context", method: HTTP_METHODS.GET },
17
17
  billing: { url: "/mcp/v1/titles/{title_id}/billing", method: HTTP_METHODS.GET },
18
+ socialCapabilities: { url: "/mcp/v1/titles/{title_id}/social/capabilities", method: HTTP_METHODS.GET },
19
+ socialOperation: { url: "/mcp/v1/titles/{title_id}/social/operations/{operation}", method: HTTP_METHODS.POST },
20
+ marketingCapabilities: { url: "/mcp/v1/titles/{title_id}/marketing/capabilities", method: HTTP_METHODS.GET },
21
+ marketingOperation: { url: "/mcp/v1/titles/{title_id}/marketing/operations/{operation}", method: HTTP_METHODS.POST },
22
+ influencerCampaignOperation: { url: "/mcp/v1/titles/{title_id}/influencer-campaigns/{operation}", method: HTTP_METHODS.POST },
18
23
  startRun: { url: "/mcp/v1/titles/{title_id}/runs", method: HTTP_METHODS.POST },
19
24
  viewRun: { url: "/mcp/v1/titles/{title_id}/runs/{run_id}", method: HTTP_METHODS.GET },
20
25
  runEvents: { url: "/mcp/v1/titles/{title_id}/runs/{run_id}/events", method: HTTP_METHODS.GET },
@@ -3,6 +3,18 @@ import HTTP_METHODS from '../constants/HttpMethods';
3
3
 
4
4
  class PreordersRoute {
5
5
  public static routes: { [key: string]: Route } = {
6
+ hostedCatalog: { url: '/hosting/preorders/catalog', method: HTTP_METHODS.GET },
7
+ createHostedSession: { url: '/hosting/preorders/checkout-sessions', method: HTTP_METHODS.POST },
8
+ createHostedRestoreSession: { url: '/hosting/preorders/restore-sessions', method: HTTP_METHODS.POST },
9
+ hostedSession: { url: '/titles/{title_id}/preorders/hosted/checkout-sessions/{session_id}', method: HTTP_METHODS.GET },
10
+ hostedMine: { url: '/titles/{title_id}/preorders/hosted/checkout-sessions/{session_id}/me', method: HTTP_METHODS.GET },
11
+ hostedAuthenticate: { url: '/titles/{title_id}/preorders/hosted/checkout-sessions/{session_id}/authenticate', method: HTTP_METHODS.POST },
12
+ hostedCheckout: { url: '/titles/{title_id}/preorders/hosted/checkout-sessions/{session_id}/checkout', method: HTTP_METHODS.POST },
13
+ hostedReconcile: { url: '/titles/{title_id}/preorders/hosted/checkout-sessions/{session_id}/reconcile', method: HTTP_METHODS.POST },
14
+ hostedRetry: { url: '/titles/{title_id}/preorders/hosted/checkout-sessions/{session_id}/retry', method: HTTP_METHODS.POST },
15
+ hostedRefund: { url: '/titles/{title_id}/preorders/hosted/checkout-sessions/{session_id}/refund', method: HTTP_METHODS.POST },
16
+ hostedResendAccess: { url: '/titles/{title_id}/preorders/hosted/checkout-sessions/{session_id}/resend-access', method: HTTP_METHODS.POST },
17
+
6
18
  catalog: { url: '/titles/{title_id}/preorders', method: HTTP_METHODS.GET },
7
19
  purchase: { url: '/titles/{title_id}/preorders/{offer_id}/purchase', method: HTTP_METHODS.POST },
8
20
  myOrders: { url: '/titles/{title_id}/preorders/me/orders', method: HTTP_METHODS.GET },
@@ -316,6 +316,19 @@ class TitlesRoute {
316
316
  reviewsReport: { url: '/reviews/{review_id}/report', method: HTTP_METHODS.POST },
317
317
  reviewsDeveloperResponse: { url: '/reviews/{review_id}/developer-response', method: HTTP_METHODS.POST },
318
318
 
319
+ // Steamworks Financial API (IPartnerFinancialsService): key, sync, stored data, live read-through.
320
+ steamFinancialsStatus: { url: '/titles/{title_id}/steam/financials', method: HTTP_METHODS.GET },
321
+ steamFinancialsConnect: { url: '/titles/{title_id}/steam/financials/key', method: HTTP_METHODS.PUT },
322
+ steamFinancialsTestKey: { url: '/titles/{title_id}/steam/financials/key/test', method: HTTP_METHODS.POST },
323
+ steamFinancialsDisconnect: { url: '/titles/{title_id}/steam/financials/key', method: HTTP_METHODS.DELETE },
324
+ steamFinancialsSync: { url: '/titles/{title_id}/steam/financials/sync', method: HTTP_METHODS.POST },
325
+ steamFinancialsReports: { url: '/titles/{title_id}/steam/financials/reports', method: HTTP_METHODS.GET },
326
+ steamFinancialsSales: { url: '/titles/{title_id}/steam/financials/sales', method: HTTP_METHODS.GET },
327
+ steamFinancialsWishlists: { url: '/titles/{title_id}/steam/financials/wishlists', method: HTTP_METHODS.GET },
328
+ steamFinancialsLookups: { url: '/titles/{title_id}/steam/financials/lookups', method: HTTP_METHODS.GET },
329
+ steamFinancialsLiveChangedDates: { url: '/titles/{title_id}/steam/financials/live/changed-dates', method: HTTP_METHODS.GET },
330
+ steamFinancialsLiveDetailedSales: { url: '/titles/{title_id}/steam/financials/live/detailed-sales', method: HTTP_METHODS.GET },
331
+ steamFinancialsLiveWishlist: { url: '/titles/{title_id}/steam/financials/live/wishlist', method: HTTP_METHODS.GET },
319
332
  };
320
333
 
321
334
  }