@posthog/browser 0.1.1 → 0.3.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.
Files changed (73) hide show
  1. package/ARCHITECTURE.md +28 -22
  2. package/README.md +94 -29
  3. package/dist/analytics-api.d.ts +32 -0
  4. package/dist/analytics-api.js +18 -0
  5. package/dist/analytics-api.mjs +1 -0
  6. package/dist/analytics-buffer.d.ts +3 -3
  7. package/dist/analytics-buffer.js +2 -161
  8. package/dist/analytics-buffer.mjs +2 -161
  9. package/dist/analytics-extension.d.ts +87 -0
  10. package/dist/analytics-extension.js +649 -0
  11. package/dist/analytics-extension.mjs +611 -0
  12. package/dist/analytics-internal.d.ts +33 -18
  13. package/dist/analytics-options.d.ts +7 -2
  14. package/dist/analytics-options.js +38 -1
  15. package/dist/analytics-options.mjs +17 -1
  16. package/dist/analytics-properties.d.ts +12 -0
  17. package/dist/analytics-properties.js +88 -0
  18. package/dist/analytics-properties.mjs +46 -0
  19. package/dist/analytics-session-properties.d.ts +12 -0
  20. package/dist/analytics-session-properties.js +84 -0
  21. package/dist/analytics-session-properties.mjs +46 -0
  22. package/dist/analytics.d.ts +4 -3
  23. package/dist/autocapture.d.ts +2 -2
  24. package/dist/autocapture.js +21 -10
  25. package/dist/autocapture.mjs +21 -10
  26. package/dist/automatic-analytics.d.ts +2 -2
  27. package/dist/browser-client.d.ts +44 -4
  28. package/dist/capture-properties.d.ts +15 -0
  29. package/dist/capture-properties.js +101 -0
  30. package/dist/capture-properties.mjs +57 -0
  31. package/dist/capture-v1.js +7 -19
  32. package/dist/capture-v1.mjs +1 -13
  33. package/dist/core.d.ts +7 -5
  34. package/dist/extensions/registry.d.ts +42 -7
  35. package/dist/extensions/registry.js +194 -37
  36. package/dist/extensions/registry.mjs +194 -37
  37. package/dist/flags-token.d.ts +4 -4
  38. package/dist/flags.js +15 -2
  39. package/dist/flags.mjs +15 -2
  40. package/dist/immutable.d.ts +1 -0
  41. package/dist/immutable.js +46 -0
  42. package/dist/immutable.mjs +8 -0
  43. package/dist/index.d.ts +7 -5
  44. package/dist/index.js +3 -67
  45. package/dist/index.mjs +3 -67
  46. package/dist/key-value-store.d.ts +21 -0
  47. package/dist/key-value-store.js +117 -0
  48. package/dist/key-value-store.mjs +72 -0
  49. package/dist/logs-internal.d.ts +2 -2
  50. package/dist/logs.js +5 -2
  51. package/dist/logs.mjs +5 -2
  52. package/dist/person-processing.d.ts +11 -0
  53. package/dist/person-processing.js +84 -0
  54. package/dist/person-processing.mjs +37 -0
  55. package/dist/posthog.d.ts +4 -3
  56. package/dist/posthog.js +154 -353
  57. package/dist/posthog.mjs +154 -353
  58. package/dist/root-composition.d.ts +11 -0
  59. package/dist/root-composition.js +138 -0
  60. package/dist/root-composition.mjs +100 -0
  61. package/dist/state.d.ts +6 -0
  62. package/dist/state.js +50 -56
  63. package/dist/state.mjs +50 -56
  64. package/dist/surveys-extension.js +11 -6
  65. package/dist/surveys-extension.mjs +11 -6
  66. package/dist/surveys-internal.d.ts +3 -2
  67. package/dist/types.d.ts +13 -19
  68. package/dist/utf8.d.ts +1 -0
  69. package/dist/utf8.js +52 -0
  70. package/dist/utf8.mjs +14 -0
  71. package/dist/version.js +1 -1
  72. package/dist/version.mjs +1 -1
  73. package/package.json +3 -3
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
31
+ const parseMessageProperties = (json)=>{
32
+ const properties = JSON.parse(json, function(_key, value) {
33
+ return null !== value || Array.isArray(this) ? value : void 0;
34
+ });
35
+ if (!isRecord(properties)) throw new Error('Event properties must serialize to an object');
36
+ return properties;
37
+ };
38
+ const snapshotCaptureProperties = (registered, dynamic, properties, options)=>{
39
+ const supplied = {
40
+ ...dynamic,
41
+ ...properties ?? {}
42
+ };
43
+ const set = options.set;
44
+ const setOnce = options.setOnce;
45
+ const uuid = options.uuid;
46
+ const timestamp = options.timestamp;
47
+ if (set) supplied['$set'] = set;
48
+ if (setOnce) supplied['$set_once'] = setOnce;
49
+ const combined = {
50
+ ...registered,
51
+ ...supplied
52
+ };
53
+ if ('function' == typeof combined.toJSON) delete combined.toJSON;
54
+ const overrides = new Set(Object.keys(supplied));
55
+ const json = JSON.stringify(combined);
56
+ const message = parseMessageProperties(json);
57
+ const observed = JSON.parse(json);
58
+ return {
59
+ message,
60
+ observed,
61
+ overrides,
62
+ uuid,
63
+ timestamp
64
+ };
65
+ };
66
+ const applySessionProperties = (snapshot, values)=>{
67
+ const entries = Object.entries(values).filter(([key])=>!snapshot.overrides.has(key));
68
+ if (0 === entries.length) return false;
69
+ const session = Object.fromEntries(entries);
70
+ const message = parseMessageProperties(JSON.stringify(session));
71
+ for (const [key] of entries)delete snapshot.message[key];
72
+ snapshot.message = {
73
+ ...snapshot.message,
74
+ ...message
75
+ };
76
+ snapshot.observed = {
77
+ ...snapshot.observed,
78
+ ...session
79
+ };
80
+ return true;
81
+ };
82
+ const unavoidableProperties = (snapshot, metadata)=>({
83
+ ...Object.fromEntries(Object.entries(snapshot.message).filter(([key])=>snapshot.overrides.has(key))),
84
+ ...metadata
85
+ });
86
+ __webpack_require__.d(__webpack_exports__, {}, {
87
+ applySessionProperties: applySessionProperties,
88
+ snapshotCaptureProperties: snapshotCaptureProperties,
89
+ unavoidableProperties: unavoidableProperties
90
+ });
91
+ exports.applySessionProperties = __webpack_exports__.applySessionProperties;
92
+ exports.snapshotCaptureProperties = __webpack_exports__.snapshotCaptureProperties;
93
+ exports.unavoidableProperties = __webpack_exports__.unavoidableProperties;
94
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
95
+ "applySessionProperties",
96
+ "snapshotCaptureProperties",
97
+ "unavoidableProperties"
98
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
99
+ Object.defineProperty(exports, '__esModule', {
100
+ value: true
101
+ });
@@ -0,0 +1,57 @@
1
+ const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
2
+ const parseMessageProperties = (json)=>{
3
+ const properties = JSON.parse(json, function(_key, value) {
4
+ return null !== value || Array.isArray(this) ? value : void 0;
5
+ });
6
+ if (!isRecord(properties)) throw new Error('Event properties must serialize to an object');
7
+ return properties;
8
+ };
9
+ const snapshotCaptureProperties = (registered, dynamic, properties, options)=>{
10
+ const supplied = {
11
+ ...dynamic,
12
+ ...properties ?? {}
13
+ };
14
+ const set = options.set;
15
+ const setOnce = options.setOnce;
16
+ const uuid = options.uuid;
17
+ const timestamp = options.timestamp;
18
+ if (set) supplied['$set'] = set;
19
+ if (setOnce) supplied['$set_once'] = setOnce;
20
+ const combined = {
21
+ ...registered,
22
+ ...supplied
23
+ };
24
+ if ('function' == typeof combined.toJSON) delete combined.toJSON;
25
+ const overrides = new Set(Object.keys(supplied));
26
+ const json = JSON.stringify(combined);
27
+ const message = parseMessageProperties(json);
28
+ const observed = JSON.parse(json);
29
+ return {
30
+ message,
31
+ observed,
32
+ overrides,
33
+ uuid,
34
+ timestamp
35
+ };
36
+ };
37
+ const applySessionProperties = (snapshot, values)=>{
38
+ const entries = Object.entries(values).filter(([key])=>!snapshot.overrides.has(key));
39
+ if (0 === entries.length) return false;
40
+ const session = Object.fromEntries(entries);
41
+ const message = parseMessageProperties(JSON.stringify(session));
42
+ for (const [key] of entries)delete snapshot.message[key];
43
+ snapshot.message = {
44
+ ...snapshot.message,
45
+ ...message
46
+ };
47
+ snapshot.observed = {
48
+ ...snapshot.observed,
49
+ ...session
50
+ };
51
+ return true;
52
+ };
53
+ const unavoidableProperties = (snapshot, metadata)=>({
54
+ ...Object.fromEntries(Object.entries(snapshot.message).filter(([key])=>snapshot.overrides.has(key))),
55
+ ...metadata
56
+ });
57
+ export { applySessionProperties, snapshotCaptureProperties, unavoidableProperties };
@@ -40,6 +40,7 @@ __webpack_require__.d(__webpack_exports__, {
40
40
  const external_analytics_internal_js_namespaceObject = require("./analytics-internal.js");
41
41
  const external_id_js_namespaceObject = require("./id.js");
42
42
  const external_named_error_js_namespaceObject = require("./named-error.js");
43
+ const external_utf8_js_namespaceObject = require("./utf8.js");
43
44
  const RETRYABLE_STATUSES = [
44
45
  408,
45
46
  500,
@@ -73,19 +74,6 @@ const failedResult = (events, error, statusCode = 0)=>({
73
74
  error,
74
75
  terminalError: error
75
76
  });
76
- const utf8Bytes = (value)=>{
77
- let bytes = 0;
78
- for(let index = 0; index < value.length; index++){
79
- const code = value.charCodeAt(index);
80
- if (code < 0x80) bytes++;
81
- else if (code < 0x800) bytes += 2;
82
- else if (code >= 0xd800 && code <= 0xdbff && value.charCodeAt(index + 1) >= 0xdc00) {
83
- bytes += 4;
84
- index++;
85
- } else bytes += 3;
86
- }
87
- return bytes;
88
- };
89
77
  const prepareEvents = (messages)=>messages.map((source)=>{
90
78
  const event = buildCaptureV1Event(source);
91
79
  const json = JSON.stringify(event);
@@ -94,13 +82,13 @@ const prepareEvents = (messages)=>messages.map((source)=>{
94
82
  event,
95
83
  uuid: event.uuid,
96
84
  json,
97
- bytes: utf8Bytes(json)
85
+ bytes: (0, external_utf8_js_namespaceObject.utf8Bytes)(json)
98
86
  };
99
87
  });
100
88
  const serializeEnvelope = (createdAt, events)=>`{"created_at":${JSON.stringify(createdAt)},"batch":[${events.map(({ json })=>json).join(',')}]}`;
101
89
  const partitionEvents = (events, createdAt, maxBatchEvents, targetBatchBytes)=>{
102
90
  const batches = [];
103
- const emptyBytes = utf8Bytes(serializeEnvelope(createdAt, []));
91
+ const emptyBytes = (0, external_utf8_js_namespaceObject.utf8Bytes)(serializeEnvelope(createdAt, []));
104
92
  let batch = [];
105
93
  let bytes = emptyBytes;
106
94
  for (const event of events){
@@ -356,14 +344,14 @@ const attemptOnce = async (runtime, events, libraryVersion, createdAt, requestId
356
344
  'PostHog-Request-Timestamp': isoNow(now)
357
345
  };
358
346
  let requestBody = body;
359
- if (compressionEnabled && utf8Bytes(body) >= compressionThresholdBytes) {
347
+ if (compressionEnabled && (0, external_utf8_js_namespaceObject.utf8Bytes)(body) >= compressionThresholdBytes) {
360
348
  const compressed = await compressWithDeadline(body, Math.max(1, Math.min(compressionTimeoutMs, remainingTime())), signal, compress);
361
349
  if (signal?.aborted || !canContinue(continuationCheck)) return [
362
350
  failedResult(events, cancellationError()),
363
351
  events,
364
352
  void 0
365
353
  ];
366
- if (compressed && compressed.size < utf8Bytes(body)) {
354
+ if (compressed && compressed.size < (0, external_utf8_js_namespaceObject.utf8Bytes)(body)) {
367
355
  requestBody = compressed;
368
356
  headers['Content-Encoding'] = 'gzip';
369
357
  }
@@ -632,14 +620,14 @@ const sendCaptureV1TeardownBatches = (runtime, messages, libraryVersion, options
632
620
  const createdAt = isoNow(now);
633
621
  const batch = [];
634
622
  let body = serializeEnvelope(createdAt, batch);
635
- let bodyBytes = utf8Bytes(body);
623
+ let bodyBytes = (0, external_utf8_js_namespaceObject.utf8Bytes)(body);
636
624
  while(index + batch.length < prepared.length && batch.length < CAPTURE_V1_MAX_BATCH_EVENTS){
637
625
  const candidate = prepared[index + batch.length];
638
626
  const candidateBody = serializeEnvelope(createdAt, [
639
627
  ...batch,
640
628
  candidate
641
629
  ]);
642
- const candidateBytes = utf8Bytes(candidateBody);
630
+ const candidateBytes = (0, external_utf8_js_namespaceObject.utf8Bytes)(candidateBody);
643
631
  if (candidateBytes > remaining || batch.length > 0 && candidateBytes > CAPTURE_V1_BATCH_TARGET_BYTES) break;
644
632
  batch.push(candidate);
645
633
  body = candidateBody;
@@ -1,6 +1,7 @@
1
1
  import { MAX_ANALYTICS_BATCH_EVENTS } from "./analytics-internal.mjs";
2
2
  import { createId } from "./id.mjs";
3
3
  import { defineErrorName } from "./named-error.mjs";
4
+ import { utf8Bytes } from "./utf8.mjs";
4
5
  const RETRYABLE_STATUSES = [
5
6
  408,
6
7
  500,
@@ -34,19 +35,6 @@ const failedResult = (events, error, statusCode = 0)=>({
34
35
  error,
35
36
  terminalError: error
36
37
  });
37
- const utf8Bytes = (value)=>{
38
- let bytes = 0;
39
- for(let index = 0; index < value.length; index++){
40
- const code = value.charCodeAt(index);
41
- if (code < 0x80) bytes++;
42
- else if (code < 0x800) bytes += 2;
43
- else if (code >= 0xd800 && code <= 0xdbff && value.charCodeAt(index + 1) >= 0xdc00) {
44
- bytes += 4;
45
- index++;
46
- } else bytes += 3;
47
- }
48
- return bytes;
49
- };
50
38
  const prepareEvents = (messages)=>messages.map((source)=>{
51
39
  const event = buildCaptureV1Event(source);
52
40
  const json = JSON.stringify(event);
package/dist/core.d.ts CHANGED
@@ -1,7 +1,9 @@
1
- import type { CorePostHogOptions, PostHog } from './types';
2
- /** Creates a buffer-only client unless analytics delivery is supplied through `extensions`. */
3
- export declare const createPostHog: (options: CorePostHogOptions) => Promise<PostHog>;
1
+ import type { CorePostHogOptions, IPostHog } from './types';
2
+ /** Creates a host with only explicitly supplied products and no automatic product imports. */
3
+ export declare const createPostHog: (options: CorePostHogOptions) => Promise<IPostHog>;
4
4
  export { version } from './version';
5
5
  export { FeatureFlagsExtension, type FeatureFlags } from './flags-token';
6
- export type { BrowserClient, IdentifyInfo, GroupInfo } from './browser-client';
7
- export type { AnalyticsOptions, ApiResponse, BrowserFetch, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, Extension, NewSessionInfo, NewSessionReason, PostHog, RemoteConfig, SendRequestInit, SessionContext, StorageLike, } from './types';
6
+ export type { IPostHogInternal, BrowserExtension, IdentifyInfo, GroupInfo } from './browser-client';
7
+ export type { IAnalytics } from './analytics-api';
8
+ export type { AnalyticsOptions, ApiResponse, BrowserFetch, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, Extension, NewSessionInfo, NewSessionReason, IPostHog, RemoteConfig, SendRequestInit, SessionContext, StorageLike, } from './types';
9
+ export type { PersonProfileMode } from './analytics-options';
@@ -1,16 +1,51 @@
1
1
  import type { Client, Extension } from '@posthog/browser-common';
2
- export declare class ExtensionRegistry {
2
+ export type ExtensionLoader<Host = Client> = (host: Host) => Extension<Host> | Promise<Extension<Host>>;
3
+ type Resolver<Host> = (name: string) => Promise<Extension<Host> | undefined>;
4
+ export interface AutomaticExtension<Host = Client> {
5
+ name: string;
6
+ activate(host: Host, acquire: () => Promise<Extension<Host> | undefined>): void | Promise<unknown>;
7
+ }
8
+ /** Owns product acquisition, installed views and one lifecycle per configured owner. */
9
+ export declare class ExtensionRegistry<Host = Client> {
10
+ private readonly _createClient;
11
+ private readonly _logger;
12
+ private readonly _loaders;
13
+ private readonly _setup;
14
+ private readonly _canInstall;
3
15
  private readonly _records;
16
+ private readonly _retired;
4
17
  private readonly _extensions;
18
+ private readonly _shared;
19
+ private readonly _sharedReservations;
20
+ private readonly _pending;
21
+ private readonly _dependencies;
22
+ private readonly _views;
23
+ private readonly _clients;
24
+ private readonly _publications;
5
25
  private _disposed;
6
- private readonly _createClient;
7
- private readonly _logger;
8
- constructor(createClient: (extensionName: string) => Client, logger: Client['logger']);
9
- get<T extends Extension = Extension>(name: string): T | undefined;
10
- install(extension: Extension): Promise<void>;
11
- rollback(extension: Extension): Promise<void>;
26
+ constructor(_createClient: (extensionName: string, resolve: Resolver<Host>) => Host, _logger: Client['logger'], _loaders?: Readonly<Record<string, ExtensionLoader<Host>>>, _setup?: (extension: Extension<Host>, host: Host) => void | Promise<void>, _canInstall?: () => boolean);
27
+ expose(target: object): void;
28
+ get<T extends Extension<Host> = Extension<Host>>(name: string): T | undefined;
29
+ getShared<T extends Extension = Extension>(name: string): T | undefined;
30
+ resolve(name: string): Promise<Extension<Host> | undefined>;
31
+ activate({ name, activate }: AutomaticExtension<Host>): Promise<void>;
32
+ install(extension: Extension<Host>): Promise<void>;
33
+ private _existingResolution;
34
+ private _reserveInstallation;
35
+ private _bindingEntries;
36
+ private _publishInstallation;
37
+ rollback(extension: Extension<Host>): Promise<void>;
12
38
  flush(reason?: 'flush' | 'shutdown'): Promise<void>;
13
39
  dispose(): Promise<void>;
40
+ private _client;
41
+ private _load;
42
+ private _resolveDependency;
43
+ private _reaches;
14
44
  private _removeRecord;
45
+ private _assertNameAvailable;
46
+ private _publish;
47
+ private _removePublication;
48
+ private _unpublish;
15
49
  private _disposeRecord;
16
50
  }
51
+ export {};
@@ -28,62 +28,139 @@ var __webpack_require__ = {};
28
28
  var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
30
  class ExtensionRegistry {
31
- constructor(createClient, logger){
31
+ constructor(_createClient, _logger, _loaders = {}, _setup = (extension, host)=>extension.setup(host), _canInstall = ()=>true){
32
+ this._createClient = _createClient;
33
+ this._logger = _logger;
34
+ this._loaders = _loaders;
35
+ this._setup = _setup;
36
+ this._canInstall = _canInstall;
32
37
  this._records = new Map();
38
+ this._retired = new WeakSet();
33
39
  this._extensions = new Map();
40
+ this._shared = new Map();
41
+ this._sharedReservations = new Set();
42
+ this._pending = new Map();
43
+ this._dependencies = new Map();
44
+ this._views = new Set();
45
+ this._clients = new Map();
46
+ this._publications = new WeakMap();
34
47
  this._disposed = false;
35
- this._createClient = createClient;
36
- this._logger = logger;
48
+ }
49
+ expose(target) {
50
+ if (this._disposed || this._views.has(target)) return;
51
+ const publications = new Map();
52
+ this._publications.set(target, publications);
53
+ try {
54
+ for (const extension of this._extensions.values())this._publish(target, extension.name);
55
+ } catch (error) {
56
+ for (const name of publications.keys())this._removePublication(target, name);
57
+ this._publications.delete(target);
58
+ throw error;
59
+ }
60
+ this._views.add(target);
37
61
  }
38
62
  get(name) {
39
63
  return this._extensions.get(name);
40
64
  }
41
- async install(extension) {
42
- if (this._disposed) throw new Error('The extension registry is disposed');
43
- const { name } = extension;
44
- const bindings = [
45
- [
46
- name,
47
- extension
48
- ],
49
- ...Object.entries(extension.bindings ?? {})
50
- ];
51
- const names = new Set();
52
- for (const [key] of bindings){
53
- if (!key || names.has(key) || this._extensions.has(key)) throw new Error(`An extension named "${key}" is already installed or the name is invalid`);
54
- names.add(key);
65
+ getShared(name) {
66
+ return this._shared.get(name);
67
+ }
68
+ resolve(name) {
69
+ if (this._disposed || !this._canInstall()) return Promise.resolve(void 0);
70
+ const existing = this._existingResolution(name);
71
+ if (existing) return existing;
72
+ const load = Object.hasOwn(this._loaders, name) ? this._loaders[name] : void 0;
73
+ if (!load) return Promise.resolve(void 0);
74
+ const loading = Promise.resolve().then(()=>this._load(name, load));
75
+ this._pending.set(name, loading);
76
+ loading.then(()=>{
77
+ if (this._pending.get(name) === loading) this._pending.delete(name);
78
+ });
79
+ return loading;
80
+ }
81
+ async activate({ name, activate }) {
82
+ if (this._disposed || !this._canInstall() || this.get(name)) return;
83
+ try {
84
+ const host = this._client(name);
85
+ this._assertNameAvailable(name);
86
+ await activate(host, ()=>this.resolve(name));
87
+ } catch (error) {
88
+ this._logger.error(`Extension "${name}" activation failed`, error);
55
89
  }
56
- const record = [
57
- extension,
58
- false,
59
- [
60
- ...names
61
- ]
62
- ];
63
- this._records.set(name, record);
64
- for (const [key, target] of bindings)this._extensions.set(key, target);
90
+ }
91
+ async install(extension) {
92
+ const installation = this._reserveInstallation(extension);
93
+ const { name, record } = installation;
65
94
  try {
66
- await extension.setup(this._createClient(name));
67
- if (this._disposed || record[1]) throw new Error('The extension registry was disposed during setup');
95
+ const host = this._client(name);
96
+ this._assertNameAvailable(name);
97
+ await this._setup(extension, host);
98
+ this._publishInstallation(installation);
68
99
  } catch (error) {
69
- if (this._records.get(name) === record) this._removeRecord(record);
100
+ this._removeRecord(record);
101
+ record.finish(void 0);
70
102
  try {
71
103
  await this._disposeRecord(record);
72
104
  } catch (disposeError) {
73
105
  this._logger.error('Extension cleanup failed after setup failed', disposeError);
74
106
  }
75
107
  throw error;
108
+ } finally{
109
+ this._dependencies.delete(name);
76
110
  }
77
111
  }
112
+ _existingResolution(name) {
113
+ const installed = this.get(name);
114
+ if (installed) return Promise.resolve(installed);
115
+ return this._pending.get(name) ?? this._records.get(name)?.ready;
116
+ }
117
+ _reserveInstallation(extension) {
118
+ if (this._disposed) throw new Error('The extension registry is disposed');
119
+ if (this._retired.has(extension)) throw new Error('The extension instance has already been disposed');
120
+ const { name } = extension;
121
+ if (!name || this._records.has(name)) throw new Error(`An extension named "${name}" is already installed or the name is invalid`);
122
+ this._assertNameAvailable(name);
123
+ const bindings = this._bindingEntries(extension);
124
+ let finish;
125
+ const record = {
126
+ extension,
127
+ disposed: false,
128
+ sharedNames: bindings.map(([key])=>key),
129
+ ready: new Promise((resolve)=>{
130
+ finish = resolve;
131
+ }),
132
+ finish: (value)=>finish(value)
133
+ };
134
+ this._records.set(name, record);
135
+ for (const [key] of bindings)this._sharedReservations.add(key);
136
+ return {
137
+ name,
138
+ bindings,
139
+ record
140
+ };
141
+ }
142
+ _bindingEntries(extension) {
143
+ const bindings = Object.entries(extension.bindings ?? {});
144
+ for (const [key] of bindings)if (!key || this._sharedReservations.has(key)) throw new Error(`A shared extension named "${key}" is already installed or the name is invalid`);
145
+ return bindings;
146
+ }
147
+ _publishInstallation({ name, bindings, record }) {
148
+ if (this._disposed || record.disposed || !this._canInstall()) throw new Error('Extension installation stopped during setup');
149
+ this._extensions.set(name, record.extension);
150
+ for (const view of this._views)this._publish(view, name);
151
+ for (const [key, target] of bindings)this._shared.set(key, target);
152
+ record.finish(record.extension);
153
+ }
78
154
  async rollback(extension) {
79
155
  const record = this._records.get(extension.name);
80
- if (record?.[0] === extension) {
156
+ if (record?.extension === extension) {
81
157
  this._removeRecord(record);
158
+ record.finish(void 0);
82
159
  await this._disposeRecord(record);
83
160
  }
84
161
  }
85
162
  async flush(reason = 'flush') {
86
- await Promise.all(Array.from(this._records.values()).map(async ([extension])=>{
163
+ await Promise.all(Array.from(this._extensions.values()).map(async (extension)=>{
87
164
  try {
88
165
  await extension.flush?.(reason);
89
166
  } catch (error) {
@@ -96,23 +173,103 @@ class ExtensionRegistry {
96
173
  this._disposed = true;
97
174
  const records = Array.from(this._records.values()).reverse();
98
175
  this._records.clear();
176
+ for (const name of this._extensions.keys())this._unpublish(name);
99
177
  this._extensions.clear();
178
+ this._shared.clear();
179
+ this._sharedReservations.clear();
180
+ this._dependencies.clear();
181
+ this._views.clear();
182
+ this._clients.clear();
100
183
  await Promise.all(records.map(async (record)=>{
184
+ record.finish(void 0);
101
185
  try {
102
186
  await this._disposeRecord(record);
103
187
  } catch (error) {
104
- this._logger.error(`Extension "${record[0].name}" cleanup failed`, error);
188
+ this._logger.error(`Extension "${record.extension.name}" cleanup failed`, error);
105
189
  }
106
190
  }));
107
191
  }
192
+ _client(name) {
193
+ const existing = this._clients.get(name);
194
+ if (void 0 !== existing) return existing;
195
+ const host = this._createClient(name, (target)=>this._resolveDependency(name, target));
196
+ if (!this._disposed) this._clients.set(name, host);
197
+ return host;
198
+ }
199
+ async _load(name, load) {
200
+ try {
201
+ const host = this._client(name);
202
+ this._assertNameAvailable(name);
203
+ const extension = await load(host);
204
+ if (this._disposed || extension.name !== name) {
205
+ await extension.dispose?.();
206
+ if (!this._disposed) throw new Error(`Loader for "${name}" returned extension "${extension.name}"`);
207
+ return;
208
+ }
209
+ await this.install(extension);
210
+ return this.get(name);
211
+ } catch (error) {
212
+ this._logger.error(`Extension "${name}" loading failed`, error);
213
+ return;
214
+ } finally{
215
+ this._dependencies.delete(name);
216
+ }
217
+ }
218
+ _resolveDependency(owner, target) {
219
+ if (this.get(owner) || this.get(target)) return this.resolve(target);
220
+ if (owner === target || this._reaches(target, owner, new Set())) {
221
+ this._logger.error(`Circular extension dependency: "${owner}" -> "${target}"`, new Error('Circular extension dependency'));
222
+ return Promise.resolve(void 0);
223
+ }
224
+ let dependencies = this._dependencies.get(owner);
225
+ if (!dependencies) this._dependencies.set(owner, dependencies = new Set());
226
+ dependencies.add(target);
227
+ return this.resolve(target);
228
+ }
229
+ _reaches(from, target, visited) {
230
+ if (from === target) return true;
231
+ if (visited.has(from)) return false;
232
+ visited.add(from);
233
+ for (const next of this._dependencies.get(from) ?? [])if (this._reaches(next, target, visited)) return true;
234
+ return false;
235
+ }
108
236
  _removeRecord(record) {
109
- this._records.delete(record[0].name);
110
- for (const name of record[2])this._extensions.delete(name);
237
+ const name = record.extension.name;
238
+ if (this._records.get(name) !== record) return;
239
+ this._records.delete(name);
240
+ this._extensions.delete(name);
241
+ this._unpublish(name);
242
+ for (const key of record.sharedNames){
243
+ this._shared.delete(key);
244
+ this._sharedReservations.delete(key);
245
+ }
246
+ }
247
+ _assertNameAvailable(name) {
248
+ for (const view of this._views)if (name in view) throw new Error(`Extension name "${name}" conflicts with a client capability`);
249
+ }
250
+ _publish(view, name) {
251
+ if (name in view) throw new Error(`Extension name "${name}" conflicts with a client capability`);
252
+ const read = ()=>this.get(name);
253
+ Object.defineProperty(view, name, {
254
+ enumerable: true,
255
+ configurable: true,
256
+ get: read
257
+ });
258
+ this._publications.get(view)?.set(name, read);
259
+ }
260
+ _removePublication(view, name) {
261
+ const read = this._publications.get(view)?.get(name);
262
+ if (read && Object.getOwnPropertyDescriptor(view, name)?.get === read) Reflect.deleteProperty(view, name);
263
+ this._publications.get(view)?.delete(name);
264
+ }
265
+ _unpublish(name) {
266
+ for (const view of this._views)this._removePublication(view, name);
111
267
  }
112
268
  async _disposeRecord(record) {
113
- if (!record[1]) {
114
- record[1] = true;
115
- await record[0].dispose?.();
269
+ if (!record.disposed) {
270
+ record.disposed = true;
271
+ this._retired.add(record.extension);
272
+ await record.extension.dispose?.();
116
273
  }
117
274
  }
118
275
  }