blubblub-the-machine 0.0.0-stage → 0.1.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 +45 -2
- package/dist/capacitor.d.ts +23 -0
- package/dist/capacitor.js +6 -0
- package/dist/index.d.ts +88 -0
- package/dist/index.js +189 -0
- package/package.json +26 -4
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# blubblub-the-machine
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Machine's client for Blub Blub apps. Onboarding questions come first; cross-promo follows in
|
|
4
|
+
the same package. At the start of onboarding it asks The Machine for
|
|
5
|
+
up to three extra questions; the app shows them in its own screens and hands the answers back.
|
|
6
|
+
|
|
7
|
+
- **Onboarding never waits.** `start` resolves within 1.5 s, and any error, timeout or refusal is
|
|
8
|
+
"no questions". Nothing in the package throws.
|
|
9
|
+
- **Answers are never lost to a bad connection.** They are queued in storage and retried on every
|
|
10
|
+
`flush` for 7 days.
|
|
11
|
+
- **The app key identifies the app; it is not a secret.** It ships inside the app.
|
|
12
|
+
|
|
13
|
+
## Use (Capacitor)
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createOnboarding } from "blubblub-the-machine";
|
|
17
|
+
import { capacitorStorage } from "blubblub-the-machine/capacitor";
|
|
18
|
+
import { Preferences } from "@capacitor/preferences";
|
|
19
|
+
|
|
20
|
+
const machine = createOnboarding({
|
|
21
|
+
appKey: "<the app's key from The Machine>",
|
|
22
|
+
platform: "ios",
|
|
23
|
+
storage: capacitorStorage(Preferences),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// When the app starts and each time it comes back to the foreground:
|
|
27
|
+
void machine.flush();
|
|
28
|
+
|
|
29
|
+
// When onboarding begins:
|
|
30
|
+
const { sessionId, questions } = await machine.start({
|
|
31
|
+
locale: "en-US",
|
|
32
|
+
identifiers: { idfv, idfa, revenuecatAppUserId, posthogDistinctId, appUserId },
|
|
33
|
+
ownQuestions: ["babyBirthDate", "olderSiblings"], // the app's own questions, as it names their answers
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// Show each question in the app's screens; then, without waiting:
|
|
37
|
+
if (sessionId) void machine.answer(sessionId, [{ questionId: questions[0].id, value: "a" }, { questionId: questions[1].id, skipped: true }]);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- `idfv` is required; without it `start` returns no questions. Send `idfa` only when the user allowed
|
|
41
|
+
tracking, and `email` only when the app already has it.
|
|
42
|
+
- A question's `type` is `single` or `multi` (answer with option `value`s), `number`, `date`
|
|
43
|
+
(`YYYY-MM-DD`) or `text`. `text` and option labels are already in the requested locale.
|
|
44
|
+
- `onError` (optional) is called with every failure, for the app's own logging.
|
|
45
|
+
|
|
46
|
+
The API contract is `docs/standards/SDK_API.md` in The Machine's repository.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Storage } from "./index";
|
|
2
|
+
/**
|
|
3
|
+
* Capacitor glue. The plugin is passed in rather than imported, so the package has no native
|
|
4
|
+
* dependency and works with whichever Capacitor version the app ships:
|
|
5
|
+
*
|
|
6
|
+
* import { Preferences } from "@capacitor/preferences";
|
|
7
|
+
* createOnboarding({ appKey, platform: "ios", storage: capacitorStorage(Preferences) });
|
|
8
|
+
*
|
|
9
|
+
* Identifiers come from the app (Yummy Bites: its DeviceIdsBridge for the IDFV and, once tracking is
|
|
10
|
+
* allowed, the IDFA), since each app already reads them its own way.
|
|
11
|
+
*/
|
|
12
|
+
export interface PreferencesPlugin {
|
|
13
|
+
get(options: {
|
|
14
|
+
key: string;
|
|
15
|
+
}): Promise<{
|
|
16
|
+
value: string | null;
|
|
17
|
+
}>;
|
|
18
|
+
set(options: {
|
|
19
|
+
key: string;
|
|
20
|
+
value: string;
|
|
21
|
+
}): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
export declare function capacitorStorage(preferences: PreferencesPlugin): Storage;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Machine's onboarding SDK client: asks for up to three extra onboarding questions and sends the
|
|
3
|
+
* answers back (contract: docs/standards/SDK_API.md in the-machine2).
|
|
4
|
+
*
|
|
5
|
+
* Two promises hold for the app: `start` never throws and never takes longer than `timeoutMs`
|
|
6
|
+
* (any error, timeout or non-200 answer is "no questions"), and `answer` never throws either: answers
|
|
7
|
+
* are queued in `storage` and sent in the background, retried on the next `flush` while their
|
|
8
|
+
* session is open (7 days). An app calls `flush` when it starts and when it returns to the foreground.
|
|
9
|
+
*/
|
|
10
|
+
export declare const SDK_VERSION = "0.1.0";
|
|
11
|
+
export declare const DEFAULT_BASE_URL = "https://the-machine-cy38u.ondigitalocean.app";
|
|
12
|
+
export declare const START_TIMEOUT_MS = 1500;
|
|
13
|
+
/** How long the server accepts answers for a session; older queued answers are dropped. */
|
|
14
|
+
export declare const SESSION_MS: number;
|
|
15
|
+
export type Platform = "ios" | "android";
|
|
16
|
+
/** Identifiers as the app has them. The ad id only when the user allowed tracking. */
|
|
17
|
+
export interface Identifiers {
|
|
18
|
+
idfv?: string | null;
|
|
19
|
+
idfa?: string | null;
|
|
20
|
+
revenuecatAppUserId?: string | null;
|
|
21
|
+
posthogDistinctId?: string | null;
|
|
22
|
+
appUserId?: string | null;
|
|
23
|
+
email?: string | null;
|
|
24
|
+
}
|
|
25
|
+
export interface Attribution {
|
|
26
|
+
network?: string;
|
|
27
|
+
campaign?: string;
|
|
28
|
+
adset?: string;
|
|
29
|
+
creative?: string;
|
|
30
|
+
}
|
|
31
|
+
export interface StartInput {
|
|
32
|
+
locale: string;
|
|
33
|
+
identifiers: Identifiers;
|
|
34
|
+
/** The app's own questions, named as the app stores their answers (`babyBirthDate`, …). */
|
|
35
|
+
ownQuestions?: string[];
|
|
36
|
+
attribution?: Attribution;
|
|
37
|
+
}
|
|
38
|
+
export type QuestionType = "single" | "multi" | "number" | "date" | "text";
|
|
39
|
+
export interface Question {
|
|
40
|
+
id: string;
|
|
41
|
+
key: string;
|
|
42
|
+
type: QuestionType;
|
|
43
|
+
text: string;
|
|
44
|
+
options?: {
|
|
45
|
+
value: string;
|
|
46
|
+
label: string;
|
|
47
|
+
}[];
|
|
48
|
+
}
|
|
49
|
+
/** `sessionId` is null when there are no questions to ask (including every failure). */
|
|
50
|
+
export interface OnboardingSession {
|
|
51
|
+
sessionId: string | null;
|
|
52
|
+
questions: Question[];
|
|
53
|
+
}
|
|
54
|
+
/** A value: an option's value (`single`), several (`multi`), a number, a `YYYY-MM-DD` day or text. */
|
|
55
|
+
export type Answer = {
|
|
56
|
+
questionId: string;
|
|
57
|
+
value: string | number | string[];
|
|
58
|
+
} | {
|
|
59
|
+
questionId: string;
|
|
60
|
+
skipped: true;
|
|
61
|
+
};
|
|
62
|
+
/** Where queued answers survive an app restart. Capacitor: `capacitorStorage` from `/capacitor`. */
|
|
63
|
+
export interface Storage {
|
|
64
|
+
get(key: string): Promise<string | null>;
|
|
65
|
+
set(key: string, value: string): Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
export interface OnboardingOptions {
|
|
68
|
+
appKey: string;
|
|
69
|
+
platform: Platform;
|
|
70
|
+
baseUrl?: string;
|
|
71
|
+
timeoutMs?: number;
|
|
72
|
+
/** Without it answers are queued in memory only and lost when the app closes. */
|
|
73
|
+
storage?: Storage;
|
|
74
|
+
/** Told about failures, for the app's own logging; never needed for correctness. */
|
|
75
|
+
onError?: (where: "start" | "answers" | "storage", error: unknown) => void;
|
|
76
|
+
fetch?: typeof fetch;
|
|
77
|
+
now?: () => number;
|
|
78
|
+
}
|
|
79
|
+
export interface Onboarding {
|
|
80
|
+
start(input: StartInput): Promise<OnboardingSession>;
|
|
81
|
+
answer(sessionId: string, answers: Answer[]): Promise<void>;
|
|
82
|
+
flush(): Promise<void>;
|
|
83
|
+
}
|
|
84
|
+
/** Empty values and an all-zero ad id (tracking not allowed yet) are left out, as the server would. */
|
|
85
|
+
export declare function cleanIdentifiers(ids: Identifiers): Record<string, string>;
|
|
86
|
+
/** The questions of a 200 answer that the app can render; anything malformed is dropped, not thrown. */
|
|
87
|
+
export declare function readSession(body: unknown): OnboardingSession;
|
|
88
|
+
export declare function createOnboarding(options: OnboardingOptions): Onboarding;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Machine's onboarding SDK client: asks for up to three extra onboarding questions and sends the
|
|
3
|
+
* answers back (contract: docs/standards/SDK_API.md in the-machine2).
|
|
4
|
+
*
|
|
5
|
+
* Two promises hold for the app: `start` never throws and never takes longer than `timeoutMs`
|
|
6
|
+
* (any error, timeout or non-200 answer is "no questions"), and `answer` never throws either: answers
|
|
7
|
+
* are queued in `storage` and sent in the background, retried on the next `flush` while their
|
|
8
|
+
* session is open (7 days). An app calls `flush` when it starts and when it returns to the foreground.
|
|
9
|
+
*/
|
|
10
|
+
export const SDK_VERSION = "0.1.0";
|
|
11
|
+
export const DEFAULT_BASE_URL = "https://the-machine-cy38u.ondigitalocean.app";
|
|
12
|
+
export const START_TIMEOUT_MS = 1500;
|
|
13
|
+
/** How long the server accepts answers for a session; older queued answers are dropped. */
|
|
14
|
+
export const SESSION_MS = 7 * 24 * 3600000;
|
|
15
|
+
const ANSWERS_TIMEOUT_MS = 10000;
|
|
16
|
+
const QUEUE_KEY = "machine-onboarding:answers:v1";
|
|
17
|
+
const ZERO_UUID = "00000000-0000-0000-0000-000000000000";
|
|
18
|
+
const NO_QUESTIONS = { sessionId: null, questions: [] };
|
|
19
|
+
const TYPES = ["single", "multi", "number", "date", "text"];
|
|
20
|
+
function memoryStorage() {
|
|
21
|
+
const m = new Map();
|
|
22
|
+
return { get: async (k) => m.get(k) ?? null, set: async (k, v) => void m.set(k, v) };
|
|
23
|
+
}
|
|
24
|
+
/** Empty values and an all-zero ad id (tracking not allowed yet) are left out, as the server would. */
|
|
25
|
+
export function cleanIdentifiers(ids) {
|
|
26
|
+
const out = {};
|
|
27
|
+
for (const [k, v] of Object.entries(ids)) {
|
|
28
|
+
const s = typeof v === "string" ? v.trim() : "";
|
|
29
|
+
if (!s || (k === "idfa" && s === ZERO_UUID))
|
|
30
|
+
continue;
|
|
31
|
+
out[k] = s;
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
/** The questions of a 200 answer that the app can render; anything malformed is dropped, not thrown. */
|
|
36
|
+
export function readSession(body) {
|
|
37
|
+
if (!body || typeof body !== "object")
|
|
38
|
+
return NO_QUESTIONS;
|
|
39
|
+
const { sessionId, questions } = body;
|
|
40
|
+
if (typeof sessionId !== "string" || !Array.isArray(questions))
|
|
41
|
+
return NO_QUESTIONS;
|
|
42
|
+
const valid = questions.filter((q) => {
|
|
43
|
+
if (!q || typeof q !== "object")
|
|
44
|
+
return false;
|
|
45
|
+
const { id, key, type, text, options } = q;
|
|
46
|
+
if (typeof id !== "string" || typeof key !== "string" || typeof text !== "string" || typeof type !== "string" || !TYPES.includes(type))
|
|
47
|
+
return false;
|
|
48
|
+
const choice = type === "single" || type === "multi";
|
|
49
|
+
if (!choice)
|
|
50
|
+
return options === undefined;
|
|
51
|
+
return Array.isArray(options) && options.length > 0 && options.every((o) => o && typeof o.value === "string" && typeof o.label === "string");
|
|
52
|
+
});
|
|
53
|
+
return valid.length ? { sessionId, questions: valid } : NO_QUESTIONS;
|
|
54
|
+
}
|
|
55
|
+
export function createOnboarding(options) {
|
|
56
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
57
|
+
const timeoutMs = options.timeoutMs ?? START_TIMEOUT_MS;
|
|
58
|
+
const storage = options.storage ?? memoryStorage();
|
|
59
|
+
const doFetch = options.fetch ?? ((...a) => fetch(...a));
|
|
60
|
+
const now = options.now ?? Date.now;
|
|
61
|
+
const report = (where, e) => {
|
|
62
|
+
try {
|
|
63
|
+
options.onError?.(where, e);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// the app's logger must not break onboarding
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
/** A POST that gives up after `ms`, also where the fetch ignores the abort signal. */
|
|
70
|
+
async function post(path, body, ms) {
|
|
71
|
+
const abort = typeof AbortController === "function" ? new AbortController() : null;
|
|
72
|
+
let timer;
|
|
73
|
+
const timeout = new Promise((_, reject) => {
|
|
74
|
+
timer = setTimeout(() => {
|
|
75
|
+
abort?.abort();
|
|
76
|
+
reject(new Error(`timed out after ${ms} ms`));
|
|
77
|
+
}, ms);
|
|
78
|
+
});
|
|
79
|
+
try {
|
|
80
|
+
return await Promise.race([
|
|
81
|
+
doFetch(`${baseUrl}${path}`, {
|
|
82
|
+
method: "POST",
|
|
83
|
+
headers: { "content-type": "application/json", "x-machine-app-key": options.appKey },
|
|
84
|
+
body: JSON.stringify(body),
|
|
85
|
+
signal: abort?.signal,
|
|
86
|
+
}),
|
|
87
|
+
timeout,
|
|
88
|
+
]);
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
// Every read-modify-write of the queue runs one after another, so a flush and an answer never
|
|
95
|
+
// overwrite each other's change.
|
|
96
|
+
let lock = Promise.resolve();
|
|
97
|
+
function locked(fn) {
|
|
98
|
+
const run = lock.then(fn, fn);
|
|
99
|
+
lock = run.catch(() => undefined);
|
|
100
|
+
return run;
|
|
101
|
+
}
|
|
102
|
+
async function readQueue() {
|
|
103
|
+
try {
|
|
104
|
+
const raw = await storage.get(QUEUE_KEY);
|
|
105
|
+
const q = raw ? JSON.parse(raw) : [];
|
|
106
|
+
return Array.isArray(q) ? q : [];
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
report("storage", e);
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async function writeQueue(q) {
|
|
114
|
+
try {
|
|
115
|
+
await storage.set(QUEUE_KEY, JSON.stringify(q));
|
|
116
|
+
}
|
|
117
|
+
catch (e) {
|
|
118
|
+
report("storage", e);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
async function start(input) {
|
|
122
|
+
try {
|
|
123
|
+
const identifiers = cleanIdentifiers(input.identifiers);
|
|
124
|
+
if (!identifiers["idfv"])
|
|
125
|
+
return NO_QUESTIONS; // the contract needs the vendor id (iOS only for now)
|
|
126
|
+
const res = await post("/api/sdk/v1/onboarding/start", { sdkVersion: SDK_VERSION, platform: options.platform, locale: input.locale, identifiers, ownQuestions: input.ownQuestions ?? [], attribution: input.attribution }, timeoutMs);
|
|
127
|
+
if (res.status !== 200) {
|
|
128
|
+
report("start", new Error(`HTTP ${res.status}`));
|
|
129
|
+
return NO_QUESTIONS;
|
|
130
|
+
}
|
|
131
|
+
return readSession(await res.json());
|
|
132
|
+
}
|
|
133
|
+
catch (e) {
|
|
134
|
+
report("start", e);
|
|
135
|
+
return NO_QUESTIONS;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
async function answer(sessionId, answers) {
|
|
139
|
+
if (!sessionId || !answers.length)
|
|
140
|
+
return;
|
|
141
|
+
await locked(async () => {
|
|
142
|
+
const q = await readQueue();
|
|
143
|
+
q.push({ sessionId, answers, queuedAt: now() });
|
|
144
|
+
await writeQueue(q);
|
|
145
|
+
});
|
|
146
|
+
await flush();
|
|
147
|
+
}
|
|
148
|
+
async function send() {
|
|
149
|
+
const keep = [];
|
|
150
|
+
for (const item of await readQueue()) {
|
|
151
|
+
if (now() - item.queuedAt > SESSION_MS)
|
|
152
|
+
continue; // the session is closed on the server
|
|
153
|
+
try {
|
|
154
|
+
const res = await post("/api/sdk/v1/onboarding/answers", { sessionId: item.sessionId, answers: item.answers }, ANSWERS_TIMEOUT_MS);
|
|
155
|
+
if (res.status === 200)
|
|
156
|
+
continue;
|
|
157
|
+
report("answers", new Error(`HTTP ${res.status}`));
|
|
158
|
+
// 400, 401 and 404 will not change on a retry; 429 and 5xx may.
|
|
159
|
+
if (res.status === 429 || res.status >= 500)
|
|
160
|
+
keep.push(item);
|
|
161
|
+
}
|
|
162
|
+
catch (e) {
|
|
163
|
+
report("answers", e);
|
|
164
|
+
keep.push(item);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
await writeQueue(keep);
|
|
168
|
+
}
|
|
169
|
+
// One flush at a time; a flush asked for while one runs makes it go round once more, so answers
|
|
170
|
+
// queued meanwhile are not left until the next app start.
|
|
171
|
+
let flushing = null;
|
|
172
|
+
let again = false;
|
|
173
|
+
function flush() {
|
|
174
|
+
if (flushing) {
|
|
175
|
+
again = true;
|
|
176
|
+
return flushing;
|
|
177
|
+
}
|
|
178
|
+
flushing = (async () => {
|
|
179
|
+
do {
|
|
180
|
+
again = false;
|
|
181
|
+
await locked(send);
|
|
182
|
+
} while (again);
|
|
183
|
+
})().finally(() => {
|
|
184
|
+
flushing = null;
|
|
185
|
+
});
|
|
186
|
+
return flushing;
|
|
187
|
+
}
|
|
188
|
+
return { start, answer, flush };
|
|
189
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "blubblub-the-machine",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The Machine's client for Blub Blub apps: extra onboarding questions now, cross-promo next.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./capacitor": {
|
|
14
|
+
"types": "./dist/capacitor.d.ts",
|
|
15
|
+
"import": "./dist/capacitor.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "tsc -p tsconfig.json",
|
|
25
|
+
"prepublishOnly": "npm run build"
|
|
26
|
+
},
|
|
27
|
+
"license": "UNLICENSED"
|
|
28
|
+
}
|