@jskit-ai/rewarded-web 0.2.5 → 0.2.6

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
@@ -14,7 +14,9 @@ const result = await rewarded.requireUnlock({ gateKey: "bonus", workspaceSlug })
14
14
  The workflow opens a prompt before delivery. It handles existing unlocks, grants,
15
15
  closed sessions and unavailable delivery through the app's `/rewarded/*` routes.
16
16
  The delivery capability supplies `launchReward({ providerConfig, onReady,
17
- onGranted, onClosed, onUnavailable })`, returning a promise for its lifecycle.
17
+ onGranted, onClosed, onUnavailable })`, returning a promise for its lifecycle;
18
+ the workflow always passes all four callbacks, and
19
+ `@jskit-ai/rewarded-web/client/types` names the contract as `RewardedDelivery`.
18
20
  Provider configuration is opaque to the workflow. The application authorizes
19
21
  server grants; browser callbacks alone do not prove provider viewing.
20
22
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/rewarded-web",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -8,6 +8,7 @@
8
8
  "exports": {
9
9
  ".": "./src/index.js",
10
10
  "./client": "./src/client/index.js",
11
+ "./client/types": "./src/client/types.js",
11
12
  "./server": "./src/server/index.js",
12
13
  "./shared": "./src/shared/index.js",
13
14
  "./locales/en.json": "./locales/en.json"
@@ -46,6 +47,10 @@
46
47
  {
47
48
  "subpath": "./client",
48
49
  "summary": "Exports the Rewarded client provider, runtime composable, and fullscreen gate host."
50
+ },
51
+ {
52
+ "subpath": "./client/types",
53
+ "summary": "The delivery contract an application supplies and the runtime it receives, as JSDoc types."
49
54
  }
50
55
  ]
51
56
  },
@@ -55,12 +60,12 @@
55
60
  }
56
61
  },
57
62
  "dependencies": {
58
- "@jskit-ai/rewarded-core": "0.2.5"
63
+ "@jskit-ai/rewarded-core": "0.2.6"
59
64
  },
60
65
  "peerDependencies": {
61
- "@jskit-ai/http-runtime": "0.2.4",
62
- "@jskit-ai/kernel": "0.2.4",
63
- "@jskit-ai/shell-web": "0.2.4",
66
+ "@jskit-ai/http-runtime": "0.2.5",
67
+ "@jskit-ai/kernel": "0.2.5",
68
+ "@jskit-ai/shell-web": "0.2.5",
64
69
  "vue": "^3.5.13"
65
70
  }
66
71
  }
@@ -1,4 +1,6 @@
1
+ // readable-check: allow module-state - shared resource: a page loads Google Publisher Tag and enables its services once
1
2
  let gptLoadPromise = null;
3
+ // readable-check: allow module-state - shared resource: a page loads Google Publisher Tag and enables its services once
2
4
  let gptServicesEnabled = false;
3
5
 
4
6
  async function ensureGooglePublisherTagLoaded() {
@@ -37,13 +39,14 @@ async function ensureGooglePublisherTagLoaded() {
37
39
  return gptLoadPromise;
38
40
  }
39
41
 
42
+ /** @param {import("@jskit-ai/rewarded-web/client/types").RewardedLaunch} launch */
40
43
  function launchGoogleRewardedAd({
41
44
  providerConfig,
42
- onReady = null,
43
- onGranted = null,
44
- onClosed = null,
45
- onUnavailable = null
46
- } = {}) {
45
+ onReady,
46
+ onGranted,
47
+ onClosed,
48
+ onUnavailable
49
+ }) {
47
50
  if (providerConfig?.provider !== "google-publisher-tag") {
48
51
  throw new TypeError("Google delivery requires provider google-publisher-tag.");
49
52
  }
@@ -61,7 +64,7 @@ function launchGoogleRewardedAd({
61
64
 
62
65
  const slot = googletag.defineOutOfPageSlot(placement, rewardedFormat);
63
66
  if (!slot) {
64
- Promise.resolve(onUnavailable?.()).finally(() => {
67
+ Promise.resolve(onUnavailable()).finally(() => {
65
68
  reject(new Error("Rewarded ads are not available on this page."));
66
69
  });
67
70
  return;
@@ -82,7 +85,7 @@ function launchGoogleRewardedAd({
82
85
  return;
83
86
  }
84
87
  readySeen = true;
85
- await Promise.resolve(onReady?.());
88
+ await Promise.resolve(onReady());
86
89
  event.makeRewardedVisible();
87
90
  };
88
91
 
@@ -90,7 +93,7 @@ function launchGoogleRewardedAd({
90
93
  if (event?.slot !== slot || settled) {
91
94
  return;
92
95
  }
93
- await Promise.resolve(onGranted?.());
96
+ await Promise.resolve(onGranted());
94
97
  };
95
98
 
96
99
  const handleClosed = async (event) => {
@@ -100,7 +103,7 @@ function launchGoogleRewardedAd({
100
103
  settled = true;
101
104
  cleanup();
102
105
  try {
103
- await Promise.resolve(onClosed?.());
106
+ await Promise.resolve(onClosed());
104
107
  resolve();
105
108
  } catch (error) {
106
109
  reject(error);
@@ -124,7 +127,7 @@ function launchGoogleRewardedAd({
124
127
  }
125
128
  settled = true;
126
129
  cleanup();
127
- Promise.resolve(onUnavailable?.()).finally(() => {
130
+ Promise.resolve(onUnavailable()).finally(() => {
128
131
  reject(new Error("No rewarded ad was available."));
129
132
  });
130
133
  }, 10000);
@@ -1,39 +1,33 @@
1
1
  <script setup>
2
2
  import { computed } from "vue";
3
- import { useRewardedRuntime } from "../composables/useRewardedRuntime.js";
4
3
  import { useJskitText } from "../i18n.js";
5
4
 
6
5
  const props = defineProps({
7
6
  runtime: {
8
- type: Object,
9
- required: false,
10
- default: null
7
+ type: /** @type {import("vue").PropType<import("../types.js").RewardedRuntime>} */ (Object),
8
+ required: true
11
9
  }
12
10
  });
13
11
 
14
12
  const { t } = useJskitText();
15
- const runtime = computed(() => props.runtime || useRewardedRuntime());
16
- const state = computed(() => runtime.value?.state || null);
17
- const isVisible = computed(() => {
18
- const currentState = state.value;
19
- return currentState?.open === true && currentState?.phase !== "showing-ad";
20
- });
21
- const titleText = computed(() => state.value?.gateState?.rule?.title || t("jskit.rewarded.gate.defaultTitle"));
13
+ const state = computed(() => props.runtime.state);
14
+ const isVisible = computed(() => state.value.open === true && state.value.phase !== "showing-ad");
15
+ const titleText = computed(() => state.value.gateState?.rule?.title || t("jskit.rewarded.gate.defaultTitle"));
22
16
  const descriptionText = computed(() =>
23
- state.value?.gateState?.rule?.description ||
17
+ state.value.gateState?.rule?.description ||
24
18
  t("jskit.rewarded.gate.defaultDescription")
25
19
  );
26
20
 
27
21
  function handleWatchClick() {
28
- runtime.value?.beginWatch?.();
22
+ props.runtime.beginWatch();
29
23
  }
30
24
 
31
25
  function handleCancelClick() {
32
- runtime.value?.cancelPrompt?.();
26
+ props.runtime.cancelPrompt();
33
27
  }
34
28
 
35
29
  function handleDismissError() {
36
- runtime.value?.dismissError?.();
30
+ props.runtime.dismissError();
37
31
  }
38
32
  </script>
39
33
 
@@ -47,22 +41,22 @@ function handleDismissError() {
47
41
  <p class="rewarded-gate__description">{{ descriptionText }}</p>
48
42
 
49
43
  <p
50
- v-if="state?.phase === 'loading'"
44
+ v-if="state.phase === 'loading'"
51
45
  class="rewarded-gate__status"
52
46
  >
53
47
  {{ t("jskit.rewarded.gate.loading") }}
54
48
  </p>
55
49
 
56
50
  <p
57
- v-else-if="state?.phase === 'error'"
51
+ v-else-if="state.phase === 'error'"
58
52
  class="rewarded-gate__status rewarded-gate__status--error"
59
53
  >
60
- {{ state?.errorMessage || t("jskit.rewarded.gate.startFailed") }}
54
+ {{ state.errorMessage || t("jskit.rewarded.gate.startFailed") }}
61
55
  </p>
62
56
 
63
57
  <div class="rewarded-gate__actions">
64
58
  <button
65
- v-if="state?.phase === 'prompt'"
59
+ v-if="state.phase === 'prompt'"
66
60
  type="button"
67
61
  class="rewarded-gate__button rewarded-gate__button--primary"
68
62
  @click="handleWatchClick"
@@ -71,7 +65,7 @@ function handleDismissError() {
71
65
  </button>
72
66
 
73
67
  <button
74
- v-if="state?.phase === 'prompt'"
68
+ v-if="state.phase === 'prompt'"
75
69
  type="button"
76
70
  class="rewarded-gate__button"
77
71
  @click="handleCancelClick"
@@ -80,7 +74,7 @@ function handleDismissError() {
80
74
  </button>
81
75
 
82
76
  <button
83
- v-if="state?.phase === 'error'"
77
+ v-if="state.phase === 'error'"
84
78
  type="button"
85
79
  class="rewarded-gate__button rewarded-gate__button--primary"
86
80
  @click="handleDismissError"
@@ -1,8 +1,9 @@
1
1
  import { inject } from "vue";
2
2
  import { REWARDED_RUNTIME_INJECTION_KEY } from "../runtime/rewardedRuntime.js";
3
3
 
4
+ /** @returns {import("../types.js").RewardedRuntime} */
4
5
  function useRewardedRuntime() {
5
- return inject(REWARDED_RUNTIME_INJECTION_KEY, null);
6
+ return inject(REWARDED_RUNTIME_INJECTION_KEY);
6
7
  }
7
8
 
8
9
  export { useRewardedRuntime };
@@ -6,7 +6,6 @@ import {
6
6
  createRewardedRuntime
7
7
  } from "../runtime/rewardedRuntime.js";
8
8
 
9
-
10
9
  const mountedHosts = new WeakMap();
11
10
 
12
11
  const RewardedClientProvider = defineProvider({
@@ -18,11 +17,16 @@ const RewardedClientProvider = defineProvider({
18
17
  provides: {
19
18
  rewarded: "client.rewarded"
20
19
  },
20
+ /** @param {{ delivery: import("../types.js").RewardedDelivery }} capabilities */
21
21
  setup({ delivery }) {
22
22
  return {
23
23
  rewarded: createRewardedRuntime({ launchReward: delivery.launchReward })
24
24
  };
25
25
  },
26
+ /**
27
+ * @param {{ vueApp: import("@jskit-ai/kernel/client/types").ClientVueApp }} capabilities
28
+ * @param {{ outputs: { rewarded: import("../types.js").RewardedRuntime } }} context
29
+ */
26
30
  async boot({ vueApp }, { outputs }) {
27
31
  if (typeof document === "undefined") {
28
32
  return;
@@ -30,9 +34,7 @@ const RewardedClientProvider = defineProvider({
30
34
 
31
35
  const runtime = outputs.rewarded;
32
36
 
33
- if (vueApp && typeof vueApp.provide === "function") {
34
- vueApp.provide(REWARDED_RUNTIME_INJECTION_KEY, runtime);
35
- }
37
+ vueApp.provide(REWARDED_RUNTIME_INJECTION_KEY, runtime);
36
38
 
37
39
  const hostContainer = document.createElement("div");
38
40
  hostContainer.dataset.jskitRewardedHost = "true";
@@ -41,11 +43,15 @@ const RewardedClientProvider = defineProvider({
41
43
  const vnode = h(RewardedGateHost, {
42
44
  runtime
43
45
  });
44
- vnode.appContext = vueApp?._context || null;
46
+ vnode.appContext = vueApp._context;
45
47
  render(vnode, hostContainer);
46
48
  mountedHosts.set(runtime, hostContainer);
47
49
  },
48
- shutdown(_dependencies, { outputs }) {
50
+ /**
51
+ * @param {object} _capabilities
52
+ * @param {{ outputs: { rewarded: import("../types.js").RewardedRuntime } }} context
53
+ */
54
+ shutdown(_capabilities, { outputs }) {
49
55
  const hostContainer = mountedHosts.get(outputs.rewarded);
50
56
  if (!hostContainer) {
51
57
  return;
@@ -67,19 +67,18 @@ function isWellFormedGateState(gateState = null) {
67
67
  return Boolean(gateState.unlock) || REWARDED_NON_BLOCKING_REASONS.has(reason);
68
68
  }
69
69
 
70
- function buildApiPath(workspaceSlug = "", action = "", query = null) {
70
+ function buildApiPath(workspaceSlug = "", action = "", query = new URLSearchParams()) {
71
71
  const normalizedWorkspaceSlug = normalizeWorkspaceSlug(workspaceSlug);
72
72
  const pathname = `/api/w/${encodeURIComponent(normalizedWorkspaceSlug)}/rewarded/${action}`;
73
- if (!(query instanceof URLSearchParams) || [...query.keys()].length < 1) {
74
- return pathname;
75
- }
76
- return `${pathname}?${query.toString()}`;
73
+ const search = query.toString();
74
+ return search ? `${pathname}?${search}` : pathname;
77
75
  }
78
76
 
79
- function createRewardedRuntime({ launchReward } = {}) {
80
- if (typeof launchReward !== "function") {
81
- throw new TypeError("Rewarded runtime requires an explicit launchReward delivery function.");
82
- }
77
+ /**
78
+ * @param {object} options
79
+ * @param {import("../types.js").RewardedDelivery["launchReward"]} options.launchReward
80
+ */
81
+ function createRewardedRuntime({ launchReward }) {
83
82
  const { t, errorMessage } = useJskitText();
84
83
  const state = reactive(createInitialState());
85
84
  let pendingResolve = null;
@@ -94,24 +93,24 @@ function createRewardedRuntime({ launchReward } = {}) {
94
93
  function settle(result) {
95
94
  const resolver = pendingResolve;
96
95
  resetState();
97
- if (typeof resolver === "function") {
96
+ if (resolver !== null) {
98
97
  resolver(result);
99
98
  }
100
99
  }
101
100
 
102
- async function requestCurrent(input = {}) {
103
- const params = new URLSearchParams({
104
- gateKey: String(input.gateKey || "")
105
- });
106
- return rewardedHttpClient.request(
107
- buildApiPath(input.workspaceSlug, "current", params),
108
- {
101
+ async function requestCurrent(input) {
102
+ const params = new URLSearchParams({
103
+ gateKey: String(input.gateKey || "")
104
+ });
105
+ return rewardedHttpClient.request(
106
+ buildApiPath(input.workspaceSlug, "current", params),
107
+ {
109
108
  method: "GET"
110
109
  }
111
110
  );
112
111
  }
113
112
 
114
- async function requestStart(input = {}) {
113
+ async function requestStart(input) {
115
114
  return rewardedHttpClient.request(
116
115
  buildApiPath(input.workspaceSlug, "start"),
117
116
  {
@@ -123,7 +122,7 @@ async function requestCurrent(input = {}) {
123
122
  );
124
123
  }
125
124
 
126
- async function requestGrant(input = {}) {
125
+ async function requestGrant(input) {
127
126
  return rewardedHttpClient.request(
128
127
  buildApiPath(input.workspaceSlug, "grant"),
129
128
  {
@@ -135,7 +134,7 @@ async function requestCurrent(input = {}) {
135
134
  );
136
135
  }
137
136
 
138
- async function requestClose(input = {}) {
137
+ async function requestClose(input) {
139
138
  return rewardedHttpClient.request(
140
139
  buildApiPath(input.workspaceSlug, "close"),
141
140
  {
@@ -148,8 +147,8 @@ async function requestCurrent(input = {}) {
148
147
  }
149
148
 
150
149
  async function requireUnlock(request = {}) {
151
- const gateKey = String(request?.gateKey || "").trim();
152
- const workspaceSlug = normalizeWorkspaceSlug(request?.workspaceSlug);
150
+ const gateKey = String(request.gateKey || "").trim();
151
+ const workspaceSlug = normalizeWorkspaceSlug(request.workspaceSlug);
153
152
 
154
153
  if (!gateKey) {
155
154
  throw new Error("requireUnlock requires gateKey.");
@@ -165,8 +164,8 @@ async function requestCurrent(input = {}) {
165
164
  if (!isWellFormedGateState(gateState)) {
166
165
  throw rewardedClientError("Rewarded gate returned an invalid state.", { messageCode: "rewarded.gate.invalidState" });
167
166
  }
168
- const alreadyUnlocked = gateState?.blocked === false && gateState?.unlock;
169
- if (!gateState?.enabled || !gateState?.blocked) {
167
+ const alreadyUnlocked = gateState.blocked === false && gateState.unlock;
168
+ if (!gateState.enabled || !gateState.blocked) {
170
169
  return {
171
170
  granted: Boolean(alreadyUnlocked),
172
171
  state: gateState
@@ -317,13 +316,13 @@ async function requestCurrent(input = {}) {
317
316
  await cancelPrompt();
318
317
  }
319
318
 
320
- return Object.freeze({
319
+ return {
321
320
  state,
322
321
  requireUnlock,
323
322
  beginWatch,
324
323
  cancelPrompt,
325
324
  dismissError
326
- });
325
+ };
327
326
  }
328
327
 
329
328
  export {
@@ -0,0 +1,22 @@
1
+ // The values rewarded's client hands out and receives across files, for its own modules and for the application that
2
+ // supplies delivery or asks for an unlock.
3
+
4
+ /**
5
+ * What a delivery receives for one reward. The workflow always passes all four callbacks.
6
+ * @typedef {object} RewardedLaunch
7
+ * @property {Record<string, unknown>} providerConfig The provider's configuration, opaque to the workflow.
8
+ * @property {() => void} onReady
9
+ * @property {() => Promise<void>} onGranted
10
+ * @property {() => Promise<void>} onClosed
11
+ * @property {() => void} onUnavailable
12
+ */
13
+
14
+ /**
15
+ * The `client.rewarded-delivery` capability an application supplies.
16
+ * @typedef {object} RewardedDelivery
17
+ * @property {(launch: RewardedLaunch) => Promise<void>} launchReward Settles when the reward's lifecycle ends.
18
+ */
19
+
20
+ /** @typedef {ReturnType<typeof import("./runtime/rewardedRuntime.js").createRewardedRuntime>} RewardedRuntime The `client.rewarded` capability. */
21
+
22
+ export {};
@@ -564,8 +564,7 @@ test("google rewarded runtime exposes an error state when no rewarded slot is av
564
564
  });
565
565
 
566
566
 
567
- test("reward orchestration requires explicit delivery and accepts non-Google configuration", async () => {
568
- assert.throws(() => createRewardedRuntime(), /explicit launchReward/);
567
+ test("reward orchestration accepts non-Google configuration", async () => {
569
568
  const originalFetch = globalThis.fetch;
570
569
  const providerConfig = { id: "custom", placement: "bonus" };
571
570
  const { calls, fetchStub } = createFetchStub({