create-expo-updates-server 0.1.5 → 0.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.
- package/dist/template/.dockerignore +16 -0
- package/dist/template/README.md +51 -660
- package/dist/template/app/api/admin/device-targets/route.test.ts +43 -0
- package/dist/template/app/api/admin/device-targets/route.ts +91 -0
- package/dist/template/app/api/admin/devices/route.test.ts +41 -0
- package/dist/template/app/api/admin/devices/route.ts +15 -0
- package/dist/template/app/api/admin/updates/[encodedKey]/audience/route.ts +75 -0
- package/dist/template/app/api/device-heartbeat/route.ts +2 -0
- package/dist/template/app/globals.css +114 -15
- package/dist/template/app/layout.tsx +12 -4
- package/dist/template/app/login/page.tsx +22 -18
- package/dist/template/app/updates/[encodedKey]/page.tsx +112 -88
- package/dist/template/app/updates/devices/page.tsx +264 -0
- package/dist/template/app/updates/embedded/page.tsx +102 -68
- package/dist/template/app/updates/emergency-redirects/page.tsx +144 -111
- package/dist/template/app/updates/layout.tsx +6 -1
- package/dist/template/app/updates/page.tsx +262 -212
- package/dist/template/components/admin/admin-shell.tsx +196 -0
- package/dist/template/components/admin/language-switcher.tsx +25 -0
- package/dist/template/components/admin/theme-provider.tsx +15 -0
- package/dist/template/components/ui/alert.tsx +65 -0
- package/dist/template/components/ui/badge.tsx +47 -0
- package/dist/template/components/ui/button.tsx +63 -0
- package/dist/template/components/ui/card.tsx +91 -0
- package/dist/template/components/ui/chart.tsx +373 -0
- package/dist/template/components/ui/checkbox.tsx +31 -0
- package/dist/template/components/ui/dialog.tsx +158 -0
- package/dist/template/components/ui/dropdown-menu.tsx +256 -0
- package/dist/template/components/ui/input.tsx +20 -0
- package/dist/template/components/ui/label.tsx +23 -0
- package/dist/template/components/ui/native-select.tsx +61 -0
- package/dist/template/components/ui/popover.tsx +88 -0
- package/dist/template/components/ui/scroll-area.tsx +57 -0
- package/dist/template/components/ui/select.tsx +189 -0
- package/dist/template/components/ui/separator.tsx +27 -0
- package/dist/template/components/ui/sheet.tsx +142 -0
- package/dist/template/components/ui/sidebar.tsx +736 -0
- package/dist/template/components/ui/skeleton.tsx +13 -0
- package/dist/template/components/ui/switch.tsx +34 -0
- package/dist/template/components/ui/table.tsx +115 -0
- package/dist/template/components/ui/tabs.tsx +90 -0
- package/dist/template/components/ui/textarea.tsx +17 -0
- package/dist/template/components/ui/tooltip.tsx +56 -0
- package/dist/template/components.json +22 -0
- package/dist/template/docs/admin-ui.md +35 -0
- package/dist/template/docs/device-targeting.md +129 -0
- package/dist/template/docs/doctor.md +137 -0
- package/dist/template/docs/expo-app-setup.md +174 -47
- package/dist/template/docs/getting-started.md +105 -146
- package/dist/template/docs/getting-started.ru.md +106 -191
- package/dist/template/docs/index.md +14 -33
- package/dist/template/docs/installation-telemetry.md +233 -0
- package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +89 -0
- package/dist/template/docs/migrations/2026-10-19-device-heartbeat.sql +131 -0
- package/dist/template/docs/migrations/2026-10-22-device-analytics.sql +264 -0
- package/dist/template/docs/migrations/2026-10-22-device-targeting-activation.sql +108 -0
- package/dist/template/docs/migrations/2026-10-22-device-targeting.sql +130 -0
- package/dist/template/docs/migrations/2026-10-22-device-version-metadata.sql +154 -0
- package/dist/template/docs/migrations/schema.sql +868 -6
- package/dist/template/docs/npm-installer.md +15 -30
- package/dist/template/docs/operations-guide.md +87 -0
- package/dist/template/docs/ota-client-lifecycle.md +263 -0
- package/dist/template/docs/ota-update-policy.md +36 -2
- package/dist/template/docs/supabase-setup.md +4 -0
- package/dist/template/hooks/use-mobile.ts +21 -0
- package/dist/template/lib/utils.ts +6 -0
- package/dist/template/package-lock.json +2325 -101
- package/dist/template/package.json +13 -3
- package/dist/template/scripts/configure-expo-app.mjs +11 -15
- package/dist/template/scripts/doctor.mjs +51 -0
- package/dist/template/scripts/ensure-test-bucket.mjs +21 -0
- package/dist/template/scripts/lib/device-identity.test.ts +29 -0
- package/dist/template/scripts/lib/doctor-probes.mjs +139 -0
- package/dist/template/scripts/lib/doctor.mjs +208 -0
- package/dist/template/scripts/lib/doctor.test.mjs +262 -0
- package/dist/template/scripts/lib/expo-app-configurator.mjs +14 -9
- package/dist/template/scripts/lib/expo-app-configurator.test.ts +3 -2
- package/dist/template/scripts/lib/ota-client-configurator.mjs +69 -0
- package/dist/template/scripts/lib/ota-client-configurator.test.ts +88 -0
- package/dist/template/scripts/lib/ota-client.test.ts +55 -0
- package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +173 -0
- package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +123 -0
- package/dist/template/scripts/lib/ota-update-controller.test.ts +231 -0
- package/dist/template/scripts/tests/device-analytics-migrations.mjs +80 -0
- package/dist/template/scripts/tests/device-analytics.mjs +126 -0
- package/dist/template/scripts/tests/device-heartbeat.mjs +86 -0
- package/dist/template/scripts/tests/device-targeting-activation.mjs +111 -0
- package/dist/template/scripts/tests/device-targeting.mjs +39 -0
- package/dist/template/scripts/tests/device-version-metadata.mjs +31 -0
- package/dist/template/scripts/tests/manifest-identity-concurrency.mjs +106 -0
- package/dist/template/scripts/tests/manifest-identity.sql +204 -0
- package/dist/template/src/client/admin-types.ts +1 -0
- package/dist/template/src/client/devices/analytics.tsx +429 -0
- package/dist/template/src/client/devices/device-name.tsx +82 -0
- package/dist/template/src/client/devices/registry.tsx +399 -0
- package/dist/template/src/client/devices/use-devices-report.ts +108 -0
- package/dist/template/src/client/devices/version-adoption-chart.tsx +269 -0
- package/dist/template/src/client/devices/version-groups.test.ts +57 -0
- package/dist/template/src/client/devices/version-groups.ts +101 -0
- package/dist/template/src/client/distribution-control.tsx +135 -81
- package/dist/template/src/client/guard-action-combobox.tsx +13 -24
- package/dist/template/src/client/i18n/en.json +286 -0
- package/dist/template/src/client/i18n/messages.test.ts +42 -0
- package/dist/template/src/client/i18n/messages.ts +31 -0
- package/dist/template/src/client/i18n/provider.tsx +55 -0
- package/dist/template/src/client/i18n/use-formatters.ts +38 -0
- package/dist/template/src/client/logout-button.tsx +3 -1
- package/dist/template/src/client/update-audience-editor.tsx +285 -0
- package/dist/template/src/client/update-policy-editor.tsx +53 -41
- package/dist/template/src/server/controllers/manifest.test.ts +250 -7
- package/dist/template/src/server/controllers/manifest.ts +39 -31
- package/dist/template/src/server/devices/audience.test.ts +48 -0
- package/dist/template/src/server/devices/audience.ts +86 -0
- package/dist/template/src/server/devices/heartbeat.test.ts +39 -0
- package/dist/template/src/server/devices/heartbeat.ts +75 -0
- package/dist/template/src/server/devices/report-types.ts +114 -0
- package/dist/template/src/server/devices/report.test.ts +29 -0
- package/dist/template/src/server/devices/report.ts +27 -0
- package/dist/template/src/server/lib/admin-audience-activation.test.ts +94 -0
- package/dist/template/src/server/lib/admin-updates.ts +32 -168
- package/dist/template/src/server/lib/distribution-control.test.ts +23 -2
- package/dist/template/src/server/lib/distribution-control.ts +13 -4
- package/dist/template/src/server/lib/supabase.js +10 -10
- package/dist/template/src/server/lib/supabase.test.ts +11 -0
- package/dist/template/src/server/manifest/manifest-identity.test.ts +30 -0
- package/dist/template/src/server/manifest/manifest-identity.ts +24 -0
- package/dist/template/src/server/manifest/manifest-repository.ts +31 -102
- package/dist/template/src/server/manifest/manifest-response.ts +1 -1
- package/dist/template/templates/expo-app/ota-client/README.md +59 -0
- package/dist/template/templates/expo-app/ota-client/controller.js +60 -0
- package/dist/template/templates/expo-app/ota-client/device-identity.js +26 -0
- package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +52 -0
- package/dist/template/templates/expo-app/ota-client/index.d.ts +47 -0
- package/dist/template/templates/expo-app/ota-client/index.js +3 -0
- package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +48 -0
- package/dist/template/templates/expo-app/ota-client/model/update-controller.js +182 -0
- package/dist/template/templates/expo-app/ota-client/runtime.js +112 -0
- package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +56 -0
- package/dist/template-manifest.json +582 -77
- package/lib/cli.mjs +4 -6
- package/package.json +1 -1
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
|
|
5
|
+
const extensions = ['tsx', 'jsx', 'ts', 'js'];
|
|
6
|
+
const suffixes = ['', '.android', '.ios', '.native', '.web'];
|
|
7
|
+
|
|
8
|
+
function unwrap(node) {
|
|
9
|
+
while (node && (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node))) node = node.expression;
|
|
10
|
+
return node;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function componentFor(source) {
|
|
14
|
+
const exported = source.statements.find((node) => node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword));
|
|
15
|
+
if (exported) return exported;
|
|
16
|
+
const assignment = source.statements.find((node) => ts.isExportAssignment(node) && !node.isExportEquals);
|
|
17
|
+
let component = unwrap(assignment?.expression);
|
|
18
|
+
if (component && ts.isIdentifier(component)) {
|
|
19
|
+
const name = component.text;
|
|
20
|
+
component = source.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === name)
|
|
21
|
+
|| source.statements.flatMap((node) => ts.isVariableStatement(node) ? [...node.declarationList.declarations] : [])
|
|
22
|
+
.find((node) => ts.isIdentifier(node.name) && node.name.text === name)?.initializer;
|
|
23
|
+
}
|
|
24
|
+
return unwrap(component);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isDirective(node) {
|
|
28
|
+
return ts.isExpressionStatement(node) && ts.isStringLiteral(node.expression);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Parse for insertion locations only: never reprint or reformat application code. */
|
|
32
|
+
export function patchOtaRootHook(text, filename, appRoot) {
|
|
33
|
+
const source = ts.createSourceFile(filename, text, ts.ScriptTarget.Latest, true);
|
|
34
|
+
const fail = (reason) => { throw new Error(`Cannot automatically connect useOtaUpdates in ${filename}: ${reason}. Export a synchronous function component directly or through a local identifier, then rerun configure-app.`); };
|
|
35
|
+
if (source.parseDiagnostics.length) fail('the root file has syntax errors');
|
|
36
|
+
const component = componentFor(source);
|
|
37
|
+
if (!component || !(ts.isFunctionDeclaration(component) || ts.isFunctionExpression(component) || ts.isArrowFunction(component)) || !component.body) fail('unsupported default root component');
|
|
38
|
+
if (component.asteriskToken || component.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)) fail('async/generator components cannot call React hooks');
|
|
39
|
+
|
|
40
|
+
const clientPath = path.join(appRoot, 'ota-client');
|
|
41
|
+
const imports = source.statements.filter(ts.isImportDeclaration);
|
|
42
|
+
const identifiers = new Set();
|
|
43
|
+
const gather = (node) => { if (ts.isIdentifier(node)) identifiers.add(node.text); ts.forEachChild(node, gather); };
|
|
44
|
+
gather(source);
|
|
45
|
+
const unique = (name) => {
|
|
46
|
+
let candidate = name;
|
|
47
|
+
for (let index = 2; identifiers.has(candidate); index += 1) candidate = `${name}${index}`;
|
|
48
|
+
identifiers.add(candidate);
|
|
49
|
+
return candidate;
|
|
50
|
+
};
|
|
51
|
+
const clientImports = imports.filter((node) => ts.isStringLiteral(node.moduleSpecifier)
|
|
52
|
+
&& node.moduleSpecifier.text.startsWith('.')
|
|
53
|
+
&& [clientPath, `${clientPath}/index`, `${clientPath}/index.js`].includes(path.resolve(path.dirname(filename), node.moduleSpecifier.text)));
|
|
54
|
+
const binding = (nodes, name) => nodes.flatMap((node) => !node.importClause?.isTypeOnly && node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings)
|
|
55
|
+
? [...node.importClause.namedBindings.elements] : [])
|
|
56
|
+
.find((element) => !element.isTypeOnly && (element.propertyName || element.name).text === name)?.name.text;
|
|
57
|
+
if (imports.some((node) => !clientImports.includes(node) && binding([node], 'useOtaUpdates'))) {
|
|
58
|
+
fail('an existing useOtaUpdates import cannot be resolved to the generated ota-client; use a relative import to ota-client so its options can be preserved');
|
|
59
|
+
}
|
|
60
|
+
const importedHook = binding(clientImports, 'useOtaUpdates');
|
|
61
|
+
const importedGate = binding(clientImports, 'OtaUpdateGate');
|
|
62
|
+
const importedCreate = binding(imports.filter((node) => node.moduleSpecifier.text === 'react'), 'createElement');
|
|
63
|
+
const importedNames = new Set([importedHook, importedGate, importedCreate].filter(Boolean));
|
|
64
|
+
const checkBinding = (name) => {
|
|
65
|
+
if (!name) return;
|
|
66
|
+
if (ts.isIdentifier(name) && importedNames.has(name.text)) fail(`the imported OTA/React binding ${name.text} is shadowed in the component`);
|
|
67
|
+
if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) for (const element of name.elements) {
|
|
68
|
+
if (ts.isBindingElement(element)) checkBinding(element.name);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
for (const parameter of component.parameters) checkBinding(parameter.name);
|
|
72
|
+
const hookName = importedHook || unique('useOtaUpdates');
|
|
73
|
+
const gateName = importedGate || unique('OtaUpdateGate');
|
|
74
|
+
const createName = importedCreate || unique('createElement');
|
|
75
|
+
const newline = text.includes('\r\n') ? '\r\n' : '\n';
|
|
76
|
+
const edits = [];
|
|
77
|
+
let controllerName;
|
|
78
|
+
let existingHookCall;
|
|
79
|
+
const returns = [];
|
|
80
|
+
const inspect = (node) => {
|
|
81
|
+
if (ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) checkBinding(node.name);
|
|
82
|
+
if (ts.isFunctionLike(node)) return;
|
|
83
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === importedHook) {
|
|
84
|
+
if (existingHookCall) fail('multiple update hooks in the root component');
|
|
85
|
+
existingHookCall = node;
|
|
86
|
+
}
|
|
87
|
+
if (ts.isReturnStatement(node)) returns.push(node);
|
|
88
|
+
ts.forEachChild(node, inspect);
|
|
89
|
+
};
|
|
90
|
+
inspect(component.body);
|
|
91
|
+
if (existingHookCall) {
|
|
92
|
+
if (returns.some((statement) => statement.pos < existingHookCall.pos)) fail('the existing hook appears after an early return');
|
|
93
|
+
const owner = existingHookCall.parent;
|
|
94
|
+
if (ts.isVariableDeclaration(owner) && ts.isIdentifier(owner.name) && owner.parent.parent.parent === component.body) {
|
|
95
|
+
controllerName = owner.name.text;
|
|
96
|
+
} else if (ts.isExpressionStatement(owner) && owner.parent === component.body) {
|
|
97
|
+
controllerName = unique('otaUpdates');
|
|
98
|
+
edits.push({ start: owner.getStart(source), end: owner.getStart(source), content: `const ${controllerName} = ` });
|
|
99
|
+
} else fail('the existing update hook must be called unconditionally at the top of the root component');
|
|
100
|
+
} else {
|
|
101
|
+
controllerName = unique('otaUpdates');
|
|
102
|
+
}
|
|
103
|
+
const hook = `const ${controllerName} = ${hookName}({ autoCheck: true, autoUpdate: false, autoReload: false });`;
|
|
104
|
+
const wrap = (expression) => {
|
|
105
|
+
const unwrapped = unwrap(expression);
|
|
106
|
+
if (unwrapped && ts.isCallExpression(unwrapped) && ts.isIdentifier(unwrapped.expression) && unwrapped.expression.text === createName
|
|
107
|
+
&& unwrapped.arguments[0] && ts.isIdentifier(unwrapped.arguments[0]) && unwrapped.arguments[0].text === gateName) return;
|
|
108
|
+
if (unwrapped && (ts.isJsxElement(unwrapped) || ts.isJsxSelfClosingElement(unwrapped))
|
|
109
|
+
&& (unwrapped.openingElement?.tagName || unwrapped.tagName)?.getText(source) === gateName) return;
|
|
110
|
+
if (!expression) return;
|
|
111
|
+
edits.push({ start: expression.getStart(source), end: expression.getStart(source), content: `${createName}(${gateName}, { controller: ${controllerName} }, ` });
|
|
112
|
+
edits.push({ start: expression.end, end: expression.end, content: ')' });
|
|
113
|
+
};
|
|
114
|
+
if (ts.isBlock(component.body)) {
|
|
115
|
+
if (!existingHookCall) {
|
|
116
|
+
let at = component.body.getStart(source) + 1;
|
|
117
|
+
for (const statement of component.body.statements) {
|
|
118
|
+
if (!isDirective(statement)) break;
|
|
119
|
+
at = statement.end;
|
|
120
|
+
}
|
|
121
|
+
edits.push({ start: at, end: at, content: `${newline} ${hook}${newline}` });
|
|
122
|
+
}
|
|
123
|
+
for (const statement of returns) {
|
|
124
|
+
if (statement.expression) wrap(statement.expression);
|
|
125
|
+
else edits.push({ start: statement.getStart(source), end: statement.end, content: `return ${createName}(${gateName}, { controller: ${controllerName} }, null);` });
|
|
126
|
+
}
|
|
127
|
+
if (!returns.length) fail('the root component has no return statement');
|
|
128
|
+
} else {
|
|
129
|
+
edits.push({ start: component.body.getStart(source), end: component.body.end, content: `{${newline} ${hook}${newline} return ${createName}(${gateName}, { controller: ${controllerName} }, (${component.body.getText(source)}));${newline}}` });
|
|
130
|
+
}
|
|
131
|
+
const newImports = [];
|
|
132
|
+
let relative = path.relative(path.dirname(filename), clientPath).split(path.sep).join('/');
|
|
133
|
+
if (!relative.startsWith('.')) relative = `./${relative}`;
|
|
134
|
+
const specifier = (name, alias) => name === alias ? name : `${name} as ${alias}`;
|
|
135
|
+
const missingClientBindings = [];
|
|
136
|
+
if (!importedHook) missingClientBindings.push(specifier('useOtaUpdates', hookName));
|
|
137
|
+
if (!importedGate) missingClientBindings.push(specifier('OtaUpdateGate', gateName));
|
|
138
|
+
if (missingClientBindings.length) newImports.push(`import { ${missingClientBindings.join(', ')} } from '${relative}';`);
|
|
139
|
+
if (!importedCreate) newImports.push(`import { ${specifier('createElement', createName)} } from 'react';`);
|
|
140
|
+
if (newImports.length) {
|
|
141
|
+
let at = imports.at(-1)?.end ?? source.statements[0]?.getStart(source) ?? text.length;
|
|
142
|
+
if (!imports.length) for (const statement of source.statements) {
|
|
143
|
+
if (!isDirective(statement)) break;
|
|
144
|
+
at = statement.end;
|
|
145
|
+
}
|
|
146
|
+
edits.push({ start: at, end: at, content: `${newline}${newImports.join(newline)}${newline}` });
|
|
147
|
+
}
|
|
148
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) text = text.slice(0, edit.start) + edit.content + text.slice(edit.end);
|
|
149
|
+
return text;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function planOtaRootHook({ appRoot, originalEntry }) {
|
|
153
|
+
const candidates = (base) => suffixes.flatMap((suffix) => extensions.map((extension) => `${base}${suffix}.${extension}`)).filter((name) => fs.existsSync(path.join(appRoot, name)));
|
|
154
|
+
const router = originalEntry === 'expo-router/entry';
|
|
155
|
+
let roots = [];
|
|
156
|
+
if (router) {
|
|
157
|
+
roots = candidates(fs.existsSync(path.join(appRoot, 'src/app')) ? 'src/app/_layout' : 'app/_layout');
|
|
158
|
+
} else if (['__platform_default__', '__app_fallback__', 'node_modules/expo/AppEntry.js', 'expo/AppEntry', 'expo/AppEntry.js'].includes(originalEntry.replace(/^\.\//, ''))) {
|
|
159
|
+
// A custom index may register another root; never guess in that case.
|
|
160
|
+
if (!candidates('index').length) roots = candidates('App');
|
|
161
|
+
}
|
|
162
|
+
if (!roots.length) return {
|
|
163
|
+
files: [],
|
|
164
|
+
warnings: ['The OTA identity/telemetry bootstrap is configured, but no safely identifiable root component was found. Call useOtaUpdates from ota-client in your main layout to enable update orchestration.'],
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
files: roots.map((name) => {
|
|
168
|
+
const filename = path.join(appRoot, name);
|
|
169
|
+
return [name, patchOtaRootHook(fs.readFileSync(filename, 'utf8'), filename, appRoot)];
|
|
170
|
+
}),
|
|
171
|
+
warnings: [],
|
|
172
|
+
};
|
|
173
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import ts from 'typescript';
|
|
5
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
6
|
+
import { patchOtaRootHook, planOtaRootHook } from './ota-root-hook-patcher.mjs';
|
|
7
|
+
|
|
8
|
+
const roots: string[] = [];
|
|
9
|
+
afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
|
|
10
|
+
const root = '/example';
|
|
11
|
+
const filename = '/example/src/app/_layout.tsx';
|
|
12
|
+
function patch(source: string, file = filename) { return patchOtaRootHook(source, file, root); }
|
|
13
|
+
function assertValid(source: string, file = filename) {
|
|
14
|
+
const result = ts.transpileModule(source, { fileName: file, reportDiagnostics: true, compilerOptions: { jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } });
|
|
15
|
+
expect(result.diagnostics).toEqual([]);
|
|
16
|
+
}
|
|
17
|
+
describe('root update hook patch', () => {
|
|
18
|
+
it('preserves directives, comments, custom options and conditional returns on rerun', () => {
|
|
19
|
+
const source = `'use client';\n// Header\nimport { Stack } from 'expo-router';\n// Component\nexport default function Layout() {\n // Keep this check.\n if (loading) return null;\n return <Stack />;\n}\n`;
|
|
20
|
+
const result = patch(source);
|
|
21
|
+
expect(result.startsWith("'use client';\n// Header\n")).toBe(true);
|
|
22
|
+
expect(result).toContain('// Component\nexport default function Layout()');
|
|
23
|
+
expect(result).toContain("from '../../ota-client'");
|
|
24
|
+
expect(result).toContain('const otaUpdates = useOtaUpdates({ autoCheck: true, autoUpdate: false, autoReload: false });');
|
|
25
|
+
expect(result).toContain('if (loading) return createElement(OtaUpdateGate, { controller: otaUpdates }, null)');
|
|
26
|
+
expect(result).toContain('return createElement(OtaUpdateGate, { controller: otaUpdates }, <Stack />)');
|
|
27
|
+
expect(result).toContain('// Keep this check.');
|
|
28
|
+
const customized = result.replace('autoCheck: true', 'autoCheck: false');
|
|
29
|
+
expect(patch(customized)).toBe(customized);
|
|
30
|
+
assertValid(result);
|
|
31
|
+
});
|
|
32
|
+
it.each([
|
|
33
|
+
'const Layout = () => (<Stack />); export default Layout;',
|
|
34
|
+
'export default () => <Stack />;',
|
|
35
|
+
'export default function () { return <Stack />; }',
|
|
36
|
+
'function Layout() { return <Stack />; } export default Layout;',
|
|
37
|
+
'const Layout = function() { return <Stack />; }; export default Layout;',
|
|
38
|
+
'const Layout = (() => <Stack />) satisfies ComponentType; export default Layout;',
|
|
39
|
+
])('supports a synchronous root shape: %s', (source) => {
|
|
40
|
+
const result = patch(source);
|
|
41
|
+
expect(result).toContain('useOtaUpdates({');
|
|
42
|
+
expect(result).toContain('createElement(OtaUpdateGate,');
|
|
43
|
+
expect(patch(result)).toBe(result);
|
|
44
|
+
assertValid(result);
|
|
45
|
+
});
|
|
46
|
+
it('leaves nested render callbacks alone and preserves all root early returns', () => {
|
|
47
|
+
const result = patch('export default function Layout() { const render = () => { return <Text />; }; if (ready) return <Stack render={render} />; return null; }');
|
|
48
|
+
expect(result).toContain('const render = () => { return <Text />; }');
|
|
49
|
+
expect(result.match(/createElement\(OtaUpdateGate/g)).toHaveLength(2);
|
|
50
|
+
assertValid(result);
|
|
51
|
+
});
|
|
52
|
+
it('uses alias imports and keeps the existing hook configuration', () => {
|
|
53
|
+
const result = patch("import { useOtaUpdates as useUpdates, OtaUpdateGate as Gate } from '../../ota-client';\nimport { createElement as el } from 'react';\nexport default function Root() { const updates = useUpdates({ autoCheck: false, autoReload: true }); return <Stack/>; }");
|
|
54
|
+
expect(result.match(/useUpdates\(/g)).toHaveLength(1);
|
|
55
|
+
expect(result).toContain('const updates = useUpdates({ autoCheck: false, autoReload: true });');
|
|
56
|
+
expect(result).toContain('return el(Gate, { controller: updates }, <Stack/>)');
|
|
57
|
+
expect(patch(result)).toBe(result);
|
|
58
|
+
assertValid(result);
|
|
59
|
+
});
|
|
60
|
+
it('upgrades an existing unassigned top-level hook to provide the gate controller', () => {
|
|
61
|
+
const result = patch("import { useOtaUpdates } from '../../ota-client';\nexport default function Root() { useOtaUpdates({ autoCheck: false }); return null; }");
|
|
62
|
+
expect(result).toContain('const otaUpdates = useOtaUpdates({ autoCheck: false });');
|
|
63
|
+
expect(result).toContain('controller: otaUpdates');
|
|
64
|
+
expect(patch(result)).toBe(result);
|
|
65
|
+
});
|
|
66
|
+
it('rejects an unresolved import alias instead of installing a competing default hook', () => {
|
|
67
|
+
const source = "import { useOtaUpdates as useUpdates } from '@/ota-client';\nexport default function Root() { const updates = useUpdates({ autoCheck: false }); return null; }";
|
|
68
|
+
expect(() => patch(source)).toThrow('use a relative import to ota-client');
|
|
69
|
+
});
|
|
70
|
+
it('avoids collisions with local names and supports non-JSX TS App roots', () => {
|
|
71
|
+
const result = patch('const useOtaUpdates = 1; const OtaUpdateGate = 2; const createElement = 3; const otaUpdates = 4; export default function App() { return null; }', '/example/App.ts');
|
|
72
|
+
expect(result).toContain("import { useOtaUpdates as useOtaUpdates2, OtaUpdateGate as OtaUpdateGate2 } from './ota-client';");
|
|
73
|
+
expect(result).toContain('const otaUpdates2 = useOtaUpdates2(');
|
|
74
|
+
expect(result).toContain('return createElement2(OtaUpdateGate2,');
|
|
75
|
+
assertValid(result, '/example/App.ts');
|
|
76
|
+
});
|
|
77
|
+
it.each([
|
|
78
|
+
'export default memo(() => <Stack/>);',
|
|
79
|
+
'export default class Root { render() { return null; } }',
|
|
80
|
+
'export default async function Root() { return null; }',
|
|
81
|
+
'export default function* Root() { return null; }',
|
|
82
|
+
"export { default } from './Root';",
|
|
83
|
+
'export default function Root( { return null;',
|
|
84
|
+
"import { useOtaUpdates } from '../../ota-client'; export default function Root() { if (ready) useOtaUpdates(); return null; }",
|
|
85
|
+
"import { useOtaUpdates } from '../../ota-client'; export default function Root() { if (loading) return null; const updates = useOtaUpdates(); return null; }",
|
|
86
|
+
"import { useOtaUpdates } from '../../ota-client'; export default function Root(useOtaUpdates) { return null; }",
|
|
87
|
+
"import { OtaUpdateGate } from '../../ota-client'; export default function Root() { const OtaUpdateGate = CustomGate; return null; }",
|
|
88
|
+
])('rejects an unsafe root before patching: %s', (source) => {
|
|
89
|
+
expect(() => patch(source)).toThrow('Cannot automatically connect');
|
|
90
|
+
});
|
|
91
|
+
it('preserves CRLF and function directives', () => {
|
|
92
|
+
const result = patch('export default function Root() {\r\n "use strict";\r\n return null;\r\n}\r\n');
|
|
93
|
+
expect(result).toContain('"use strict";\r\n const otaUpdates');
|
|
94
|
+
expect(result.replaceAll('\r\n', '')).not.toContain('\n');
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
describe('root selection', () => {
|
|
99
|
+
function fixture(files: Record<string, string>) {
|
|
100
|
+
const appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ota-root-hook-')); roots.push(appRoot);
|
|
101
|
+
for (const [name, source] of Object.entries(files)) { fs.mkdirSync(path.dirname(path.join(appRoot, name)), { recursive: true }); fs.writeFileSync(path.join(appRoot, name), source); }
|
|
102
|
+
return appRoot;
|
|
103
|
+
}
|
|
104
|
+
const component = 'export default function Root() { return null; }';
|
|
105
|
+
it('prefers src/app and patches all its platform roots only', () => {
|
|
106
|
+
const appRoot = fixture({ 'src/app/_layout.tsx': component, 'src/app/_layout.ios.tsx': component, 'app/_layout.tsx': 'unsupported' });
|
|
107
|
+
const result = planOtaRootHook({ appRoot, originalEntry: 'expo-router/entry' });
|
|
108
|
+
expect(result.files.map((file: string[]) => file[0])).toEqual(['src/app/_layout.tsx', 'src/app/_layout.ios.tsx']);
|
|
109
|
+
expect(result.warnings).toEqual([]);
|
|
110
|
+
expect(fs.readFileSync(path.join(appRoot, 'src/app/_layout.tsx'), 'utf8')).toBe(component);
|
|
111
|
+
});
|
|
112
|
+
it('supports standard App fallback and warns for unknown custom entry', () => {
|
|
113
|
+
const appRoot = fixture({ 'App.tsx': component });
|
|
114
|
+
expect(planOtaRootHook({ appRoot, originalEntry: '__platform_default__' }).files).toHaveLength(1);
|
|
115
|
+
expect(planOtaRootHook({ appRoot, originalEntry: './entry.js' }).warnings).toHaveLength(1);
|
|
116
|
+
fs.writeFileSync(path.join(appRoot, 'index.android.js'), 'custom registration');
|
|
117
|
+
expect(planOtaRootHook({ appRoot, originalEntry: '__platform_default__' }).files).toHaveLength(0);
|
|
118
|
+
});
|
|
119
|
+
it('does not patch ignored app root when src/app exists without a layout', () => {
|
|
120
|
+
const appRoot = fixture({ 'src/app/index.tsx': component, 'app/_layout.tsx': component });
|
|
121
|
+
expect(planOtaRootHook({ appRoot, originalEntry: 'expo-router/entry' }).warnings).toHaveLength(1);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createUpdateController } from '../../templates/expo-app/ota-client/model/update-controller.js';
|
|
3
|
+
|
|
4
|
+
function manifest(id = 'update-a', delivery = 'manual', action?: string) {
|
|
5
|
+
return { id, extra: { updatePolicy: { schemaVersion: 1, policyVersion: 1, delivery,
|
|
6
|
+
...(action ? { guard: { action, payload: { message: 'Please update' } } } : {}) } } };
|
|
7
|
+
}
|
|
8
|
+
function fixture() {
|
|
9
|
+
let clock = 0;
|
|
10
|
+
const deps = {
|
|
11
|
+
enabled: true, start: vi.fn(),
|
|
12
|
+
identity: vi.fn(async () => ({ installationId: 'installation', deviceId: 'device' })),
|
|
13
|
+
check: vi.fn(async (): Promise<unknown> => ({ isAvailable: true, manifest: manifest() })),
|
|
14
|
+
fetch: vi.fn(async (): Promise<unknown> => ({ isNew: true, manifest: manifest() })),
|
|
15
|
+
reload: vi.fn(async () => undefined), openStore: vi.fn(async () => undefined),
|
|
16
|
+
isActive: vi.fn(() => true), now: () => clock,
|
|
17
|
+
};
|
|
18
|
+
const client = createUpdateController(deps);
|
|
19
|
+
const owner = Symbol('root');
|
|
20
|
+
const configure = (value: Record<string, unknown> = {}) => client.configure(owner, value);
|
|
21
|
+
return { deps, client, configure, owner, advance: () => { clock += 60000; } };
|
|
22
|
+
}
|
|
23
|
+
function deferred<T>() {
|
|
24
|
+
let resolve!: (value: T) => void;
|
|
25
|
+
const promise = new Promise<T>(r => { resolve = r; });
|
|
26
|
+
return { promise, resolve };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe('OTA lifecycle policy and operations', () => {
|
|
30
|
+
it('keeps manual checks separate from download and reload, initializing identity first', async () => {
|
|
31
|
+
const f = fixture();
|
|
32
|
+
const identity = deferred<{ installationId: string; deviceId: string }>();
|
|
33
|
+
f.deps.identity.mockReturnValue(identity.promise);
|
|
34
|
+
const checking = f.client.check();
|
|
35
|
+
await vi.waitFor(() => expect(f.deps.identity).toHaveBeenCalledOnce());
|
|
36
|
+
expect(f.deps.check).not.toHaveBeenCalled();
|
|
37
|
+
identity.resolve({ installationId: 'installation', deviceId: 'device' });
|
|
38
|
+
await checking;
|
|
39
|
+
expect(f.client.getSnapshot()).toMatchObject({ available: true, pending: false, status: 'idle' });
|
|
40
|
+
expect(f.deps.fetch).not.toHaveBeenCalled();
|
|
41
|
+
await f.client.download();
|
|
42
|
+
expect(f.client.getSnapshot()).toMatchObject({ pending: true });
|
|
43
|
+
expect(f.deps.reload).not.toHaveBeenCalled();
|
|
44
|
+
await f.client.reload();
|
|
45
|
+
expect(f.deps.reload).toHaveBeenCalledOnce();
|
|
46
|
+
});
|
|
47
|
+
it('automatically downloads and reloads manual candidates only with the requested flags', async () => {
|
|
48
|
+
const f = fixture(); f.configure({ autoUpdate: true, autoReload: true });
|
|
49
|
+
await f.client.check();
|
|
50
|
+
expect(f.deps.fetch).toHaveBeenCalledOnce(); expect(f.deps.reload).toHaveBeenCalledOnce();
|
|
51
|
+
});
|
|
52
|
+
it('does not repeat a manual fetch when the server withdrew the candidate', async () => {
|
|
53
|
+
const f = fixture();
|
|
54
|
+
await f.client.check();
|
|
55
|
+
f.configure({ autoUpdate: true, autoReload: true });
|
|
56
|
+
f.deps.fetch.mockResolvedValue({ isNew: false, isRollBackToEmbedded: false });
|
|
57
|
+
await f.client.download();
|
|
58
|
+
expect(f.deps.fetch).toHaveBeenCalledOnce();
|
|
59
|
+
expect(f.deps.reload).not.toHaveBeenCalled();
|
|
60
|
+
expect(f.client.getSnapshot().pending).toBe(false);
|
|
61
|
+
});
|
|
62
|
+
it('keeps legacy manifests without policy usable through the manual workflow', async () => {
|
|
63
|
+
const f = fixture(); f.configure({ autoReload: true });
|
|
64
|
+
f.deps.check.mockResolvedValue({ isAvailable: true, manifest: { id: 'legacy' } });
|
|
65
|
+
f.deps.fetch.mockResolvedValue({ isNew: true, manifest: { id: 'legacy' } });
|
|
66
|
+
await f.client.check();
|
|
67
|
+
expect(f.client.getSnapshot()).toMatchObject({ blocked: false, policy: null, available: true });
|
|
68
|
+
expect(f.deps.fetch).not.toHaveBeenCalled();
|
|
69
|
+
await f.client.download(); expect(f.deps.reload).toHaveBeenCalledOnce();
|
|
70
|
+
});
|
|
71
|
+
it('does not guess how to apply a future policy schema', async () => {
|
|
72
|
+
const f = fixture(); f.configure({ autoUpdate: true, autoReload: true });
|
|
73
|
+
const candidate = manifest(); candidate.extra.updatePolicy.schemaVersion = 2;
|
|
74
|
+
f.deps.check.mockResolvedValue({ isAvailable: true, manifest: candidate });
|
|
75
|
+
await f.client.check();
|
|
76
|
+
expect(f.client.getSnapshot()).toMatchObject({ blocked: true, blockReason: 'unsupported-policy' });
|
|
77
|
+
expect(f.deps.fetch).not.toHaveBeenCalled();
|
|
78
|
+
});
|
|
79
|
+
it('honors server background delivery even when autoUpdate is false and never auto-reloads it', async () => {
|
|
80
|
+
const f = fixture(); f.configure({ autoUpdate: false, autoReload: true });
|
|
81
|
+
f.deps.check.mockResolvedValue({ isAvailable: true, manifest: manifest('background', 'background') });
|
|
82
|
+
f.deps.fetch.mockResolvedValue({ isNew: true, manifest: manifest('background', 'background') });
|
|
83
|
+
await f.client.check();
|
|
84
|
+
expect(f.deps.fetch).toHaveBeenCalledOnce(); expect(f.deps.reload).not.toHaveBeenCalled();
|
|
85
|
+
expect(f.client.getSnapshot()).toMatchObject({ pending: true, blocked: false });
|
|
86
|
+
});
|
|
87
|
+
it('automatically downloads forced OTA but keeps a gate until explicitly applied', async () => {
|
|
88
|
+
const f = fixture();
|
|
89
|
+
f.deps.check.mockResolvedValue({ isAvailable: true, manifest: manifest('force', 'manual', 'ota-force-update') });
|
|
90
|
+
f.deps.fetch.mockResolvedValue({ isNew: true, manifest: manifest('force', 'manual', 'ota-force-update') });
|
|
91
|
+
await f.client.check();
|
|
92
|
+
expect(f.client.getSnapshot()).toMatchObject({ blocked: true, blockReason: 'ota-force-update', pending: true });
|
|
93
|
+
expect(f.deps.reload).not.toHaveBeenCalled();
|
|
94
|
+
await f.client.reload(); expect(f.deps.reload).toHaveBeenCalledOnce();
|
|
95
|
+
});
|
|
96
|
+
it('force-store guard cannot be bypassed by download, reload or automatic flags', async () => {
|
|
97
|
+
const f = fixture(); f.configure({ autoUpdate: true, autoReload: true });
|
|
98
|
+
f.deps.check.mockResolvedValue({ isAvailable: true, manifest: manifest('store', 'background', 'ota-force-store-update') });
|
|
99
|
+
await f.client.check();
|
|
100
|
+
expect(f.client.getSnapshot()).toMatchObject({ blocked: true, blockReason: 'ota-force-store-update' });
|
|
101
|
+
expect(f.deps.fetch).not.toHaveBeenCalled();
|
|
102
|
+
await expect(f.client.download()).rejects.toThrow('guard');
|
|
103
|
+
await expect(f.client.reload()).rejects.toThrow();
|
|
104
|
+
await f.client.openStore(); expect(f.deps.openStore).toHaveBeenCalledWith({ message: 'Please update' });
|
|
105
|
+
});
|
|
106
|
+
it('keeps unknown guards closed until an asynchronous handler explicitly allows the candidate', async () => {
|
|
107
|
+
const f = fixture(); f.configure({ autoUpdate: true });
|
|
108
|
+
f.deps.check.mockResolvedValue({ isAvailable: true, manifest: manifest('custom', 'manual', 'login') });
|
|
109
|
+
await f.client.check();
|
|
110
|
+
expect(f.client.getSnapshot()).toMatchObject({ blocked: true }); expect(f.deps.fetch).not.toHaveBeenCalled();
|
|
111
|
+
const decision = deferred<string>();
|
|
112
|
+
f.configure({ guardHandlers: { login: () => decision.promise } });
|
|
113
|
+
const checking = f.client.retry();
|
|
114
|
+
await vi.waitFor(() => expect(f.deps.check).toHaveBeenCalledTimes(2));
|
|
115
|
+
expect(f.client.getSnapshot()).toMatchObject({ blocked: true });
|
|
116
|
+
decision.resolve('allow'); await checking;
|
|
117
|
+
expect(f.client.getSnapshot()).toMatchObject({ blocked: false });
|
|
118
|
+
});
|
|
119
|
+
it('rechecks the fetched manifest guard if delivery changed between check and fetch', async () => {
|
|
120
|
+
const f = fixture(); f.configure({ autoUpdate: true, autoReload: true });
|
|
121
|
+
f.deps.fetch.mockResolvedValue({ isNew: true, manifest: manifest('different', 'manual', 'ota-force-store-update') });
|
|
122
|
+
await f.client.check();
|
|
123
|
+
expect(f.client.getSnapshot()).toMatchObject({ pending: true, blocked: true, blockReason: 'ota-force-store-update', candidate: { manifest: { id: 'different' } } });
|
|
124
|
+
expect(f.deps.reload).not.toHaveBeenCalled();
|
|
125
|
+
await expect(f.client.reload()).rejects.toThrow('guard');
|
|
126
|
+
});
|
|
127
|
+
it('supports rollback to embedded without expecting a manifest', async () => {
|
|
128
|
+
const f = fixture();
|
|
129
|
+
f.deps.check.mockResolvedValue({ isAvailable: false, isRollBackToEmbedded: true });
|
|
130
|
+
f.deps.fetch.mockResolvedValue({ isNew: false, isRollBackToEmbedded: true });
|
|
131
|
+
await f.client.check(); await f.client.download(); await f.client.reload();
|
|
132
|
+
expect(f.client.getSnapshot()).toMatchObject({ candidate: { type: 'rollback', manifest: null }, pending: true });
|
|
133
|
+
expect(f.deps.reload).toHaveBeenCalledOnce();
|
|
134
|
+
});
|
|
135
|
+
it('retries identity failure without performing an anonymous update check', async () => {
|
|
136
|
+
const f = fixture(); f.deps.identity.mockRejectedValueOnce(new Error('storage unavailable'));
|
|
137
|
+
await expect(f.client.check()).rejects.toThrow('storage unavailable');
|
|
138
|
+
expect(f.deps.check).not.toHaveBeenCalled();
|
|
139
|
+
await f.client.retry(); expect(f.deps.identity).toHaveBeenCalledTimes(2); expect(f.deps.check).toHaveBeenCalledOnce();
|
|
140
|
+
});
|
|
141
|
+
it('single-flights identical operations and rejects conflicting operations', async () => {
|
|
142
|
+
const f = fixture(); const response = deferred<unknown>(); f.deps.check.mockReturnValue(response.promise);
|
|
143
|
+
const first = f.client.check(); const second = f.client.check();
|
|
144
|
+
expect(first).toBe(second);
|
|
145
|
+
await expect(f.client.download()).rejects.toThrow('in progress');
|
|
146
|
+
response.resolve({ isAvailable: true, manifest: manifest() }); await first;
|
|
147
|
+
expect(f.deps.check).toHaveBeenCalledOnce();
|
|
148
|
+
});
|
|
149
|
+
it('does not mark a failed download pending and supports retry', async () => {
|
|
150
|
+
const f = fixture(); await f.client.check(); f.deps.fetch.mockRejectedValueOnce(new Error('offline'));
|
|
151
|
+
await expect(f.client.download()).rejects.toThrow('offline');
|
|
152
|
+
expect(f.client.getSnapshot()).toMatchObject({ pending: false, status: 'idle' });
|
|
153
|
+
await f.client.download(); expect(f.client.getSnapshot()).toMatchObject({ pending: true, error: null });
|
|
154
|
+
});
|
|
155
|
+
it('never reloads while the native app is inactive', async () => {
|
|
156
|
+
const f = fixture(); await f.client.check(); await f.client.download(); f.deps.isActive.mockReturnValue(false);
|
|
157
|
+
await expect(f.client.reload()).rejects.toThrow('active'); expect(f.deps.reload).not.toHaveBeenCalled();
|
|
158
|
+
});
|
|
159
|
+
it('automatic checks require an active owner and obey the foreground throttle', async () => {
|
|
160
|
+
const f = fixture(); f.client.automaticCheck(); expect(f.deps.check).not.toHaveBeenCalled();
|
|
161
|
+
f.configure({ autoCheck: true }); f.client.automaticCheck();
|
|
162
|
+
await vi.waitFor(() => expect(f.client.getSnapshot().status).toBe('idle'));
|
|
163
|
+
expect(f.deps.check).toHaveBeenCalledOnce();
|
|
164
|
+
f.client.automaticCheck(); expect(f.deps.check).toHaveBeenCalledOnce();
|
|
165
|
+
f.advance(); f.deps.isActive.mockReturnValue(false); f.client.automaticCheck(); expect(f.deps.check).toHaveBeenCalledOnce();
|
|
166
|
+
f.deps.isActive.mockReturnValue(true); f.client.automaticCheck();
|
|
167
|
+
await vi.waitFor(() => expect(f.deps.check).toHaveBeenCalledTimes(2));
|
|
168
|
+
f.client.removeOwner(f.owner); f.advance(); f.client.automaticCheck(); expect(f.deps.check).toHaveBeenCalledTimes(2);
|
|
169
|
+
});
|
|
170
|
+
it('disabled builds never initialize native update operations', async () => {
|
|
171
|
+
const f = fixture(); const client = createUpdateController({ ...f.deps, enabled: false });
|
|
172
|
+
await client.initialize(); await expect(client.check()).rejects.toThrow('unavailable');
|
|
173
|
+
expect(f.deps.identity).not.toHaveBeenCalled(); expect(f.deps.check).not.toHaveBeenCalled();
|
|
174
|
+
});
|
|
175
|
+
it('preserves pending candidate policy when a later check returns another update', async () => {
|
|
176
|
+
const f = fixture(); await f.client.syncPending({ type: 'new', manifest: manifest('cached', 'manual', 'ota-force-store-update') });
|
|
177
|
+
await f.client.check();
|
|
178
|
+
expect(f.client.getSnapshot()).toMatchObject({ candidate: { manifest: { id: 'cached' } }, blocked: true });
|
|
179
|
+
});
|
|
180
|
+
it('re-evaluates a pending guard on retry after application conditions change', async () => {
|
|
181
|
+
const f = fixture();
|
|
182
|
+
await f.client.syncPending({ type: 'new', manifest: manifest('cached', 'manual', 'login') });
|
|
183
|
+
f.configure({ guardHandlers: { login: async () => 'allow' } });
|
|
184
|
+
await f.client.retry();
|
|
185
|
+
expect(f.client.getSnapshot()).toMatchObject({ candidate: { manifest: { id: 'cached' } }, pending: true, blocked: false });
|
|
186
|
+
});
|
|
187
|
+
it('ignores an old native pending snapshot queued while a newer download completes', async () => {
|
|
188
|
+
const f = fixture(); await f.client.check();
|
|
189
|
+
const fetched = deferred<unknown>(); f.deps.fetch.mockReturnValue(fetched.promise);
|
|
190
|
+
const downloading = f.client.download();
|
|
191
|
+
await vi.waitFor(() => expect(f.deps.fetch).toHaveBeenCalledOnce());
|
|
192
|
+
const syncing = f.client.syncPending({ type: 'new', manifest: manifest('old') });
|
|
193
|
+
fetched.resolve({ isNew: true, manifest: manifest('latest', 'manual', 'ota-force-store-update') });
|
|
194
|
+
await Promise.all([downloading, syncing]);
|
|
195
|
+
expect(f.client.getSnapshot()).toMatchObject({ candidate: { manifest: { id: 'latest' } }, blocked: true, blockReason: 'ota-force-store-update' });
|
|
196
|
+
});
|
|
197
|
+
it('preserves force-store policy after the cached bundle cold-starts with no new update', async () => {
|
|
198
|
+
const f = fixture(); f.deps.check.mockResolvedValue({ isAvailable: false });
|
|
199
|
+
const client = createUpdateController({ ...f.deps, runningCandidate: () => ({ type: 'new', manifest: manifest('running', 'manual', 'ota-force-store-update') }) });
|
|
200
|
+
await client.initialize();
|
|
201
|
+
expect(client.getSnapshot()).toMatchObject({ blocked: true, blockReason: 'ota-force-store-update', pending: false });
|
|
202
|
+
await client.check();
|
|
203
|
+
expect(client.getSnapshot()).toMatchObject({ blocked: true, blockReason: 'ota-force-store-update', available: false });
|
|
204
|
+
expect(f.deps.fetch).not.toHaveBeenCalled();
|
|
205
|
+
});
|
|
206
|
+
it('updates policy when a later native download replaces the pending bundle outside this controller', async () => {
|
|
207
|
+
const f = fixture();
|
|
208
|
+
await f.client.syncPending({ type: 'new', manifest: manifest('old') });
|
|
209
|
+
await f.client.syncPending({ type: 'new', manifest: manifest('new-native-download', 'manual', 'ota-force-store-update') });
|
|
210
|
+
expect(f.client.getSnapshot()).toMatchObject({ candidate: { manifest: { id: 'new-native-download' } }, blocked: true, blockReason: 'ota-force-store-update' });
|
|
211
|
+
await expect(f.client.reload()).rejects.toThrow('guard');
|
|
212
|
+
expect(f.deps.reload).not.toHaveBeenCalled();
|
|
213
|
+
});
|
|
214
|
+
it('does not force a second OTA installation for an already running force-OTA bundle', async () => {
|
|
215
|
+
const f = fixture(); f.deps.check.mockResolvedValue({ isAvailable: false });
|
|
216
|
+
const client = createUpdateController({ ...f.deps, runningCandidate: () => ({ type: 'new', manifest: manifest('running', 'manual', 'ota-force-update') }) });
|
|
217
|
+
await client.initialize(); await client.check();
|
|
218
|
+
expect(client.getSnapshot()).toMatchObject({ blocked: false, pending: false, available: false });
|
|
219
|
+
expect(f.deps.fetch).not.toHaveBeenCalled();
|
|
220
|
+
});
|
|
221
|
+
it('evaluates a running custom guard using the application handler', async () => {
|
|
222
|
+
const f = fixture(); f.deps.check.mockResolvedValue({ isAvailable: false });
|
|
223
|
+
const client = createUpdateController({ ...f.deps, runningCandidate: () => ({ type: 'new', manifest: manifest('running', 'manual', 'login') }) });
|
|
224
|
+
await client.initialize(); expect(client.getSnapshot()).toMatchObject({ blocked: true, blockReason: 'login' });
|
|
225
|
+
const handler = vi.fn(async () => 'allow');
|
|
226
|
+
client.configure(f.owner, { guardHandlers: { login: handler } });
|
|
227
|
+
await client.check();
|
|
228
|
+
expect(handler).toHaveBeenCalledWith(expect.objectContaining({ action: 'login', manifest: expect.objectContaining({ id: 'running' }) }));
|
|
229
|
+
expect(client.getSnapshot()).toMatchObject({ blocked: false, available: false });
|
|
230
|
+
});
|
|
231
|
+
});
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Requires an EMPTY disposable PostgreSQL database owned by its connection role.
|
|
2
|
+
// OTA_TEST_DATABASE_URL=... node scripts/tests/device-analytics-migrations.mjs [--fresh]
|
|
3
|
+
// No environment files, fixed credentials, or CREATE DATABASE privilege are used.
|
|
4
|
+
import assert from 'node:assert/strict';
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
import { Pool } from 'pg';
|
|
9
|
+
|
|
10
|
+
if (!process.env.OTA_TEST_DATABASE_URL) throw new Error('Set OTA_TEST_DATABASE_URL to an empty disposable database');
|
|
11
|
+
if (process.argv.slice(2).some(arg => arg !== '--fresh')) throw new Error('Only --fresh is supported');
|
|
12
|
+
const fresh = process.argv.includes('--fresh');
|
|
13
|
+
const schema = readFileSync(new URL('../../docs/migrations/schema.sql', import.meta.url), 'utf8');
|
|
14
|
+
const migration = readFileSync(new URL('../../docs/migrations/2026-10-22-device-analytics.sql', import.meta.url), 'utf8');
|
|
15
|
+
const versionMigration = readFileSync(new URL('../../docs/migrations/2026-10-22-device-version-metadata.sql', import.meta.url), 'utf8');
|
|
16
|
+
assert.ok(schema.includes(versionMigration.trim()), 'Canonical version metadata SQL must match migration');
|
|
17
|
+
const targetingMigration = readFileSync(new URL('../../docs/migrations/2026-10-22-device-targeting.sql', import.meta.url), 'utf8');
|
|
18
|
+
const activationMigration = readFileSync(new URL('../../docs/migrations/2026-10-22-device-targeting-activation.sql', import.meta.url), 'utf8');
|
|
19
|
+
assert.ok(schema.includes(targetingMigration.trim()), 'Canonical targeting SQL must match migration');
|
|
20
|
+
assert.ok(schema.includes(activationMigration.trim()), 'Canonical activation SQL must match migration');
|
|
21
|
+
const marker = '-- Daily device analytics (2026-10-22).';
|
|
22
|
+
assert.ok(schema.includes(marker), 'Canonical schema must contain the analytics migration marker');
|
|
23
|
+
assert.ok(schema.split(marker)[1].trimStart().startsWith(migration.trim()), 'Canonical analytics SQL must match the standalone migration');
|
|
24
|
+
const pool = new Pool({ connectionString: process.env.OTA_TEST_DATABASE_URL, connectionTimeoutMillis: 5000, statement_timeout: 15000 });
|
|
25
|
+
const event = {
|
|
26
|
+
installationId: randomUUID(), platform: 'ios', channel: 'analytics-upgrade-test', runtimeVersion: 'analytics-upgrade-test',
|
|
27
|
+
eventId: randomUUID(), sequence: 1, observedAt: new Date().toISOString(), updateId: null,
|
|
28
|
+
nativeVersion: '1', nativeBuild: '1', isEmbeddedLaunch: true, isEmergencyLaunch: false,
|
|
29
|
+
};
|
|
30
|
+
const send = async (value) => pool.query('select * from ota_record_heartbeat($1::jsonb)', [JSON.stringify(value)]);
|
|
31
|
+
let installed = false;
|
|
32
|
+
try {
|
|
33
|
+
assert.equal((await pool.query("select count(*)::int as n from pg_class c join pg_namespace n on n.oid=c.relnamespace where n.nspname='public' and c.relkind in ('r','p')")).rows[0].n, 0,
|
|
34
|
+
'Refusing a nonempty OTA database: use an empty disposable database');
|
|
35
|
+
await pool.query(fresh ? schema : schema.split(marker)[0]);
|
|
36
|
+
installed = true;
|
|
37
|
+
let original;
|
|
38
|
+
if (!fresh) {
|
|
39
|
+
await send(event);
|
|
40
|
+
original = (await pool.query('select to_jsonb(s) as state from ota_device_state s where installation_id=$1', [event.installationId])).rows[0].state;
|
|
41
|
+
await pool.query(migration);
|
|
42
|
+
await pool.query(versionMigration);
|
|
43
|
+
}
|
|
44
|
+
const coverage = (await pool.query('select collection_started_at from ota_device_analytics_metadata')).rows[0].collection_started_at.toISOString();
|
|
45
|
+
await pool.query(migration);
|
|
46
|
+
await pool.query(versionMigration);
|
|
47
|
+
assert.equal((await pool.query('select collection_started_at from ota_device_analytics_metadata')).rows[0].collection_started_at.toISOString(), coverage);
|
|
48
|
+
if (!fresh) {
|
|
49
|
+
assert.deepEqual((await pool.query('select to_jsonb(s) as state from ota_device_state s where installation_id=$1', [event.installationId])).rows[0].state, original);
|
|
50
|
+
assert.equal((await pool.query('select count(*)::int as n from ota_device_activity_daily')).rows[0].n, 0);
|
|
51
|
+
assert.equal((await pool.query('select count(*)::int as n from ota_device_activity_cohorts')).rows[0].n, 0);
|
|
52
|
+
let report = (await pool.query('select * from ota_devices_report_v2()')).rows[0].report;
|
|
53
|
+
assert.equal(report.total, 1); assert.equal(report.cohorts.length, 0); assert.equal(report.adoptionCohorts[0].installations, 1);
|
|
54
|
+
await send({ ...event, sequence: 2, eventId: randomUUID() });
|
|
55
|
+
report = (await pool.query('select * from ota_devices_report_v2()')).rows[0].report;
|
|
56
|
+
assert.equal(report.activity.at(-1).activeInstallations, 1);
|
|
57
|
+
assert.equal(report.cohorts.length, 0, 'An existing installation is not a new retention-cohort member');
|
|
58
|
+
}
|
|
59
|
+
await pool.query(targetingMigration);
|
|
60
|
+
await pool.query(activationMigration);
|
|
61
|
+
await pool.query(activationMigration);
|
|
62
|
+
console.log(`PASS: ${fresh ? 'fresh canonical schema' : 'upgrade preserving existing state without backfill'}, SQL parity, and repeat migration preserving collection start.`);
|
|
63
|
+
} finally {
|
|
64
|
+
if (installed) {
|
|
65
|
+
for (const table of ['ota_device_activity_daily', 'ota_device_activity_cohorts', 'ota_device_transitions', 'ota_device_state']) {
|
|
66
|
+
if ((await pool.query('select to_regclass($1) as name', [`public.${table}`])).rows[0].name) {
|
|
67
|
+
await pool.query(`delete from public.${table} where installation_id=$1`, [event.installationId]);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
await pool.end();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
for (const test of ['./device-analytics.mjs', './device-version-metadata.mjs', './device-targeting-activation.mjs', './device-targeting.mjs']) {
|
|
75
|
+
const regression = spawnSync(process.execPath, [new URL(test, import.meta.url).pathname], {
|
|
76
|
+
env: process.env, stdio: 'inherit',
|
|
77
|
+
});
|
|
78
|
+
if (regression.error) throw regression.error;
|
|
79
|
+
if (regression.status !== 0) { process.exitCode = regression.status || 1; break; }
|
|
80
|
+
}
|