@onekeyfe/hd-transport 1.2.10-alpha.2 → 1.2.10-alpha.3

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,436 +0,0 @@
1
- import { isDeepStrictEqual } from 'util';
2
- import { mkdirSync, writeFileSync } from 'fs';
3
- import path from 'path';
4
- import ByteBuffer from 'bytebuffer';
5
- import * as protobuf from 'protobufjs/light';
6
- import Long from 'long';
7
-
8
- import v1 from '@onekeyfe/hd-core/src/data/messages/messages.json';
9
- import legacy from '@onekeyfe/hd-core/src/data/messages/messages_legacy_v1.json';
10
- import v2 from '../messages-protocol-v2.json';
11
- import { parseConfigure, createMessageFromName } from '../src/serialization/protobuf/messages';
12
- import { encode } from '../src/serialization/protobuf/encode';
13
- import { decode } from '../src/serialization/protobuf/decode';
14
- import { installStaticCodecs } from '../src/serialization/protobuf/generated/codecs';
15
- import { ProtocolV1, ProtocolV2 } from '../src/protocols';
16
-
17
- import { patchFeatures } from '@onekeyfe/hd-core/src/utils/patch';
18
- import { fixFeaturesFirmwareVersion } from '@onekeyfe/hd-core/src/utils/deviceFeaturesUtils';
19
- import { buildProtocolV1FeaturesPayload } from '@onekeyfe/hd-core/src/deviceProfile/buildDeviceFeatures';
20
- import {
21
- mapFeaturesToState,
22
- mapProtocolV2DeviceInfoToState,
23
- mapProtocolV2DeviceStatusToState,
24
- } from '@onekeyfe/hd-core/src/device/DeviceStateMapper';
25
- import { DeviceStateStore } from '@onekeyfe/hd-core/src/device/DeviceStateStore';
26
- import { projectFeatures } from '@onekeyfe/hd-core/src/device/DeviceStateProjector';
27
-
28
- jest.mock('@onekeyfe/hd-core/src/data/config', () => ({
29
- getSDKVersion: () => '1.0.0-test',
30
- DEFAULT_DOMAIN: 'https://jssdk.onekey.so/1.0.0-test/',
31
- }));
32
-
33
- const constants = Object.values(Long)
34
- .filter(value => value instanceof Long)
35
- .map(value => ({ value, low: value.low, high: value.high, unsigned: value.unsigned }));
36
- const resetLong = () => {
37
- constants.forEach(({ value, low, high, unsigned }) =>
38
- Object.assign(value, { low, high, unsigned })
39
- );
40
- };
41
- const collectTypes = namespace => [
42
- ...(namespace instanceof protobuf.Type ? [namespace] : []),
43
- ...(namespace.nestedArray || []).flatMap(collectTypes),
44
- ];
45
- const capture = fn => {
46
- try {
47
- return { ok: true, value: fn() };
48
- } catch (error) {
49
- return { ok: false, name: error.name, message: error.message };
50
- }
51
- };
52
-
53
- function seed(type, mode, depth = 0) {
54
- const result = {};
55
- if (depth > 5) return result;
56
- type.fieldsArray.forEach(field => {
57
- if (field.partOf && field.partOf.fieldsArray[0] !== field) return;
58
- if (mode === 'required' && !field.required) return;
59
- if (field.resolvedType instanceof protobuf.Type && !field.required && depth > 2) return;
60
- let value;
61
- if (field.resolvedType instanceof protobuf.Type)
62
- value = seed(field.resolvedType, mode, depth + 1);
63
- else if (field.resolvedType instanceof protobuf.Enum) {
64
- const values = Object.values(field.resolvedType.values);
65
- value = values[mode === 'values' ? Math.min(1, values.length - 1) : 0];
66
- } else if (field.type === 'bytes') value = mode === 'values' ? '00ff' : '';
67
- else if (field.type === 'string') value = mode === 'values' ? 'test-验证' : '';
68
- else if (field.type === 'bool') value = mode === 'values';
69
- else if (field.long) value = mode === 'values' ? '9007199254740993' : '0';
70
- else value = mode === 'values' ? 1 : 0;
71
- result[field.name] = field.repeated ? [value] : value;
72
- });
73
- return result;
74
- }
75
-
76
- function inputCases(type) {
77
- const base = seed(type, 'required');
78
- const cases = [
79
- ['absent', {}],
80
- ['required', base],
81
- ['zeros', seed(type, 'zeros')],
82
- ['values', seed(type, 'values')],
83
- ];
84
- type.fieldsArray.forEach(field => {
85
- const add = (label, value) =>
86
- cases.push([`${field.name}:${label}`, { ...base, [field.name]: value }]);
87
- const scalar = value => (field.repeated ? [value] : value);
88
- add('undefined', undefined);
89
- if (!field.repeated) add('null', null);
90
- let values = [];
91
- if (field.resolvedType instanceof protobuf.Enum) {
92
- values = [
93
- ...Object.entries(field.resolvedType.values).flat(),
94
- -1,
95
- 2147483647,
96
- '0',
97
- 'UNKNOWN_ENUM',
98
- ];
99
- } else if (!field.resolvedType) {
100
- if (field.type === 'bytes')
101
- values = ['', '00', '0', 'zz', Buffer.alloc(0), new Uint8Array([0, 255])];
102
- else if (field.type === 'string') values = [0, 1, false, '', '01'];
103
- else if (field.type === 'bool') values = [false, true, 0, 1, 'false', 'true'];
104
- else if (field.long)
105
- values = [
106
- '0',
107
- '9007199254740991',
108
- '9007199254740993',
109
- '18446744073709551615',
110
- '-9223372036854775808',
111
- 9007199254740992,
112
- ];
113
- else values = [0, -1, 1, '0', '1', '01', 1.5, NaN, Infinity];
114
- }
115
- values.forEach((value, index) => add(`coercion-${index}`, scalar(value)));
116
- if (field.repeated) add('empty-array', []);
117
- if (field.repeated && field.type === 'bytes') add('three-empty-bytes', ['', '', '']);
118
- });
119
- return cases;
120
- }
121
-
122
- // Do not print inputs or wire bytes on failures, even though all data here is synthetic.
123
- function compare(label, oldCall, newCall, reset = true) {
124
- if (reset) resetLong();
125
- const expected = capture(oldCall);
126
- if (reset) resetLong();
127
- const actual = capture(newCall);
128
- if (!isDeepStrictEqual(expected, actual)) throw new Error(`Static protobuf differs: ${label}`);
129
- return expected;
130
- }
131
-
132
- const toBytes = (type, input) => Buffer.from(encode(type, input).toBuffer());
133
- const fromBytes = (type, bytes) => decode(type, ByteBuffer.wrap(bytes));
134
-
135
- afterEach(() => {
136
- resetLong();
137
- jest.restoreAllMocks();
138
- });
139
-
140
- test.each([
141
- ['v1', v1],
142
- ['legacy-v1', legacy],
143
- ['v2', v2],
144
- ])(
145
- '%s matches legacy bytes, own properties, scalar types, malformed input and framing',
146
- (schemaName, schema) => {
147
- const reference = protobuf.Root.fromJSON(schema);
148
- const types = collectTypes(reference);
149
- types.forEach(type => {
150
- type.setup();
151
- type.create();
152
- });
153
- // Baseline functions are ready. Every candidate constructor and codec must now be static.
154
- jest.spyOn(protobuf.Type.prototype, 'setup').mockImplementation(() => {
155
- throw new Error('Dynamic setup');
156
- });
157
- jest.spyOn(protobuf.Type, 'generateConstructor').mockImplementation(() => {
158
- throw new Error('Dynamic constructor');
159
- });
160
- const candidate = parseConfigure(schema);
161
- const stringCandidate = parseConfigure(JSON.stringify(schema));
162
- expect(collectTypes(candidate)).toHaveLength(types.length);
163
- let inputs = 0;
164
- let wires = 0;
165
- let frames = 0;
166
- const rows = [];
167
- types.forEach(type => {
168
- const next = candidate.lookupType(type.fullName);
169
- rows.push({ message: type.fullName, result: 'equal', inputs: inputCases(type).length });
170
- inputCases(type).forEach(([label, input]) => {
171
- const encoded = compare(
172
- `${schemaName}/${type.name}/${label}/encode`,
173
- () => toBytes(type, input),
174
- () => toBytes(next, input)
175
- );
176
- inputs += 1;
177
- if (encoded.ok) {
178
- compare(
179
- `${schemaName}/${type.name}/${label}/decode`,
180
- () => fromBytes(type, encoded.value),
181
- () => fromBytes(next, encoded.value)
182
- );
183
- wires += 1;
184
- }
185
- });
186
- const base = capture(() => toBytes(type, seed(type, 'required')));
187
- if (!base.ok) return;
188
- const checkWire = (label, bytes) => {
189
- compare(
190
- `${schemaName}/${type.name}/${label}`,
191
- () => fromBytes(type, bytes),
192
- () => fromBytes(next, bytes)
193
- );
194
- wires += 1;
195
- };
196
- checkWire('empty-wire', Buffer.alloc(0));
197
- const dense = capture(() => toBytes(type, seed(type, 'values')));
198
- if (dense.ok) {
199
- [0, 1, Math.floor(dense.value.length / 2), dense.value.length - 1]
200
- .filter(length => length >= 0)
201
- .forEach(length => checkWire(`truncated-${length}`, dense.value.subarray(0, length)));
202
- for (let index = 0; index < Math.min(12, dense.value.length); index += 1) {
203
- const bytes = Buffer.from(dense.value);
204
- bytes[index] = (bytes[index] + 2 ** (index % 8)) % 256;
205
- checkWire(`mutation-${index}`, bytes);
206
- }
207
- }
208
- const tail = protobuf.Writer.create()
209
- .uint32(500000 * 8)
210
- .finish();
211
- checkWire('battery-ff-fallback', Buffer.concat([base.value, tail, Buffer.from([255])]));
212
- checkWire(
213
- 'unknown-field',
214
- Buffer.concat([
215
- base.value,
216
- protobuf.Writer.create()
217
- .uint32(500000 * 8 + 2)
218
- .bytes([0, 255, 1])
219
- .finish(),
220
- ])
221
- );
222
- type.fieldsArray.forEach(field => {
223
- if (field.resolvedType instanceof protobuf.Enum) {
224
- const known = Object.values(field.resolvedType.values)[0];
225
- [-1, 2147483647].forEach(unknown => {
226
- const write = value =>
227
- protobuf.Writer.create()
228
- .uint32(field.id * 8)
229
- .int32(value)
230
- .finish();
231
- checkWire(`${field.name}/unknown`, Buffer.concat([base.value, write(unknown)]));
232
- checkWire(
233
- `${field.name}/mixed`,
234
- Buffer.concat([base.value, write(known), write(unknown), write(known)])
235
- );
236
- if (field.repeated) {
237
- const packed = protobuf.Writer.create()
238
- .int32(known)
239
- .int32(unknown)
240
- .int32(known)
241
- .finish();
242
- checkWire(
243
- `${field.name}/packed-mixed`,
244
- Buffer.concat([
245
- base.value,
246
- protobuf.Writer.create()
247
- .uint32(field.id * 8 + 2)
248
- .bytes(packed)
249
- .finish(),
250
- ])
251
- );
252
- }
253
- });
254
- } else if (field.resolvedType instanceof protobuf.Type && !field.repeated) {
255
- const first = capture(() =>
256
- toBytes(field.resolvedType, seed(field.resolvedType, 'values'))
257
- );
258
- const second = capture(() =>
259
- toBytes(field.resolvedType, seed(field.resolvedType, 'required'))
260
- );
261
- if (first.ok && second.ok) {
262
- const wrap = bytes =>
263
- protobuf.Writer.create()
264
- .uint32(field.id * 8 + 2)
265
- .bytes(bytes)
266
- .finish();
267
- checkWire(
268
- `${field.name}/duplicate-message`,
269
- Buffer.concat([base.value, wrap(first.value), wrap(second.value)])
270
- );
271
- }
272
- }
273
- });
274
- const name = type.fullName.slice(1);
275
- const message = capture(() => createMessageFromName(reference, name));
276
- if (message.ok) {
277
- const input = seed(type, 'values');
278
- compare(
279
- `${name}/id`,
280
- () => message.value.messageTypeId,
281
- () => createMessageFromName(candidate, name).messageTypeId
282
- );
283
- compare(
284
- `${name}/v1-envelope`,
285
- () => ProtocolV1.encodeEnvelope(reference, name, input).toBuffer(),
286
- () => ProtocolV1.encodeEnvelope(candidate, name, input).toBuffer()
287
- );
288
- compare(
289
- `${name}/v1-chunks`,
290
- () => ProtocolV1.encodeMessageChunks(reference, name, input),
291
- () => ProtocolV1.encodeMessageChunks(candidate, name, input)
292
- );
293
- if (schemaName === 'v2') {
294
- compare(
295
- `${name}/v2-frame`,
296
- () =>
297
- ProtocolV2.encodeFrame(
298
- { protocolV1: reference, protocolV2: reference },
299
- name,
300
- input,
301
- { seq: 23 }
302
- ),
303
- () =>
304
- ProtocolV2.encodeFrame(
305
- { protocolV1: candidate, protocolV2: candidate },
306
- name,
307
- input,
308
- { seq: 23 }
309
- )
310
- );
311
- }
312
- frames += 1;
313
- }
314
- compare(
315
- `${name}/string-config`,
316
- () => toBytes(next, seed(type, 'required')),
317
- () => toBytes(stringCandidate.lookupType(type.fullName), seed(type, 'required'))
318
- );
319
- });
320
- const reportDirectory = path.resolve(__dirname, '../../../node_modules/.cache/protobuf-static');
321
- mkdirSync(reportDirectory, { recursive: true });
322
- writeFileSync(
323
- path.join(reportDirectory, `${schemaName}.json`),
324
- JSON.stringify({ schemaName, inputs, wires, frames, rows }, null, 2)
325
- );
326
- console.info(
327
- `Static protobuf ${schemaName}: ${types.length} messages, ${inputs} inputs, ${wires} decodes, ${frames} message envelopes; zero differences`
328
- );
329
- },
330
- 120000
331
- );
332
-
333
- test('custom schemas retain reflection support instead of selecting a similar built-in message', () => {
334
- const schema = { nested: { Features: { fields: { custom: { type: 'string', id: 1 } } } } };
335
- const root = parseConfigure(schema);
336
- expect(installStaticCodecs(root)).toBe(false);
337
- expect(
338
- fromBytes(root.lookupType('Features'), toBytes(root.lookupType('Features'), { custom: 'test' }))
339
- ).toStrictEqual({ custom: 'test' });
340
- });
341
-
342
- test.each([
343
- ['v1', v1],
344
- ['legacy-v1', legacy],
345
- ['v2', v2],
346
- ])(
347
- '%s preserves Features compatibility patches, state and projected own properties',
348
- (schemaName, schema) => {
349
- jest.spyOn(Date, 'now').mockReturnValue(1700000000000);
350
- const reference = protobuf.Root.fromJSON(schema).resolveAll();
351
- const candidate = parseConfigure(schema);
352
- const names = schemaName === 'v2' ? ['Features', 'DeviceInfo', 'DeviceStatus'] : ['Features'];
353
- let comparisons = 0;
354
- names.forEach(name => {
355
- const type = reference.lookupType(name);
356
- const next = candidate.lookupType(name);
357
- const pipeline = (decoded, cached, mode) => {
358
- let payload = decoded;
359
- let mapped;
360
- if (name === 'Features') {
361
- const patched = patchFeatures({ type: name, message: decoded }).message;
362
- payload = buildProtocolV1FeaturesPayload(patched, cached?.previous);
363
- payload.unlocked = payload.unlocked ?? true;
364
- payload = fixFeaturesFirmwareVersion(payload);
365
- mapped = mapFeaturesToState(payload);
366
- } else {
367
- mapped =
368
- name === 'DeviceInfo'
369
- ? mapProtocolV2DeviceInfoToState(decoded, mode)
370
- : mapProtocolV2DeviceStatusToState(decoded);
371
- }
372
- const store = new DeviceStateStore(cached?.state);
373
- const updated = store.update(mapped, 'initialize');
374
- return { payload, mapped, ...updated, projected: projectFeatures(updated.state) };
375
- };
376
- const dense = toBytes(type, seed(type, 'values'));
377
- const initial = pipeline(fromBytes(type, dense), undefined, 'normal');
378
- const cache = { state: initial.state, previous: initial.projected };
379
- const cases = inputCases(type);
380
- const populated = seed(type, 'values');
381
- type.fieldsArray.forEach(field => {
382
- const omitted = { ...populated };
383
- delete omitted[field.name];
384
- cases.push([`${field.name}/omitted`, omitted]);
385
- });
386
- cases.forEach(([label, input]) => {
387
- const encoded = capture(() => toBytes(type, input));
388
- if (!encoded.ok) return;
389
- [undefined, cache].forEach(cached => {
390
- ['normal', 'bootloader'].forEach(mode => {
391
- compare(
392
- `${schemaName}/${name}/${label}/pipeline/${mode}/${!!cached}`,
393
- () => pipeline(fromBytes(type, encoded.value), cached, mode),
394
- () => pipeline(fromBytes(next, encoded.value), cached, mode)
395
- );
396
- comparisons += 1;
397
- });
398
- });
399
- });
400
- });
401
- console.info(
402
- `Static protobuf ${schemaName}: ${comparisons} Features pipeline comparisons; zero differences`
403
- );
404
- }
405
- );
406
-
407
- test('retains sequence-dependent Long conversion behavior', () => {
408
- const reference = protobuf.Root.fromJSON(v2).resolveAll();
409
- const candidate = parseConfigure(v2);
410
- const signed = reference.lookupType('CardanoToken');
411
- const unsigned = collectTypes(reference).find(type =>
412
- type.fieldsArray.some(field => field.type === 'uint64' && !field.repeated)
413
- );
414
- const field = unsigned.fieldsArray.find(item => item.type === 'uint64' && !item.repeated);
415
- const bytes = toBytes(signed, {
416
- ...seed(signed, 'required'),
417
- mint_amount: '-9223372036854775808',
418
- });
419
- const sequence = root => {
420
- resetLong();
421
- const before = capture(() => fromBytes(root.lookupType(signed.fullName), bytes));
422
- const encoded = capture(() =>
423
- toBytes(root.lookupType(unsigned.fullName), {
424
- ...seed(unsigned, 'required'),
425
- [field.name]: '-9223372036854775808',
426
- })
427
- );
428
- const after = capture(() => fromBytes(root.lookupType(signed.fullName), bytes));
429
- return { before, encoded, after };
430
- };
431
- compare(
432
- 'Long mutation sequence',
433
- () => sequence(reference),
434
- () => sequence(candidate)
435
- );
436
- });
@@ -1,103 +0,0 @@
1
- // Run after lerna run build, with --disallow-code-generation-from-strings.
2
- const assert = require('assert');
3
- const path = require('path');
4
- const vm = require('vm');
5
- const { readFileSync } = require('fs');
6
- const { build } = require('tsup');
7
- const protobuf = require('protobufjs/light');
8
- const { default: transport } = require('../dist');
9
-
10
- const v1 = require('../../core/src/data/messages/messages.json');
11
- const legacy = require('../../core/src/data/messages/messages_legacy_v1.json');
12
- const v2 = require('../messages-protocol-v2.json');
13
-
14
- const schemas = [v1, legacy, v2];
15
- function collectTypes(namespace) {
16
- return [
17
- ...(namespace instanceof protobuf.Type ? [namespace] : []),
18
- ...(namespace.nestedArray || []).flatMap(collectTypes),
19
- ];
20
- }
21
- let blocked = 0;
22
- const dynamic = () => {
23
- blocked += 1;
24
- throw new Error('Unexpected dynamic protobuf setup');
25
- };
26
- protobuf.Type.prototype.setup = dynamic;
27
- protobuf.Type.generateConstructor = dynamic;
28
- let count = 0;
29
- for (const schema of schemas) {
30
- const root = transport.parseConfigure(schema);
31
- for (const type of collectTypes(root)) {
32
- // Missing required fields can throw; no constructor or codec may fall back to codegen.
33
- for (const operation of [
34
- () => type.fromObject({}),
35
- () => type.encode(type.create()).finish(),
36
- () => type.decode(new Uint8Array()),
37
- () => type.verify({}),
38
- () => type.toObject(type.create()),
39
- ]) {
40
- try {
41
- operation();
42
- } catch (error) {
43
- if (error instanceof EvalError) throw error;
44
- }
45
- count += 1;
46
- }
47
- }
48
- }
49
- assert.strictEqual(blocked, 0);
50
- console.log(`CSP static protobuf: ${count} operations, no dynamic setup`);
51
-
52
- async function checkBrowser() {
53
- const outDir = path.resolve(__dirname, '../../../node_modules/.cache/protobuf-static/browser');
54
- await build({
55
- entry: { browser: path.resolve(__dirname, '../dist/index.js') },
56
- outDir,
57
- format: ['iife'],
58
- globalName: 'transport',
59
- platform: 'browser',
60
- noExternal: [/.*/],
61
- splitting: false,
62
- silent: true,
63
- config: false,
64
- });
65
- const code = readFileSync(path.join(outDir, 'browser.global.js'), 'utf8');
66
- const context = vm.createContext(
67
- { schemas },
68
- { codeGeneration: { strings: false, wasm: false } }
69
- );
70
- vm.runInContext(code, context);
71
- const operations = vm.runInContext(
72
- `
73
- let count = 0;
74
- function visit(namespace) {
75
- if (namespace.fields) {
76
- if (!Object.hasOwn(namespace, 'encode')) throw Error('Missing static codec');
77
- for (const operation of [
78
- () => namespace.fromObject({}),
79
- () => namespace.encode(namespace.create()).finish(),
80
- () => namespace.decode(new Uint8Array()),
81
- () => namespace.verify({}),
82
- () => namespace.toObject(namespace.create())
83
- ]) {
84
- try { operation(); } catch (error) {
85
- if (error instanceof EvalError) throw error;
86
- }
87
- count += 1;
88
- }
89
- }
90
- for (const child of namespace.nestedArray || []) visit(child);
91
- }
92
- for (const schema of schemas) visit(transport.default.parseConfigure(schema));
93
- count;
94
- `,
95
- context
96
- );
97
- assert.strictEqual(operations, count);
98
- console.log(`Browser CSP: ${operations} operations, ${code.length} bytes before minification`);
99
- }
100
- checkBrowser().catch(error => {
101
- console.error(error.message);
102
- process.exitCode = 1;
103
- });
@@ -1,85 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const protobuf = require('protobufjs/light');
4
- const Long = require('long');
5
-
6
- protobuf.util.Long = Long;
7
- protobuf.configure();
8
-
9
- const packageRoot = path.resolve(__dirname, '..');
10
- const outputDirectory = path.join(packageRoot, 'src/serialization/protobuf/generated');
11
- const schemaPaths = [
12
- '../core/src/data/messages/messages.json',
13
- '../core/src/data/messages/messages_legacy_v1.json',
14
- 'messages-protocol-v2.json',
15
- 'src/serialization/protobuf/legacy-protocol-info.json',
16
- ];
17
- const methods = ['encode', 'decode', 'verify', 'fromObject', 'toObject'];
18
- const factories = new Map();
19
- const registrations = [];
20
-
21
- function collectTypes(namespace) {
22
- return [
23
- ...(namespace instanceof protobuf.Type ? [namespace] : []),
24
- ...(namespace.nestedArray || []).flatMap(collectTypes),
25
- ];
26
- }
27
-
28
- for (const schemaPath of schemaPaths) {
29
- const schema = JSON.parse(fs.readFileSync(path.join(packageRoot, schemaPath), 'utf8'));
30
- const root = protobuf.Root.fromJSON(schema);
31
- // Capture before resolution, which can normalize field options in place.
32
- const signature = JSON.stringify(root.toJSON());
33
- const registrationsForSchema = [];
34
- for (const type of collectTypes(root)) {
35
- type.setup();
36
- const source = [
37
- `type.ctor = ${type.ctor.toString()};`,
38
- 'const types = type.fieldsArray.map(field => field.resolvedType);',
39
- ...methods.map(method => `type.${method} = ${type[method].toString()};`),
40
- ].join('\n');
41
- if (!factories.has(source)) factories.set(source, factories.size);
42
- registrationsForSchema.push([type.fullName, factories.get(source)]);
43
- }
44
- registrations.push({ signature, types: registrationsForSchema });
45
- }
46
-
47
- // Keep the exact generated algorithms, including legacy conversion quirks.
48
- const source = [
49
- '// @generated by scripts/protobuf-static.js. DO NOT EDIT.',
50
- `const { Reader, Writer, util } = require('protobufjs/minimal');`,
51
- 'const factories = [',
52
- ...Array.from(factories.keys(), body => `function(type) {\n${body}\n},`),
53
- '];',
54
- `const schemas = ${JSON.stringify(registrations)};`,
55
- 'exports.installStaticCodecs = function(root) {',
56
- ' const signature = JSON.stringify(root.toJSON());',
57
- ' const schema = schemas.find(candidate => candidate.signature === signature);',
58
- ' if (!schema) return false;',
59
- ' for (const [name, factory] of schema.types) factories[factory](root.lookupType(name));',
60
- ' return true;',
61
- '};',
62
- '',
63
- ].join('\n');
64
- const declaration = [
65
- '// @generated by scripts/protobuf-static.js. DO NOT EDIT.',
66
- "import type { Root } from 'protobufjs/light';",
67
- 'export declare function installStaticCodecs(root: Root): boolean;',
68
- '',
69
- ].join('\n');
70
-
71
- for (const [name, content] of [
72
- ['codecs.js', source],
73
- ['codecs.d.ts', declaration],
74
- ]) {
75
- const destination = path.join(outputDirectory, name);
76
- if (process.argv.includes('--check')) {
77
- if (!fs.existsSync(destination) || fs.readFileSync(destination, 'utf8') !== content) {
78
- throw new Error(`Static protobuf is stale: run yarn update-protobuf:static (${name})`);
79
- }
80
- } else {
81
- fs.mkdirSync(outputDirectory, { recursive: true });
82
- fs.writeFileSync(destination, content);
83
- }
84
- }
85
- console.log(`Static protobuf: ${registrations.length} schemas, ${factories.size} shared codecs`);
@@ -1,3 +0,0 @@
1
- // @generated by scripts/protobuf-static.js. DO NOT EDIT.
2
- import type { Root } from 'protobufjs/light';
3
- export declare function installStaticCodecs(root: Root): boolean;